1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2015 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);
224 static void remote_btrace_reset (void);
228 static struct cmd_list_element *remote_cmdlist;
230 /* For "set remote" and "show remote". */
232 static struct cmd_list_element *remote_set_cmdlist;
233 static struct cmd_list_element *remote_show_cmdlist;
235 /* Stub vCont actions support.
237 Each field is a boolean flag indicating whether the stub reports
238 support for the corresponding action. */
240 struct vCont_action_support
249 /* Controls whether GDB is willing to use range stepping. */
251 static int use_range_stepping = 1;
253 #define OPAQUETHREADBYTES 8
255 /* a 64 bit opaque identifier */
256 typedef unsigned char threadref[OPAQUETHREADBYTES];
258 /* About this many threadisds fit in a packet. */
260 #define MAXTHREADLISTRESULTS 32
262 /* Description of the remote protocol state for the currently
263 connected target. This is per-target state, and independent of the
264 selected architecture. */
268 /* A buffer to use for incoming packets, and its current size. The
269 buffer is grown dynamically for larger incoming packets.
270 Outgoing packets may also be constructed in this buffer.
271 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
272 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
277 /* True if we're going through initial connection setup (finding out
278 about the remote side's threads, relocating symbols, etc.). */
281 /* If we negotiated packet size explicitly (and thus can bypass
282 heuristics for the largest packet size that will not overflow
283 a buffer in the stub), this will be set to that packet size.
284 Otherwise zero, meaning to use the guessed size. */
285 long explicit_packet_size;
287 /* remote_wait is normally called when the target is running and
288 waits for a stop reply packet. But sometimes we need to call it
289 when the target is already stopped. We can send a "?" packet
290 and have remote_wait read the response. Or, if we already have
291 the response, we can stash it in BUF and tell remote_wait to
292 skip calling getpkt. This flag is set when BUF contains a
293 stop reply packet and the target is not waiting. */
294 int cached_wait_status;
296 /* True, if in no ack mode. That is, neither GDB nor the stub will
297 expect acks from each other. The connection is assumed to be
301 /* True if we're connected in extended remote mode. */
304 /* True if we resumed the target and we're waiting for the target to
305 stop. In the mean time, we can't start another command/query.
306 The remote server wouldn't be ready to process it, so we'd
307 timeout waiting for a reply that would never come and eventually
308 we'd close the connection. This can happen in asynchronous mode
309 because we allow GDB commands while the target is running. */
310 int waiting_for_stop_reply;
312 /* The status of the stub support for the various vCont actions. */
313 struct vCont_action_support supports_vCont;
315 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
316 responded to that. */
319 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
320 remote_open knows that we don't have a file open when the program
322 struct serial *remote_desc;
324 /* These are the threads which we last sent to the remote system. The
325 TID member will be -1 for all or -2 for not sent yet. */
326 ptid_t general_thread;
327 ptid_t continue_thread;
329 /* This is the traceframe which we last selected on the remote system.
330 It will be -1 if no traceframe is selected. */
331 int remote_traceframe_number;
333 char *last_pass_packet;
335 /* The last QProgramSignals packet sent to the target. We bypass
336 sending a new program signals list down to the target if the new
337 packet is exactly the same as the last we sent. IOW, we only let
338 the target know about program signals list changes. */
339 char *last_program_signals_packet;
341 enum gdb_signal last_sent_signal;
345 char *finished_object;
346 char *finished_annex;
347 ULONGEST finished_offset;
349 /* Should we try the 'ThreadInfo' query packet?
351 This variable (NOT available to the user: auto-detect only!)
352 determines whether GDB will use the new, simpler "ThreadInfo"
353 query or the older, more complex syntax for thread queries.
354 This is an auto-detect variable (set to true at each connect,
355 and set to false when the target fails to recognize it). */
356 int use_threadinfo_query;
357 int use_threadextra_query;
359 void (*async_client_callback) (enum inferior_event_type event_type,
361 void *async_client_context;
363 /* This is set to the data address of the access causing the target
364 to stop for a watchpoint. */
365 CORE_ADDR remote_watch_data_address;
367 /* This is non-zero if target stopped for a watchpoint. */
368 int remote_stopped_by_watchpoint_p;
370 threadref echo_nextthread;
371 threadref nextthread;
372 threadref resultthreadlist[MAXTHREADLISTRESULTS];
374 /* The state of remote notification. */
375 struct remote_notif_state *notif_state;
377 /* The branch trace configuration. */
378 struct btrace_config btrace_config;
381 /* Private data that we'll store in (struct thread_info)->private. */
382 struct private_thread_info
389 free_private_thread_info (struct private_thread_info *info)
395 /* This data could be associated with a target, but we do not always
396 have access to the current target when we need it, so for now it is
397 static. This will be fine for as long as only one target is in use
399 static struct remote_state *remote_state;
401 static struct remote_state *
402 get_remote_state_raw (void)
407 /* Allocate a new struct remote_state with xmalloc, initialize it, and
410 static struct remote_state *
411 new_remote_state (void)
413 struct remote_state *result = XCNEW (struct remote_state);
415 /* The default buffer size is unimportant; it will be expanded
416 whenever a larger buffer is needed. */
417 result->buf_size = 400;
418 result->buf = xmalloc (result->buf_size);
419 result->remote_traceframe_number = -1;
420 result->last_sent_signal = GDB_SIGNAL_0;
425 /* Description of the remote protocol for a given architecture. */
429 long offset; /* Offset into G packet. */
430 long regnum; /* GDB's internal register number. */
431 LONGEST pnum; /* Remote protocol register number. */
432 int in_g_packet; /* Always part of G packet. */
433 /* long size in bytes; == register_size (target_gdbarch (), regnum);
435 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
439 struct remote_arch_state
441 /* Description of the remote protocol registers. */
442 long sizeof_g_packet;
444 /* Description of the remote protocol registers indexed by REGNUM
445 (making an array gdbarch_num_regs in size). */
446 struct packet_reg *regs;
448 /* This is the size (in chars) of the first response to the ``g''
449 packet. It is used as a heuristic when determining the maximum
450 size of memory-read and memory-write packets. A target will
451 typically only reserve a buffer large enough to hold the ``g''
452 packet. The size does not include packet overhead (headers and
454 long actual_register_packet_size;
456 /* This is the maximum size (in chars) of a non read/write packet.
457 It is also used as a cap on the size of read/write packets. */
458 long remote_packet_size;
461 /* Utility: generate error from an incoming stub packet. */
463 trace_error (char *buf)
466 return; /* not an error msg */
469 case '1': /* malformed packet error */
470 if (*++buf == '0') /* general case: */
471 error (_("remote.c: error in outgoing packet."));
473 error (_("remote.c: error in outgoing packet at field #%ld."),
474 strtol (buf, NULL, 16));
476 error (_("Target returns error code '%s'."), buf);
480 /* Utility: wait for reply from stub, while accepting "O" packets. */
482 remote_get_noisy_reply (char **buf_p,
485 do /* Loop on reply from remote stub. */
489 QUIT; /* Allow user to bail out with ^C. */
490 getpkt (buf_p, sizeof_buf, 0);
494 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
497 CORE_ADDR from, to, org_to;
499 int adjusted_size = 0;
500 volatile struct gdb_exception ex;
502 p = buf + strlen ("qRelocInsn:");
503 pp = unpack_varlen_hex (p, &ul);
505 error (_("invalid qRelocInsn packet: %s"), buf);
509 unpack_varlen_hex (p, &ul);
514 TRY_CATCH (ex, RETURN_MASK_ALL)
516 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
520 adjusted_size = to - org_to;
522 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
525 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
527 /* Propagate memory errors silently back to the target.
528 The stub may have limited the range of addresses we
529 can write to, for example. */
534 /* Something unexpectedly bad happened. Be verbose so
535 we can tell what, and propagate the error back to the
536 stub, so it doesn't get stuck waiting for a
538 exception_fprintf (gdb_stderr, ex,
539 _("warning: relocating instruction: "));
543 else if (buf[0] == 'O' && buf[1] != 'K')
544 remote_console_output (buf + 1); /* 'O' message from stub */
546 return buf; /* Here's the actual reply. */
551 /* Handle for retreving the remote protocol data from gdbarch. */
552 static struct gdbarch_data *remote_gdbarch_data_handle;
554 static struct remote_arch_state *
555 get_remote_arch_state (void)
557 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
560 /* Fetch the global remote target state. */
562 static struct remote_state *
563 get_remote_state (void)
565 /* Make sure that the remote architecture state has been
566 initialized, because doing so might reallocate rs->buf. Any
567 function which calls getpkt also needs to be mindful of changes
568 to rs->buf, but this call limits the number of places which run
570 get_remote_arch_state ();
572 return get_remote_state_raw ();
576 compare_pnums (const void *lhs_, const void *rhs_)
578 const struct packet_reg * const *lhs = lhs_;
579 const struct packet_reg * const *rhs = rhs_;
581 if ((*lhs)->pnum < (*rhs)->pnum)
583 else if ((*lhs)->pnum == (*rhs)->pnum)
590 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
592 int regnum, num_remote_regs, offset;
593 struct packet_reg **remote_regs;
595 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
597 struct packet_reg *r = ®s[regnum];
599 if (register_size (gdbarch, regnum) == 0)
600 /* Do not try to fetch zero-sized (placeholder) registers. */
603 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
608 /* Define the g/G packet format as the contents of each register
609 with a remote protocol number, in order of ascending protocol
612 remote_regs = alloca (gdbarch_num_regs (gdbarch)
613 * sizeof (struct packet_reg *));
614 for (num_remote_regs = 0, regnum = 0;
615 regnum < gdbarch_num_regs (gdbarch);
617 if (regs[regnum].pnum != -1)
618 remote_regs[num_remote_regs++] = ®s[regnum];
620 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
623 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
625 remote_regs[regnum]->in_g_packet = 1;
626 remote_regs[regnum]->offset = offset;
627 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
633 /* Given the architecture described by GDBARCH, return the remote
634 protocol register's number and the register's offset in the g/G
635 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
636 If the target does not have a mapping for REGNUM, return false,
637 otherwise, return true. */
640 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
641 int *pnum, int *poffset)
644 struct packet_reg *regs;
645 struct cleanup *old_chain;
647 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
649 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
650 old_chain = make_cleanup (xfree, regs);
652 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
654 *pnum = regs[regnum].pnum;
655 *poffset = regs[regnum].offset;
657 do_cleanups (old_chain);
663 init_remote_state (struct gdbarch *gdbarch)
665 struct remote_state *rs = get_remote_state_raw ();
666 struct remote_arch_state *rsa;
668 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
670 /* Use the architecture to build a regnum<->pnum table, which will be
671 1:1 unless a feature set specifies otherwise. */
672 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
673 gdbarch_num_regs (gdbarch),
676 /* Record the maximum possible size of the g packet - it may turn out
678 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
680 /* Default maximum number of characters in a packet body. Many
681 remote stubs have a hardwired buffer size of 400 bytes
682 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
683 as the maximum packet-size to ensure that the packet and an extra
684 NUL character can always fit in the buffer. This stops GDB
685 trashing stubs that try to squeeze an extra NUL into what is
686 already a full buffer (As of 1999-12-04 that was most stubs). */
687 rsa->remote_packet_size = 400 - 1;
689 /* This one is filled in when a ``g'' packet is received. */
690 rsa->actual_register_packet_size = 0;
692 /* Should rsa->sizeof_g_packet needs more space than the
693 default, adjust the size accordingly. Remember that each byte is
694 encoded as two characters. 32 is the overhead for the packet
695 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
696 (``$NN:G...#NN'') is a better guess, the below has been padded a
698 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
699 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
701 /* Make sure that the packet buffer is plenty big enough for
702 this architecture. */
703 if (rs->buf_size < rsa->remote_packet_size)
705 rs->buf_size = 2 * rsa->remote_packet_size;
706 rs->buf = xrealloc (rs->buf, rs->buf_size);
712 /* Return the current allowed size of a remote packet. This is
713 inferred from the current architecture, and should be used to
714 limit the length of outgoing packets. */
716 get_remote_packet_size (void)
718 struct remote_state *rs = get_remote_state ();
719 struct remote_arch_state *rsa = get_remote_arch_state ();
721 if (rs->explicit_packet_size)
722 return rs->explicit_packet_size;
724 return rsa->remote_packet_size;
727 static struct packet_reg *
728 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
730 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
734 struct packet_reg *r = &rsa->regs[regnum];
736 gdb_assert (r->regnum == regnum);
741 static struct packet_reg *
742 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
746 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
748 struct packet_reg *r = &rsa->regs[i];
756 static struct target_ops remote_ops;
758 static struct target_ops extended_remote_ops;
760 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
761 ``forever'' still use the normal timeout mechanism. This is
762 currently used by the ASYNC code to guarentee that target reads
763 during the initial connect always time-out. Once getpkt has been
764 modified to return a timeout indication and, in turn
765 remote_wait()/wait_for_inferior() have gained a timeout parameter
767 static int wait_forever_enabled_p = 1;
769 /* Allow the user to specify what sequence to send to the remote
770 when he requests a program interruption: Although ^C is usually
771 what remote systems expect (this is the default, here), it is
772 sometimes preferable to send a break. On other systems such
773 as the Linux kernel, a break followed by g, which is Magic SysRq g
774 is required in order to interrupt the execution. */
775 const char interrupt_sequence_control_c[] = "Ctrl-C";
776 const char interrupt_sequence_break[] = "BREAK";
777 const char interrupt_sequence_break_g[] = "BREAK-g";
778 static const char *const interrupt_sequence_modes[] =
780 interrupt_sequence_control_c,
781 interrupt_sequence_break,
782 interrupt_sequence_break_g,
785 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
788 show_interrupt_sequence (struct ui_file *file, int from_tty,
789 struct cmd_list_element *c,
792 if (interrupt_sequence_mode == interrupt_sequence_control_c)
793 fprintf_filtered (file,
794 _("Send the ASCII ETX character (Ctrl-c) "
795 "to the remote target to interrupt the "
796 "execution of the program.\n"));
797 else if (interrupt_sequence_mode == interrupt_sequence_break)
798 fprintf_filtered (file,
799 _("send a break signal to the remote target "
800 "to interrupt the execution of the program.\n"));
801 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
802 fprintf_filtered (file,
803 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
804 "the remote target to interrupt the execution "
805 "of Linux kernel.\n"));
807 internal_error (__FILE__, __LINE__,
808 _("Invalid value for interrupt_sequence_mode: %s."),
809 interrupt_sequence_mode);
812 /* This boolean variable specifies whether interrupt_sequence is sent
813 to the remote target when gdb connects to it.
814 This is mostly needed when you debug the Linux kernel: The Linux kernel
815 expects BREAK g which is Magic SysRq g for connecting gdb. */
816 static int interrupt_on_connect = 0;
818 /* This variable is used to implement the "set/show remotebreak" commands.
819 Since these commands are now deprecated in favor of "set/show remote
820 interrupt-sequence", it no longer has any effect on the code. */
821 static int remote_break;
824 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
827 interrupt_sequence_mode = interrupt_sequence_break;
829 interrupt_sequence_mode = interrupt_sequence_control_c;
833 show_remotebreak (struct ui_file *file, int from_tty,
834 struct cmd_list_element *c,
839 /* This variable sets the number of bits in an address that are to be
840 sent in a memory ("M" or "m") packet. Normally, after stripping
841 leading zeros, the entire address would be sent. This variable
842 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
843 initial implementation of remote.c restricted the address sent in
844 memory packets to ``host::sizeof long'' bytes - (typically 32
845 bits). Consequently, for 64 bit targets, the upper 32 bits of an
846 address was never sent. Since fixing this bug may cause a break in
847 some remote targets this variable is principly provided to
848 facilitate backward compatibility. */
850 static unsigned int remote_address_size;
852 /* Temporary to track who currently owns the terminal. See
853 remote_terminal_* for more details. */
855 static int remote_async_terminal_ours_p;
857 /* The executable file to use for "run" on the remote side. */
859 static char *remote_exec_file = "";
862 /* User configurable variables for the number of characters in a
863 memory read/write packet. MIN (rsa->remote_packet_size,
864 rsa->sizeof_g_packet) is the default. Some targets need smaller
865 values (fifo overruns, et.al.) and some users need larger values
866 (speed up transfers). The variables ``preferred_*'' (the user
867 request), ``current_*'' (what was actually set) and ``forced_*''
868 (Positive - a soft limit, negative - a hard limit). */
870 struct memory_packet_config
877 /* Compute the current size of a read/write packet. Since this makes
878 use of ``actual_register_packet_size'' the computation is dynamic. */
881 get_memory_packet_size (struct memory_packet_config *config)
883 struct remote_state *rs = get_remote_state ();
884 struct remote_arch_state *rsa = get_remote_arch_state ();
886 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
887 law?) that some hosts don't cope very well with large alloca()
888 calls. Eventually the alloca() code will be replaced by calls to
889 xmalloc() and make_cleanups() allowing this restriction to either
890 be lifted or removed. */
891 #ifndef MAX_REMOTE_PACKET_SIZE
892 #define MAX_REMOTE_PACKET_SIZE 16384
894 /* NOTE: 20 ensures we can write at least one byte. */
895 #ifndef MIN_REMOTE_PACKET_SIZE
896 #define MIN_REMOTE_PACKET_SIZE 20
901 if (config->size <= 0)
902 what_they_get = MAX_REMOTE_PACKET_SIZE;
904 what_they_get = config->size;
908 what_they_get = get_remote_packet_size ();
909 /* Limit the packet to the size specified by the user. */
911 && what_they_get > config->size)
912 what_they_get = config->size;
914 /* Limit it to the size of the targets ``g'' response unless we have
915 permission from the stub to use a larger packet size. */
916 if (rs->explicit_packet_size == 0
917 && rsa->actual_register_packet_size > 0
918 && what_they_get > rsa->actual_register_packet_size)
919 what_they_get = rsa->actual_register_packet_size;
921 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
922 what_they_get = MAX_REMOTE_PACKET_SIZE;
923 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
924 what_they_get = MIN_REMOTE_PACKET_SIZE;
926 /* Make sure there is room in the global buffer for this packet
927 (including its trailing NUL byte). */
928 if (rs->buf_size < what_they_get + 1)
930 rs->buf_size = 2 * what_they_get;
931 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
934 return what_they_get;
937 /* Update the size of a read/write packet. If they user wants
938 something really big then do a sanity check. */
941 set_memory_packet_size (char *args, struct memory_packet_config *config)
943 int fixed_p = config->fixed_p;
944 long size = config->size;
947 error (_("Argument required (integer, `fixed' or `limited')."));
948 else if (strcmp (args, "hard") == 0
949 || strcmp (args, "fixed") == 0)
951 else if (strcmp (args, "soft") == 0
952 || strcmp (args, "limit") == 0)
958 size = strtoul (args, &end, 0);
960 error (_("Invalid %s (bad syntax)."), config->name);
962 /* Instead of explicitly capping the size of a packet to
963 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
964 instead allowed to set the size to something arbitrarily
966 if (size > MAX_REMOTE_PACKET_SIZE)
967 error (_("Invalid %s (too large)."), config->name);
971 if (fixed_p && !config->fixed_p)
973 if (! query (_("The target may not be able to correctly handle a %s\n"
974 "of %ld bytes. Change the packet size? "),
976 error (_("Packet size not changed."));
978 /* Update the config. */
979 config->fixed_p = fixed_p;
984 show_memory_packet_size (struct memory_packet_config *config)
986 printf_filtered (_("The %s is %ld. "), config->name, config->size);
988 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
989 get_memory_packet_size (config));
991 printf_filtered (_("Packets are limited to %ld bytes.\n"),
992 get_memory_packet_size (config));
995 static struct memory_packet_config memory_write_packet_config =
997 "memory-write-packet-size",
1001 set_memory_write_packet_size (char *args, int from_tty)
1003 set_memory_packet_size (args, &memory_write_packet_config);
1007 show_memory_write_packet_size (char *args, int from_tty)
1009 show_memory_packet_size (&memory_write_packet_config);
1013 get_memory_write_packet_size (void)
1015 return get_memory_packet_size (&memory_write_packet_config);
1018 static struct memory_packet_config memory_read_packet_config =
1020 "memory-read-packet-size",
1024 set_memory_read_packet_size (char *args, int from_tty)
1026 set_memory_packet_size (args, &memory_read_packet_config);
1030 show_memory_read_packet_size (char *args, int from_tty)
1032 show_memory_packet_size (&memory_read_packet_config);
1036 get_memory_read_packet_size (void)
1038 long size = get_memory_packet_size (&memory_read_packet_config);
1040 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1041 extra buffer size argument before the memory read size can be
1042 increased beyond this. */
1043 if (size > get_remote_packet_size ())
1044 size = get_remote_packet_size ();
1049 /* Generic configuration support for packets the stub optionally
1050 supports. Allows the user to specify the use of the packet as well
1051 as allowing GDB to auto-detect support in the remote stub. */
1055 PACKET_SUPPORT_UNKNOWN = 0,
1060 struct packet_config
1065 /* If auto, GDB auto-detects support for this packet or feature,
1066 either through qSupported, or by trying the packet and looking
1067 at the response. If true, GDB assumes the target supports this
1068 packet. If false, the packet is disabled. Configs that don't
1069 have an associated command always have this set to auto. */
1070 enum auto_boolean detect;
1072 /* Does the target support this packet? */
1073 enum packet_support support;
1076 /* Analyze a packet's return value and update the packet config
1086 static enum packet_support packet_config_support (struct packet_config *config);
1087 static enum packet_support packet_support (int packet);
1090 show_packet_config_cmd (struct packet_config *config)
1092 char *support = "internal-error";
1094 switch (packet_config_support (config))
1097 support = "enabled";
1099 case PACKET_DISABLE:
1100 support = "disabled";
1102 case PACKET_SUPPORT_UNKNOWN:
1103 support = "unknown";
1106 switch (config->detect)
1108 case AUTO_BOOLEAN_AUTO:
1109 printf_filtered (_("Support for the `%s' packet "
1110 "is auto-detected, currently %s.\n"),
1111 config->name, support);
1113 case AUTO_BOOLEAN_TRUE:
1114 case AUTO_BOOLEAN_FALSE:
1115 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1116 config->name, support);
1122 add_packet_config_cmd (struct packet_config *config, const char *name,
1123 const char *title, int legacy)
1129 config->name = name;
1130 config->title = title;
1131 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1133 show_doc = xstrprintf ("Show current use of remote "
1134 "protocol `%s' (%s) packet",
1136 /* set/show TITLE-packet {auto,on,off} */
1137 cmd_name = xstrprintf ("%s-packet", title);
1138 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1139 &config->detect, set_doc,
1140 show_doc, NULL, /* help_doc */
1142 show_remote_protocol_packet_cmd,
1143 &remote_set_cmdlist, &remote_show_cmdlist);
1144 /* The command code copies the documentation strings. */
1147 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1152 legacy_name = xstrprintf ("%s-packet", name);
1153 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1154 &remote_set_cmdlist);
1155 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1156 &remote_show_cmdlist);
1160 static enum packet_result
1161 packet_check_result (const char *buf)
1165 /* The stub recognized the packet request. Check that the
1166 operation succeeded. */
1168 && isxdigit (buf[1]) && isxdigit (buf[2])
1170 /* "Enn" - definitly an error. */
1171 return PACKET_ERROR;
1173 /* Always treat "E." as an error. This will be used for
1174 more verbose error messages, such as E.memtypes. */
1175 if (buf[0] == 'E' && buf[1] == '.')
1176 return PACKET_ERROR;
1178 /* The packet may or may not be OK. Just assume it is. */
1182 /* The stub does not support the packet. */
1183 return PACKET_UNKNOWN;
1186 static enum packet_result
1187 packet_ok (const char *buf, struct packet_config *config)
1189 enum packet_result result;
1191 if (config->detect != AUTO_BOOLEAN_TRUE
1192 && config->support == PACKET_DISABLE)
1193 internal_error (__FILE__, __LINE__,
1194 _("packet_ok: attempt to use a disabled packet"));
1196 result = packet_check_result (buf);
1201 /* The stub recognized the packet request. */
1202 if (config->support == PACKET_SUPPORT_UNKNOWN)
1205 fprintf_unfiltered (gdb_stdlog,
1206 "Packet %s (%s) is supported\n",
1207 config->name, config->title);
1208 config->support = PACKET_ENABLE;
1211 case PACKET_UNKNOWN:
1212 /* The stub does not support the packet. */
1213 if (config->detect == AUTO_BOOLEAN_AUTO
1214 && config->support == PACKET_ENABLE)
1216 /* If the stub previously indicated that the packet was
1217 supported then there is a protocol error. */
1218 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1219 config->name, config->title);
1221 else if (config->detect == AUTO_BOOLEAN_TRUE)
1223 /* The user set it wrong. */
1224 error (_("Enabled packet %s (%s) not recognized by stub"),
1225 config->name, config->title);
1229 fprintf_unfiltered (gdb_stdlog,
1230 "Packet %s (%s) is NOT supported\n",
1231 config->name, config->title);
1232 config->support = PACKET_DISABLE;
1252 PACKET_vFile_pwrite,
1254 PACKET_vFile_unlink,
1255 PACKET_vFile_readlink,
1257 PACKET_qXfer_features,
1258 PACKET_qXfer_libraries,
1259 PACKET_qXfer_libraries_svr4,
1260 PACKET_qXfer_memory_map,
1261 PACKET_qXfer_spu_read,
1262 PACKET_qXfer_spu_write,
1263 PACKET_qXfer_osdata,
1264 PACKET_qXfer_threads,
1265 PACKET_qXfer_statictrace_read,
1266 PACKET_qXfer_traceframe_info,
1272 PACKET_QPassSignals,
1273 PACKET_QProgramSignals,
1275 PACKET_qSearch_memory,
1278 PACKET_QStartNoAckMode,
1280 PACKET_qXfer_siginfo_read,
1281 PACKET_qXfer_siginfo_write,
1284 /* Support for conditional tracepoints. */
1285 PACKET_ConditionalTracepoints,
1287 /* Support for target-side breakpoint conditions. */
1288 PACKET_ConditionalBreakpoints,
1290 /* Support for target-side breakpoint commands. */
1291 PACKET_BreakpointCommands,
1293 /* Support for fast tracepoints. */
1294 PACKET_FastTracepoints,
1296 /* Support for static tracepoints. */
1297 PACKET_StaticTracepoints,
1299 /* Support for installing tracepoints while a trace experiment is
1301 PACKET_InstallInTrace,
1305 PACKET_TracepointSource,
1308 PACKET_QDisableRandomization,
1310 PACKET_QTBuffer_size,
1313 PACKET_qXfer_btrace,
1315 /* Support for the QNonStop packet. */
1318 /* Support for multi-process extensions. */
1319 PACKET_multiprocess_feature,
1321 /* Support for enabling and disabling tracepoints while a trace
1322 experiment is running. */
1323 PACKET_EnableDisableTracepoints_feature,
1325 /* Support for collecting strings using the tracenz bytecode. */
1326 PACKET_tracenz_feature,
1328 /* Support for continuing to run a trace experiment while GDB is
1330 PACKET_DisconnectedTracing_feature,
1332 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1333 PACKET_augmented_libraries_svr4_read_feature,
1335 /* Support for the qXfer:btrace-conf:read packet. */
1336 PACKET_qXfer_btrace_conf,
1341 static struct packet_config remote_protocol_packets[PACKET_MAX];
1343 /* Returns whether a given packet or feature is supported. This takes
1344 into account the state of the corresponding "set remote foo-packet"
1345 command, which may be used to bypass auto-detection. */
1347 static enum packet_support
1348 packet_config_support (struct packet_config *config)
1350 switch (config->detect)
1352 case AUTO_BOOLEAN_TRUE:
1353 return PACKET_ENABLE;
1354 case AUTO_BOOLEAN_FALSE:
1355 return PACKET_DISABLE;
1356 case AUTO_BOOLEAN_AUTO:
1357 return config->support;
1359 gdb_assert_not_reached (_("bad switch"));
1363 /* Same as packet_config_support, but takes the packet's enum value as
1366 static enum packet_support
1367 packet_support (int packet)
1369 struct packet_config *config = &remote_protocol_packets[packet];
1371 return packet_config_support (config);
1375 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1376 struct cmd_list_element *c,
1379 struct packet_config *packet;
1381 for (packet = remote_protocol_packets;
1382 packet < &remote_protocol_packets[PACKET_MAX];
1385 if (&packet->detect == c->var)
1387 show_packet_config_cmd (packet);
1391 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1395 /* Should we try one of the 'Z' requests? */
1399 Z_PACKET_SOFTWARE_BP,
1400 Z_PACKET_HARDWARE_BP,
1407 /* For compatibility with older distributions. Provide a ``set remote
1408 Z-packet ...'' command that updates all the Z packet types. */
1410 static enum auto_boolean remote_Z_packet_detect;
1413 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1414 struct cmd_list_element *c)
1418 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1419 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1423 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1424 struct cmd_list_element *c,
1429 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1431 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1435 /* Returns true if the multi-process extensions are in effect. */
1438 remote_multi_process_p (struct remote_state *rs)
1440 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1443 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1444 static struct async_signal_handler *async_sigint_remote_twice_token;
1445 static struct async_signal_handler *async_sigint_remote_token;
1448 /* Asynchronous signal handle registered as event loop source for
1449 when we have pending events ready to be passed to the core. */
1451 static struct async_event_handler *remote_async_inferior_event_token;
1455 static ptid_t magic_null_ptid;
1456 static ptid_t not_sent_ptid;
1457 static ptid_t any_thread_ptid;
1459 /* Find out if the stub attached to PID (and hence GDB should offer to
1460 detach instead of killing it when bailing out). */
1463 remote_query_attached (int pid)
1465 struct remote_state *rs = get_remote_state ();
1466 size_t size = get_remote_packet_size ();
1468 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1471 if (remote_multi_process_p (rs))
1472 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1474 xsnprintf (rs->buf, size, "qAttached");
1477 getpkt (&rs->buf, &rs->buf_size, 0);
1479 switch (packet_ok (rs->buf,
1480 &remote_protocol_packets[PACKET_qAttached]))
1483 if (strcmp (rs->buf, "1") == 0)
1487 warning (_("Remote failure reply: %s"), rs->buf);
1489 case PACKET_UNKNOWN:
1496 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1497 has been invented by GDB, instead of reported by the target. Since
1498 we can be connected to a remote system before before knowing about
1499 any inferior, mark the target with execution when we find the first
1500 inferior. If ATTACHED is 1, then we had just attached to this
1501 inferior. If it is 0, then we just created this inferior. If it
1502 is -1, then try querying the remote stub to find out if it had
1503 attached to the inferior or not. */
1505 static struct inferior *
1506 remote_add_inferior (int fake_pid_p, int pid, int attached)
1508 struct inferior *inf;
1510 /* Check whether this process we're learning about is to be
1511 considered attached, or if is to be considered to have been
1512 spawned by the stub. */
1514 attached = remote_query_attached (pid);
1516 if (gdbarch_has_global_solist (target_gdbarch ()))
1518 /* If the target shares code across all inferiors, then every
1519 attach adds a new inferior. */
1520 inf = add_inferior (pid);
1522 /* ... and every inferior is bound to the same program space.
1523 However, each inferior may still have its own address
1525 inf->aspace = maybe_new_address_space ();
1526 inf->pspace = current_program_space;
1530 /* In the traditional debugging scenario, there's a 1-1 match
1531 between program/address spaces. We simply bind the inferior
1532 to the program space's address space. */
1533 inf = current_inferior ();
1534 inferior_appeared (inf, pid);
1537 inf->attach_flag = attached;
1538 inf->fake_pid_p = fake_pid_p;
1543 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1544 according to RUNNING. */
1547 remote_add_thread (ptid_t ptid, int running)
1549 struct remote_state *rs = get_remote_state ();
1551 /* GDB historically didn't pull threads in the initial connection
1552 setup. If the remote target doesn't even have a concept of
1553 threads (e.g., a bare-metal target), even if internally we
1554 consider that a single-threaded target, mentioning a new thread
1555 might be confusing to the user. Be silent then, preserving the
1556 age old behavior. */
1557 if (rs->starting_up)
1558 add_thread_silent (ptid);
1562 set_executing (ptid, running);
1563 set_running (ptid, running);
1566 /* Come here when we learn about a thread id from the remote target.
1567 It may be the first time we hear about such thread, so take the
1568 opportunity to add it to GDB's thread list. In case this is the
1569 first time we're noticing its corresponding inferior, add it to
1570 GDB's inferior list as well. */
1573 remote_notice_new_inferior (ptid_t currthread, int running)
1575 /* If this is a new thread, add it to GDB's thread list.
1576 If we leave it up to WFI to do this, bad things will happen. */
1578 if (in_thread_list (currthread) && is_exited (currthread))
1580 /* We're seeing an event on a thread id we knew had exited.
1581 This has to be a new thread reusing the old id. Add it. */
1582 remote_add_thread (currthread, running);
1586 if (!in_thread_list (currthread))
1588 struct inferior *inf = NULL;
1589 int pid = ptid_get_pid (currthread);
1591 if (ptid_is_pid (inferior_ptid)
1592 && pid == ptid_get_pid (inferior_ptid))
1594 /* inferior_ptid has no thread member yet. This can happen
1595 with the vAttach -> remote_wait,"TAAthread:" path if the
1596 stub doesn't support qC. This is the first stop reported
1597 after an attach, so this is the main thread. Update the
1598 ptid in the thread list. */
1599 if (in_thread_list (pid_to_ptid (pid)))
1600 thread_change_ptid (inferior_ptid, currthread);
1603 remote_add_thread (currthread, running);
1604 inferior_ptid = currthread;
1609 if (ptid_equal (magic_null_ptid, inferior_ptid))
1611 /* inferior_ptid is not set yet. This can happen with the
1612 vRun -> remote_wait,"TAAthread:" path if the stub
1613 doesn't support qC. This is the first stop reported
1614 after an attach, so this is the main thread. Update the
1615 ptid in the thread list. */
1616 thread_change_ptid (inferior_ptid, currthread);
1620 /* When connecting to a target remote, or to a target
1621 extended-remote which already was debugging an inferior, we
1622 may not know about it yet. Add it before adding its child
1623 thread, so notifications are emitted in a sensible order. */
1624 if (!in_inferior_list (ptid_get_pid (currthread)))
1626 struct remote_state *rs = get_remote_state ();
1627 int fake_pid_p = !remote_multi_process_p (rs);
1629 inf = remote_add_inferior (fake_pid_p,
1630 ptid_get_pid (currthread), -1);
1633 /* This is really a new thread. Add it. */
1634 remote_add_thread (currthread, running);
1636 /* If we found a new inferior, let the common code do whatever
1637 it needs to with it (e.g., read shared libraries, insert
1638 breakpoints), unless we're just setting up an all-stop
1642 struct remote_state *rs = get_remote_state ();
1644 if (non_stop || !rs->starting_up)
1645 notice_new_inferior (currthread, running, 0);
1650 /* Return the private thread data, creating it if necessary. */
1652 static struct private_thread_info *
1653 demand_private_info (ptid_t ptid)
1655 struct thread_info *info = find_thread_ptid (ptid);
1661 info->private = xmalloc (sizeof (*(info->private)));
1662 info->private_dtor = free_private_thread_info;
1663 info->private->core = -1;
1664 info->private->extra = 0;
1667 return info->private;
1670 /* Call this function as a result of
1671 1) A halt indication (T packet) containing a thread id
1672 2) A direct query of currthread
1673 3) Successful execution of set thread */
1676 record_currthread (struct remote_state *rs, ptid_t currthread)
1678 rs->general_thread = currthread;
1681 /* If 'QPassSignals' is supported, tell the remote stub what signals
1682 it can simply pass through to the inferior without reporting. */
1685 remote_pass_signals (struct target_ops *self,
1686 int numsigs, unsigned char *pass_signals)
1688 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1690 char *pass_packet, *p;
1692 struct remote_state *rs = get_remote_state ();
1694 gdb_assert (numsigs < 256);
1695 for (i = 0; i < numsigs; i++)
1697 if (pass_signals[i])
1700 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1701 strcpy (pass_packet, "QPassSignals:");
1702 p = pass_packet + strlen (pass_packet);
1703 for (i = 0; i < numsigs; i++)
1705 if (pass_signals[i])
1708 *p++ = tohex (i >> 4);
1709 *p++ = tohex (i & 15);
1718 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1720 putpkt (pass_packet);
1721 getpkt (&rs->buf, &rs->buf_size, 0);
1722 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1723 if (rs->last_pass_packet)
1724 xfree (rs->last_pass_packet);
1725 rs->last_pass_packet = pass_packet;
1728 xfree (pass_packet);
1732 /* If 'QProgramSignals' is supported, tell the remote stub what
1733 signals it should pass through to the inferior when detaching. */
1736 remote_program_signals (struct target_ops *self,
1737 int numsigs, unsigned char *signals)
1739 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1743 struct remote_state *rs = get_remote_state ();
1745 gdb_assert (numsigs < 256);
1746 for (i = 0; i < numsigs; i++)
1751 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1752 strcpy (packet, "QProgramSignals:");
1753 p = packet + strlen (packet);
1754 for (i = 0; i < numsigs; i++)
1756 if (signal_pass_state (i))
1759 *p++ = tohex (i >> 4);
1760 *p++ = tohex (i & 15);
1769 if (!rs->last_program_signals_packet
1770 || strcmp (rs->last_program_signals_packet, packet) != 0)
1773 getpkt (&rs->buf, &rs->buf_size, 0);
1774 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1775 xfree (rs->last_program_signals_packet);
1776 rs->last_program_signals_packet = packet;
1783 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1784 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1785 thread. If GEN is set, set the general thread, if not, then set
1786 the step/continue thread. */
1788 set_thread (struct ptid ptid, int gen)
1790 struct remote_state *rs = get_remote_state ();
1791 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1792 char *buf = rs->buf;
1793 char *endbuf = rs->buf + get_remote_packet_size ();
1795 if (ptid_equal (state, ptid))
1799 *buf++ = gen ? 'g' : 'c';
1800 if (ptid_equal (ptid, magic_null_ptid))
1801 xsnprintf (buf, endbuf - buf, "0");
1802 else if (ptid_equal (ptid, any_thread_ptid))
1803 xsnprintf (buf, endbuf - buf, "0");
1804 else if (ptid_equal (ptid, minus_one_ptid))
1805 xsnprintf (buf, endbuf - buf, "-1");
1807 write_ptid (buf, endbuf, ptid);
1809 getpkt (&rs->buf, &rs->buf_size, 0);
1811 rs->general_thread = ptid;
1813 rs->continue_thread = ptid;
1817 set_general_thread (struct ptid ptid)
1819 set_thread (ptid, 1);
1823 set_continue_thread (struct ptid ptid)
1825 set_thread (ptid, 0);
1828 /* Change the remote current process. Which thread within the process
1829 ends up selected isn't important, as long as it is the same process
1830 as what INFERIOR_PTID points to.
1832 This comes from that fact that there is no explicit notion of
1833 "selected process" in the protocol. The selected process for
1834 general operations is the process the selected general thread
1838 set_general_process (void)
1840 struct remote_state *rs = get_remote_state ();
1842 /* If the remote can't handle multiple processes, don't bother. */
1843 if (!rs->extended || !remote_multi_process_p (rs))
1846 /* We only need to change the remote current thread if it's pointing
1847 at some other process. */
1848 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1849 set_general_thread (inferior_ptid);
1853 /* Return nonzero if this is the main thread that we made up ourselves
1854 to model non-threaded targets as single-threaded. */
1857 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1859 struct remote_state *rs = get_remote_state ();
1862 if (ptid_equal (ptid, magic_null_ptid))
1863 /* The main thread is always alive. */
1866 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
1867 /* The main thread is always alive. This can happen after a
1868 vAttach, if the remote side doesn't support
1875 /* Return nonzero if the thread PTID is still alive on the remote
1879 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1881 struct remote_state *rs = get_remote_state ();
1884 /* Check if this is a thread that we made up ourselves to model
1885 non-threaded targets as single-threaded. */
1886 if (remote_thread_always_alive (ops, ptid))
1890 endp = rs->buf + get_remote_packet_size ();
1893 write_ptid (p, endp, ptid);
1896 getpkt (&rs->buf, &rs->buf_size, 0);
1897 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1900 /* About these extended threadlist and threadinfo packets. They are
1901 variable length packets but, the fields within them are often fixed
1902 length. They are redundent enough to send over UDP as is the
1903 remote protocol in general. There is a matching unit test module
1906 /* WARNING: This threadref data structure comes from the remote O.S.,
1907 libstub protocol encoding, and remote.c. It is not particularly
1910 /* Right now, the internal structure is int. We want it to be bigger.
1911 Plan to fix this. */
1913 typedef int gdb_threadref; /* Internal GDB thread reference. */
1915 /* gdb_ext_thread_info is an internal GDB data structure which is
1916 equivalent to the reply of the remote threadinfo packet. */
1918 struct gdb_ext_thread_info
1920 threadref threadid; /* External form of thread reference. */
1921 int active; /* Has state interesting to GDB?
1923 char display[256]; /* Brief state display, name,
1924 blocked/suspended. */
1925 char shortname[32]; /* To be used to name threads. */
1926 char more_display[256]; /* Long info, statistics, queue depth,
1930 /* The volume of remote transfers can be limited by submitting
1931 a mask containing bits specifying the desired information.
1932 Use a union of these values as the 'selection' parameter to
1933 get_thread_info. FIXME: Make these TAG names more thread specific. */
1935 #define TAG_THREADID 1
1936 #define TAG_EXISTS 2
1937 #define TAG_DISPLAY 4
1938 #define TAG_THREADNAME 8
1939 #define TAG_MOREDISPLAY 16
1941 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1943 static char *unpack_nibble (char *buf, int *val);
1945 static char *unpack_byte (char *buf, int *value);
1947 static char *pack_int (char *buf, int value);
1949 static char *unpack_int (char *buf, int *value);
1951 static char *unpack_string (char *src, char *dest, int length);
1953 static char *pack_threadid (char *pkt, threadref *id);
1955 static char *unpack_threadid (char *inbuf, threadref *id);
1957 void int_to_threadref (threadref *id, int value);
1959 static int threadref_to_int (threadref *ref);
1961 static void copy_threadref (threadref *dest, threadref *src);
1963 static int threadmatch (threadref *dest, threadref *src);
1965 static char *pack_threadinfo_request (char *pkt, int mode,
1968 static int remote_unpack_thread_info_response (char *pkt,
1969 threadref *expectedref,
1970 struct gdb_ext_thread_info
1974 static int remote_get_threadinfo (threadref *threadid,
1975 int fieldset, /*TAG mask */
1976 struct gdb_ext_thread_info *info);
1978 static char *pack_threadlist_request (char *pkt, int startflag,
1980 threadref *nextthread);
1982 static int parse_threadlist_response (char *pkt,
1984 threadref *original_echo,
1985 threadref *resultlist,
1988 static int remote_get_threadlist (int startflag,
1989 threadref *nextthread,
1993 threadref *threadlist);
1995 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1997 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1998 void *context, int looplimit);
2000 static int remote_newthread_step (threadref *ref, void *context);
2003 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2004 buffer we're allowed to write to. Returns
2005 BUF+CHARACTERS_WRITTEN. */
2008 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2011 struct remote_state *rs = get_remote_state ();
2013 if (remote_multi_process_p (rs))
2015 pid = ptid_get_pid (ptid);
2017 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2019 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2021 tid = ptid_get_lwp (ptid);
2023 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2025 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2030 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2031 passed the last parsed char. Returns null_ptid on error. */
2034 read_ptid (char *buf, char **obuf)
2038 ULONGEST pid = 0, tid = 0;
2042 /* Multi-process ptid. */
2043 pp = unpack_varlen_hex (p + 1, &pid);
2045 error (_("invalid remote ptid: %s"), p);
2048 pp = unpack_varlen_hex (p + 1, &tid);
2051 return ptid_build (pid, tid, 0);
2054 /* No multi-process. Just a tid. */
2055 pp = unpack_varlen_hex (p, &tid);
2057 /* Since the stub is not sending a process id, then default to
2058 what's in inferior_ptid, unless it's null at this point. If so,
2059 then since there's no way to know the pid of the reported
2060 threads, use the magic number. */
2061 if (ptid_equal (inferior_ptid, null_ptid))
2062 pid = ptid_get_pid (magic_null_ptid);
2064 pid = ptid_get_pid (inferior_ptid);
2068 return ptid_build (pid, tid, 0);
2074 if (ch >= 'a' && ch <= 'f')
2075 return ch - 'a' + 10;
2076 if (ch >= '0' && ch <= '9')
2078 if (ch >= 'A' && ch <= 'F')
2079 return ch - 'A' + 10;
2084 stub_unpack_int (char *buff, int fieldlength)
2091 nibble = stubhex (*buff++);
2095 retval = retval << 4;
2101 unpack_nibble (char *buf, int *val)
2103 *val = fromhex (*buf++);
2108 unpack_byte (char *buf, int *value)
2110 *value = stub_unpack_int (buf, 2);
2115 pack_int (char *buf, int value)
2117 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2118 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2119 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2120 buf = pack_hex_byte (buf, (value & 0xff));
2125 unpack_int (char *buf, int *value)
2127 *value = stub_unpack_int (buf, 8);
2131 #if 0 /* Currently unused, uncomment when needed. */
2132 static char *pack_string (char *pkt, char *string);
2135 pack_string (char *pkt, char *string)
2140 len = strlen (string);
2142 len = 200; /* Bigger than most GDB packets, junk??? */
2143 pkt = pack_hex_byte (pkt, len);
2147 if ((ch == '\0') || (ch == '#'))
2148 ch = '*'; /* Protect encapsulation. */
2153 #endif /* 0 (unused) */
2156 unpack_string (char *src, char *dest, int length)
2165 pack_threadid (char *pkt, threadref *id)
2168 unsigned char *altid;
2170 altid = (unsigned char *) id;
2171 limit = pkt + BUF_THREAD_ID_SIZE;
2173 pkt = pack_hex_byte (pkt, *altid++);
2179 unpack_threadid (char *inbuf, threadref *id)
2182 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2185 altref = (char *) id;
2187 while (inbuf < limit)
2189 x = stubhex (*inbuf++);
2190 y = stubhex (*inbuf++);
2191 *altref++ = (x << 4) | y;
2196 /* Externally, threadrefs are 64 bits but internally, they are still
2197 ints. This is due to a mismatch of specifications. We would like
2198 to use 64bit thread references internally. This is an adapter
2202 int_to_threadref (threadref *id, int value)
2204 unsigned char *scan;
2206 scan = (unsigned char *) id;
2212 *scan++ = (value >> 24) & 0xff;
2213 *scan++ = (value >> 16) & 0xff;
2214 *scan++ = (value >> 8) & 0xff;
2215 *scan++ = (value & 0xff);
2219 threadref_to_int (threadref *ref)
2222 unsigned char *scan;
2228 value = (value << 8) | ((*scan++) & 0xff);
2233 copy_threadref (threadref *dest, threadref *src)
2236 unsigned char *csrc, *cdest;
2238 csrc = (unsigned char *) src;
2239 cdest = (unsigned char *) dest;
2246 threadmatch (threadref *dest, threadref *src)
2248 /* Things are broken right now, so just assume we got a match. */
2250 unsigned char *srcp, *destp;
2252 srcp = (char *) src;
2253 destp = (char *) dest;
2257 result &= (*srcp++ == *destp++) ? 1 : 0;
2264 threadid:1, # always request threadid
2271 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2274 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2276 *pkt++ = 'q'; /* Info Query */
2277 *pkt++ = 'P'; /* process or thread info */
2278 pkt = pack_int (pkt, mode); /* mode */
2279 pkt = pack_threadid (pkt, id); /* threadid */
2280 *pkt = '\0'; /* terminate */
2284 /* These values tag the fields in a thread info response packet. */
2285 /* Tagging the fields allows us to request specific fields and to
2286 add more fields as time goes by. */
2288 #define TAG_THREADID 1 /* Echo the thread identifier. */
2289 #define TAG_EXISTS 2 /* Is this process defined enough to
2290 fetch registers and its stack? */
2291 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2292 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2293 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2297 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2298 struct gdb_ext_thread_info *info)
2300 struct remote_state *rs = get_remote_state ();
2304 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2307 /* info->threadid = 0; FIXME: implement zero_threadref. */
2309 info->display[0] = '\0';
2310 info->shortname[0] = '\0';
2311 info->more_display[0] = '\0';
2313 /* Assume the characters indicating the packet type have been
2315 pkt = unpack_int (pkt, &mask); /* arg mask */
2316 pkt = unpack_threadid (pkt, &ref);
2319 warning (_("Incomplete response to threadinfo request."));
2320 if (!threadmatch (&ref, expectedref))
2321 { /* This is an answer to a different request. */
2322 warning (_("ERROR RMT Thread info mismatch."));
2325 copy_threadref (&info->threadid, &ref);
2327 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2329 /* Packets are terminated with nulls. */
2330 while ((pkt < limit) && mask && *pkt)
2332 pkt = unpack_int (pkt, &tag); /* tag */
2333 pkt = unpack_byte (pkt, &length); /* length */
2334 if (!(tag & mask)) /* Tags out of synch with mask. */
2336 warning (_("ERROR RMT: threadinfo tag mismatch."));
2340 if (tag == TAG_THREADID)
2344 warning (_("ERROR RMT: length of threadid is not 16."));
2348 pkt = unpack_threadid (pkt, &ref);
2349 mask = mask & ~TAG_THREADID;
2352 if (tag == TAG_EXISTS)
2354 info->active = stub_unpack_int (pkt, length);
2356 mask = mask & ~(TAG_EXISTS);
2359 warning (_("ERROR RMT: 'exists' length too long."));
2365 if (tag == TAG_THREADNAME)
2367 pkt = unpack_string (pkt, &info->shortname[0], length);
2368 mask = mask & ~TAG_THREADNAME;
2371 if (tag == TAG_DISPLAY)
2373 pkt = unpack_string (pkt, &info->display[0], length);
2374 mask = mask & ~TAG_DISPLAY;
2377 if (tag == TAG_MOREDISPLAY)
2379 pkt = unpack_string (pkt, &info->more_display[0], length);
2380 mask = mask & ~TAG_MOREDISPLAY;
2383 warning (_("ERROR RMT: unknown thread info tag."));
2384 break; /* Not a tag we know about. */
2390 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2391 struct gdb_ext_thread_info *info)
2393 struct remote_state *rs = get_remote_state ();
2396 pack_threadinfo_request (rs->buf, fieldset, threadid);
2398 getpkt (&rs->buf, &rs->buf_size, 0);
2400 if (rs->buf[0] == '\0')
2403 result = remote_unpack_thread_info_response (rs->buf + 2,
2408 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2411 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2412 threadref *nextthread)
2414 *pkt++ = 'q'; /* info query packet */
2415 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2416 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2417 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2418 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2423 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2426 parse_threadlist_response (char *pkt, int result_limit,
2427 threadref *original_echo, threadref *resultlist,
2430 struct remote_state *rs = get_remote_state ();
2432 int count, resultcount, done;
2435 /* Assume the 'q' and 'M chars have been stripped. */
2436 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2437 /* done parse past here */
2438 pkt = unpack_byte (pkt, &count); /* count field */
2439 pkt = unpack_nibble (pkt, &done);
2440 /* The first threadid is the argument threadid. */
2441 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2442 while ((count-- > 0) && (pkt < limit))
2444 pkt = unpack_threadid (pkt, resultlist++);
2445 if (resultcount++ >= result_limit)
2453 /* Fetch the next batch of threads from the remote. Returns -1 if the
2454 qL packet is not supported, 0 on error and 1 on success. */
2457 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2458 int *done, int *result_count, threadref *threadlist)
2460 struct remote_state *rs = get_remote_state ();
2463 /* Trancate result limit to be smaller than the packet size. */
2464 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2465 >= get_remote_packet_size ())
2466 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2468 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2470 getpkt (&rs->buf, &rs->buf_size, 0);
2471 if (*rs->buf == '\0')
2473 /* Packet not supported. */
2478 parse_threadlist_response (rs->buf + 2, result_limit,
2479 &rs->echo_nextthread, threadlist, done);
2481 if (!threadmatch (&rs->echo_nextthread, nextthread))
2483 /* FIXME: This is a good reason to drop the packet. */
2484 /* Possably, there is a duplicate response. */
2486 retransmit immediatly - race conditions
2487 retransmit after timeout - yes
2489 wait for packet, then exit
2491 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2492 return 0; /* I choose simply exiting. */
2494 if (*result_count <= 0)
2498 warning (_("RMT ERROR : failed to get remote thread list."));
2501 return result; /* break; */
2503 if (*result_count > result_limit)
2506 warning (_("RMT ERROR: threadlist response longer than requested."));
2512 /* Fetch the list of remote threads, with the qL packet, and call
2513 STEPFUNCTION for each thread found. Stops iterating and returns 1
2514 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2515 STEPFUNCTION returns false. If the packet is not supported,
2519 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2522 struct remote_state *rs = get_remote_state ();
2523 int done, i, result_count;
2531 if (loopcount++ > looplimit)
2534 warning (_("Remote fetch threadlist -infinite loop-."));
2537 result = remote_get_threadlist (startflag, &rs->nextthread,
2538 MAXTHREADLISTRESULTS,
2539 &done, &result_count,
2540 rs->resultthreadlist);
2543 /* Clear for later iterations. */
2545 /* Setup to resume next batch of thread references, set nextthread. */
2546 if (result_count >= 1)
2547 copy_threadref (&rs->nextthread,
2548 &rs->resultthreadlist[result_count - 1]);
2550 while (result_count--)
2552 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2562 /* A thread found on the remote target. */
2564 typedef struct thread_item
2566 /* The thread's PTID. */
2569 /* The thread's extra info. May be NULL. */
2572 /* The core the thread was running on. -1 if not known. */
2575 DEF_VEC_O(thread_item_t);
2577 /* Context passed around to the various methods listing remote
2578 threads. As new threads are found, they're added to the ITEMS
2581 struct threads_listing_context
2583 /* The threads found on the remote target. */
2584 VEC (thread_item_t) *items;
2587 /* Discard the contents of the constructed thread listing context. */
2590 clear_threads_listing_context (void *p)
2592 struct threads_listing_context *context = p;
2594 struct thread_item *item;
2596 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2597 xfree (item->extra);
2599 VEC_free (thread_item_t, context->items);
2603 remote_newthread_step (threadref *ref, void *data)
2605 struct threads_listing_context *context = data;
2606 struct thread_item item;
2607 int pid = ptid_get_pid (inferior_ptid);
2609 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2613 VEC_safe_push (thread_item_t, context->items, &item);
2615 return 1; /* continue iterator */
2618 #define CRAZY_MAX_THREADS 1000
2621 remote_current_thread (ptid_t oldpid)
2623 struct remote_state *rs = get_remote_state ();
2626 getpkt (&rs->buf, &rs->buf_size, 0);
2627 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2628 return read_ptid (&rs->buf[2], NULL);
2633 /* List remote threads using the deprecated qL packet. */
2636 remote_get_threads_with_ql (struct target_ops *ops,
2637 struct threads_listing_context *context)
2639 if (remote_threadlist_iterator (remote_newthread_step, context,
2640 CRAZY_MAX_THREADS) >= 0)
2646 #if defined(HAVE_LIBEXPAT)
2649 start_thread (struct gdb_xml_parser *parser,
2650 const struct gdb_xml_element *element,
2651 void *user_data, VEC(gdb_xml_value_s) *attributes)
2653 struct threads_listing_context *data = user_data;
2655 struct thread_item item;
2657 struct gdb_xml_value *attr;
2659 id = xml_find_attribute (attributes, "id")->value;
2660 item.ptid = read_ptid (id, NULL);
2662 attr = xml_find_attribute (attributes, "core");
2664 item.core = *(ULONGEST *) attr->value;
2670 VEC_safe_push (thread_item_t, data->items, &item);
2674 end_thread (struct gdb_xml_parser *parser,
2675 const struct gdb_xml_element *element,
2676 void *user_data, const char *body_text)
2678 struct threads_listing_context *data = user_data;
2680 if (body_text && *body_text)
2681 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2684 const struct gdb_xml_attribute thread_attributes[] = {
2685 { "id", GDB_XML_AF_NONE, NULL, NULL },
2686 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2687 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2690 const struct gdb_xml_element thread_children[] = {
2691 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2694 const struct gdb_xml_element threads_children[] = {
2695 { "thread", thread_attributes, thread_children,
2696 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2697 start_thread, end_thread },
2698 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2701 const struct gdb_xml_element threads_elements[] = {
2702 { "threads", NULL, threads_children,
2703 GDB_XML_EF_NONE, NULL, NULL },
2704 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2709 /* List remote threads using qXfer:threads:read. */
2712 remote_get_threads_with_qxfer (struct target_ops *ops,
2713 struct threads_listing_context *context)
2715 #if defined(HAVE_LIBEXPAT)
2716 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2718 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2719 struct cleanup *back_to = make_cleanup (xfree, xml);
2721 if (xml != NULL && *xml != '\0')
2723 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2724 threads_elements, xml, context);
2727 do_cleanups (back_to);
2735 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2738 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2739 struct threads_listing_context *context)
2741 struct remote_state *rs = get_remote_state ();
2743 if (rs->use_threadinfo_query)
2747 putpkt ("qfThreadInfo");
2748 getpkt (&rs->buf, &rs->buf_size, 0);
2750 if (bufp[0] != '\0') /* q packet recognized */
2752 while (*bufp++ == 'm') /* reply contains one or more TID */
2756 struct thread_item item;
2758 item.ptid = read_ptid (bufp, &bufp);
2762 VEC_safe_push (thread_item_t, context->items, &item);
2764 while (*bufp++ == ','); /* comma-separated list */
2765 putpkt ("qsThreadInfo");
2766 getpkt (&rs->buf, &rs->buf_size, 0);
2773 /* Packet not recognized. */
2774 rs->use_threadinfo_query = 0;
2781 /* Implement the to_update_thread_list function for the remote
2785 remote_update_thread_list (struct target_ops *ops)
2787 struct remote_state *rs = get_remote_state ();
2788 struct threads_listing_context context;
2789 struct cleanup *old_chain;
2792 context.items = NULL;
2793 old_chain = make_cleanup (clear_threads_listing_context, &context);
2795 /* We have a few different mechanisms to fetch the thread list. Try
2796 them all, starting with the most preferred one first, falling
2797 back to older methods. */
2798 if (remote_get_threads_with_qxfer (ops, &context)
2799 || remote_get_threads_with_qthreadinfo (ops, &context)
2800 || remote_get_threads_with_ql (ops, &context))
2803 struct thread_item *item;
2804 struct thread_info *tp, *tmp;
2808 if (VEC_empty (thread_item_t, context.items)
2809 && remote_thread_always_alive (ops, inferior_ptid))
2811 /* Some targets don't really support threads, but still
2812 reply an (empty) thread list in response to the thread
2813 listing packets, instead of replying "packet not
2814 supported". Exit early so we don't delete the main
2816 do_cleanups (old_chain);
2820 /* CONTEXT now holds the current thread list on the remote
2821 target end. Delete GDB-side threads no longer found on the
2823 ALL_NON_EXITED_THREADS_SAFE (tp, tmp)
2826 VEC_iterate (thread_item_t, context.items, i, item);
2829 if (ptid_equal (item->ptid, tp->ptid))
2833 if (i == VEC_length (thread_item_t, context.items))
2836 delete_thread (tp->ptid);
2840 /* And now add threads we don't know about yet to our list. */
2842 VEC_iterate (thread_item_t, context.items, i, item);
2845 if (!ptid_equal (item->ptid, null_ptid))
2847 struct private_thread_info *info;
2848 /* In non-stop mode, we assume new found threads are
2849 running until proven otherwise with a stop reply. In
2850 all-stop, we can only get here if all threads are
2852 int running = non_stop ? 1 : 0;
2854 remote_notice_new_inferior (item->ptid, running);
2856 info = demand_private_info (item->ptid);
2857 info->core = item->core;
2858 info->extra = item->extra;
2866 /* If no thread listing method is supported, then query whether
2867 each known thread is alive, one by one, with the T packet.
2868 If the target doesn't support threads at all, then this is a
2869 no-op. See remote_thread_alive. */
2873 do_cleanups (old_chain);
2877 * Collect a descriptive string about the given thread.
2878 * The target may say anything it wants to about the thread
2879 * (typically info about its blocked / runnable state, name, etc.).
2880 * This string will appear in the info threads display.
2882 * Optional: targets are not required to implement this function.
2886 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
2888 struct remote_state *rs = get_remote_state ();
2892 struct gdb_ext_thread_info threadinfo;
2893 static char display_buf[100]; /* arbitrary... */
2894 int n = 0; /* position in display_buf */
2896 if (rs->remote_desc == 0) /* paranoia */
2897 internal_error (__FILE__, __LINE__,
2898 _("remote_threads_extra_info"));
2900 if (ptid_equal (tp->ptid, magic_null_ptid)
2901 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
2902 /* This is the main thread which was added by GDB. The remote
2903 server doesn't know about it. */
2906 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2908 struct thread_info *info = find_thread_ptid (tp->ptid);
2910 if (info && info->private)
2911 return info->private->extra;
2916 if (rs->use_threadextra_query)
2919 char *endb = rs->buf + get_remote_packet_size ();
2921 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2923 write_ptid (b, endb, tp->ptid);
2926 getpkt (&rs->buf, &rs->buf_size, 0);
2927 if (rs->buf[0] != 0)
2929 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2930 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2931 display_buf [result] = '\0';
2936 /* If the above query fails, fall back to the old method. */
2937 rs->use_threadextra_query = 0;
2938 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2939 | TAG_MOREDISPLAY | TAG_DISPLAY;
2940 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
2941 if (remote_get_threadinfo (&id, set, &threadinfo))
2942 if (threadinfo.active)
2944 if (*threadinfo.shortname)
2945 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2946 " Name: %s,", threadinfo.shortname);
2947 if (*threadinfo.display)
2948 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2949 " State: %s,", threadinfo.display);
2950 if (*threadinfo.more_display)
2951 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2952 " Priority: %s", threadinfo.more_display);
2956 /* For purely cosmetic reasons, clear up trailing commas. */
2957 if (',' == display_buf[n-1])
2958 display_buf[n-1] = ' ';
2967 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
2968 struct static_tracepoint_marker *marker)
2970 struct remote_state *rs = get_remote_state ();
2973 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2975 p += hexnumstr (p, addr);
2977 getpkt (&rs->buf, &rs->buf_size, 0);
2981 error (_("Remote failure reply: %s"), p);
2985 parse_static_tracepoint_marker_definition (p, &p, marker);
2992 static VEC(static_tracepoint_marker_p) *
2993 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
2996 struct remote_state *rs = get_remote_state ();
2997 VEC(static_tracepoint_marker_p) *markers = NULL;
2998 struct static_tracepoint_marker *marker = NULL;
2999 struct cleanup *old_chain;
3002 /* Ask for a first packet of static tracepoint marker
3005 getpkt (&rs->buf, &rs->buf_size, 0);
3008 error (_("Remote failure reply: %s"), p);
3010 old_chain = make_cleanup (free_current_marker, &marker);
3015 marker = XCNEW (struct static_tracepoint_marker);
3019 parse_static_tracepoint_marker_definition (p, &p, marker);
3021 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3023 VEC_safe_push (static_tracepoint_marker_p,
3029 release_static_tracepoint_marker (marker);
3030 memset (marker, 0, sizeof (*marker));
3033 while (*p++ == ','); /* comma-separated list */
3034 /* Ask for another packet of static tracepoint definition. */
3036 getpkt (&rs->buf, &rs->buf_size, 0);
3040 do_cleanups (old_chain);
3045 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3048 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3050 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3054 /* Restart the remote side; this is an extended protocol operation. */
3057 extended_remote_restart (void)
3059 struct remote_state *rs = get_remote_state ();
3061 /* Send the restart command; for reasons I don't understand the
3062 remote side really expects a number after the "R". */
3063 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3066 remote_fileio_reset ();
3069 /* Clean up connection to a remote debugger. */
3072 remote_close (struct target_ops *self)
3074 struct remote_state *rs = get_remote_state ();
3076 if (rs->remote_desc == NULL)
3077 return; /* already closed */
3079 /* Make sure we leave stdin registered in the event loop, and we
3080 don't leave the async SIGINT signal handler installed. */
3081 remote_terminal_ours (self);
3083 serial_close (rs->remote_desc);
3084 rs->remote_desc = NULL;
3086 /* We don't have a connection to the remote stub anymore. Get rid
3087 of all the inferiors and their threads we were controlling.
3088 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3089 will be unable to find the thread corresponding to (pid, 0, 0). */
3090 inferior_ptid = null_ptid;
3091 discard_all_inferiors ();
3093 /* We are closing the remote target, so we should discard
3094 everything of this target. */
3095 discard_pending_stop_replies_in_queue (rs);
3097 if (remote_async_inferior_event_token)
3098 delete_async_event_handler (&remote_async_inferior_event_token);
3100 remote_notif_state_xfree (rs->notif_state);
3102 trace_reset_local_state ();
3105 /* Query the remote side for the text, data and bss offsets. */
3110 struct remote_state *rs = get_remote_state ();
3113 int lose, num_segments = 0, do_sections, do_segments;
3114 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3115 struct section_offsets *offs;
3116 struct symfile_segment_data *data;
3118 if (symfile_objfile == NULL)
3121 putpkt ("qOffsets");
3122 getpkt (&rs->buf, &rs->buf_size, 0);
3125 if (buf[0] == '\000')
3126 return; /* Return silently. Stub doesn't support
3130 warning (_("Remote failure reply: %s"), buf);
3134 /* Pick up each field in turn. This used to be done with scanf, but
3135 scanf will make trouble if CORE_ADDR size doesn't match
3136 conversion directives correctly. The following code will work
3137 with any size of CORE_ADDR. */
3138 text_addr = data_addr = bss_addr = 0;
3142 if (strncmp (ptr, "Text=", 5) == 0)
3145 /* Don't use strtol, could lose on big values. */
3146 while (*ptr && *ptr != ';')
3147 text_addr = (text_addr << 4) + fromhex (*ptr++);
3149 if (strncmp (ptr, ";Data=", 6) == 0)
3152 while (*ptr && *ptr != ';')
3153 data_addr = (data_addr << 4) + fromhex (*ptr++);
3158 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3161 while (*ptr && *ptr != ';')
3162 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3164 if (bss_addr != data_addr)
3165 warning (_("Target reported unsupported offsets: %s"), buf);
3170 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3173 /* Don't use strtol, could lose on big values. */
3174 while (*ptr && *ptr != ';')
3175 text_addr = (text_addr << 4) + fromhex (*ptr++);
3178 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3181 while (*ptr && *ptr != ';')
3182 data_addr = (data_addr << 4) + fromhex (*ptr++);
3190 error (_("Malformed response to offset query, %s"), buf);
3191 else if (*ptr != '\0')
3192 warning (_("Target reported unsupported offsets: %s"), buf);
3194 offs = ((struct section_offsets *)
3195 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3196 memcpy (offs, symfile_objfile->section_offsets,
3197 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3199 data = get_symfile_segment_data (symfile_objfile->obfd);
3200 do_segments = (data != NULL);
3201 do_sections = num_segments == 0;
3203 if (num_segments > 0)
3205 segments[0] = text_addr;
3206 segments[1] = data_addr;
3208 /* If we have two segments, we can still try to relocate everything
3209 by assuming that the .text and .data offsets apply to the whole
3210 text and data segments. Convert the offsets given in the packet
3211 to base addresses for symfile_map_offsets_to_segments. */
3212 else if (data && data->num_segments == 2)
3214 segments[0] = data->segment_bases[0] + text_addr;
3215 segments[1] = data->segment_bases[1] + data_addr;
3218 /* If the object file has only one segment, assume that it is text
3219 rather than data; main programs with no writable data are rare,
3220 but programs with no code are useless. Of course the code might
3221 have ended up in the data segment... to detect that we would need
3222 the permissions here. */
3223 else if (data && data->num_segments == 1)
3225 segments[0] = data->segment_bases[0] + text_addr;
3228 /* There's no way to relocate by segment. */
3234 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3235 offs, num_segments, segments);
3237 if (ret == 0 && !do_sections)
3238 error (_("Can not handle qOffsets TextSeg "
3239 "response with this symbol file"));
3246 free_symfile_segment_data (data);
3250 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3252 /* This is a temporary kludge to force data and bss to use the
3253 same offsets because that's what nlmconv does now. The real
3254 solution requires changes to the stub and remote.c that I
3255 don't have time to do right now. */
3257 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3258 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3261 objfile_relocate (symfile_objfile, offs);
3264 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3265 threads we know are stopped already. This is used during the
3266 initial remote connection in non-stop mode --- threads that are
3267 reported as already being stopped are left stopped. */
3270 set_stop_requested_callback (struct thread_info *thread, void *data)
3272 /* If we have a stop reply for this thread, it must be stopped. */
3273 if (peek_stop_reply (thread->ptid))
3274 set_stop_requested (thread->ptid, 1);
3279 /* Send interrupt_sequence to remote target. */
3281 send_interrupt_sequence (void)
3283 struct remote_state *rs = get_remote_state ();
3285 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3286 remote_serial_write ("\x03", 1);
3287 else if (interrupt_sequence_mode == interrupt_sequence_break)
3288 serial_send_break (rs->remote_desc);
3289 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3291 serial_send_break (rs->remote_desc);
3292 remote_serial_write ("g", 1);
3295 internal_error (__FILE__, __LINE__,
3296 _("Invalid value for interrupt_sequence_mode: %s."),
3297 interrupt_sequence_mode);
3301 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3302 and extract the PTID. Returns NULL_PTID if not found. */
3305 stop_reply_extract_thread (char *stop_reply)
3307 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3311 /* Txx r:val ; r:val (...) */
3314 /* Look for "register" named "thread". */
3319 p1 = strchr (p, ':');
3323 if (strncmp (p, "thread", p1 - p) == 0)
3324 return read_ptid (++p1, &p);
3326 p1 = strchr (p, ';');
3338 /* Determine the remote side's current thread. If we have a stop
3339 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3340 "thread" register we can extract the current thread from. If not,
3341 ask the remote which is the current thread with qC. The former
3342 method avoids a roundtrip. */
3345 get_current_thread (char *wait_status)
3349 /* Note we don't use remote_parse_stop_reply as that makes use of
3350 the target architecture, which we haven't yet fully determined at
3352 if (wait_status != NULL)
3353 ptid = stop_reply_extract_thread (wait_status);
3354 if (ptid_equal (ptid, null_ptid))
3355 ptid = remote_current_thread (inferior_ptid);
3360 /* Query the remote target for which is the current thread/process,
3361 add it to our tables, and update INFERIOR_PTID. The caller is
3362 responsible for setting the state such that the remote end is ready
3363 to return the current thread.
3365 This function is called after handling the '?' or 'vRun' packets,
3366 whose response is a stop reply from which we can also try
3367 extracting the thread. If the target doesn't support the explicit
3368 qC query, we infer the current thread from that stop reply, passed
3369 in in WAIT_STATUS, which may be NULL. */
3372 add_current_inferior_and_thread (char *wait_status)
3374 struct remote_state *rs = get_remote_state ();
3376 ptid_t ptid = null_ptid;
3378 inferior_ptid = null_ptid;
3380 /* Now, if we have thread information, update inferior_ptid. */
3381 ptid = get_current_thread (wait_status);
3383 if (!ptid_equal (ptid, null_ptid))
3385 if (!remote_multi_process_p (rs))
3388 inferior_ptid = ptid;
3392 /* Without this, some commands which require an active target
3393 (such as kill) won't work. This variable serves (at least)
3394 double duty as both the pid of the target process (if it has
3395 such), and as a flag indicating that a target is active. */
3396 inferior_ptid = magic_null_ptid;
3400 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3402 /* Add the main thread. */
3403 add_thread_silent (inferior_ptid);
3407 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3409 struct remote_state *rs = get_remote_state ();
3410 struct packet_config *noack_config;
3411 char *wait_status = NULL;
3413 immediate_quit++; /* Allow user to interrupt it. */
3416 if (interrupt_on_connect)
3417 send_interrupt_sequence ();
3419 /* Ack any packet which the remote side has already sent. */
3420 serial_write (rs->remote_desc, "+", 1);
3422 /* Signal other parts that we're going through the initial setup,
3423 and so things may not be stable yet. */
3424 rs->starting_up = 1;
3426 /* The first packet we send to the target is the optional "supported
3427 packets" request. If the target can answer this, it will tell us
3428 which later probes to skip. */
3429 remote_query_supported ();
3431 /* If the stub wants to get a QAllow, compose one and send it. */
3432 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3433 remote_set_permissions (target);
3435 /* Next, we possibly activate noack mode.
3437 If the QStartNoAckMode packet configuration is set to AUTO,
3438 enable noack mode if the stub reported a wish for it with
3441 If set to TRUE, then enable noack mode even if the stub didn't
3442 report it in qSupported. If the stub doesn't reply OK, the
3443 session ends with an error.
3445 If FALSE, then don't activate noack mode, regardless of what the
3446 stub claimed should be the default with qSupported. */
3448 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3449 if (packet_config_support (noack_config) != PACKET_DISABLE)
3451 putpkt ("QStartNoAckMode");
3452 getpkt (&rs->buf, &rs->buf_size, 0);
3453 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3459 /* Tell the remote that we are using the extended protocol. */
3461 getpkt (&rs->buf, &rs->buf_size, 0);
3464 /* Let the target know which signals it is allowed to pass down to
3466 update_signals_program_target ();
3468 /* Next, if the target can specify a description, read it. We do
3469 this before anything involving memory or registers. */
3470 target_find_description ();
3472 /* Next, now that we know something about the target, update the
3473 address spaces in the program spaces. */
3474 update_address_spaces ();
3476 /* On OSs where the list of libraries is global to all
3477 processes, we fetch them early. */
3478 if (gdbarch_has_global_solist (target_gdbarch ()))
3479 solib_add (NULL, from_tty, target, auto_solib_add);
3483 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3484 error (_("Non-stop mode requested, but remote "
3485 "does not support non-stop"));
3487 putpkt ("QNonStop:1");
3488 getpkt (&rs->buf, &rs->buf_size, 0);
3490 if (strcmp (rs->buf, "OK") != 0)
3491 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3493 /* Find about threads and processes the stub is already
3494 controlling. We default to adding them in the running state.
3495 The '?' query below will then tell us about which threads are
3497 remote_update_thread_list (target);
3499 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3501 /* Don't assume that the stub can operate in all-stop mode.
3502 Request it explicitly. */
3503 putpkt ("QNonStop:0");
3504 getpkt (&rs->buf, &rs->buf_size, 0);
3506 if (strcmp (rs->buf, "OK") != 0)
3507 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3510 /* Upload TSVs regardless of whether the target is running or not. The
3511 remote stub, such as GDBserver, may have some predefined or builtin
3512 TSVs, even if the target is not running. */
3513 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3515 struct uploaded_tsv *uploaded_tsvs = NULL;
3517 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3518 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3521 /* Check whether the target is running now. */
3523 getpkt (&rs->buf, &rs->buf_size, 0);
3529 struct inferior *inf;
3531 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3534 error (_("The target is not running (try extended-remote?)"));
3536 /* We're connected, but not running. Drop out before we
3537 call start_remote. */
3538 rs->starting_up = 0;
3543 /* Save the reply for later. */
3544 wait_status = alloca (strlen (rs->buf) + 1);
3545 strcpy (wait_status, rs->buf);
3548 /* Fetch thread list. */
3549 target_update_thread_list ();
3551 /* Let the stub know that we want it to return the thread. */
3552 set_continue_thread (minus_one_ptid);
3554 if (thread_count () == 0)
3556 /* Target has no concept of threads at all. GDB treats
3557 non-threaded target as single-threaded; add a main
3559 add_current_inferior_and_thread (wait_status);
3563 /* We have thread information; select the thread the target
3564 says should be current. If we're reconnecting to a
3565 multi-threaded program, this will ideally be the thread
3566 that last reported an event before GDB disconnected. */
3567 inferior_ptid = get_current_thread (wait_status);
3568 if (ptid_equal (inferior_ptid, null_ptid))
3570 /* Odd... The target was able to list threads, but not
3571 tell us which thread was current (no "thread"
3572 register in T stop reply?). Just pick the first
3573 thread in the thread list then. */
3574 inferior_ptid = thread_list->ptid;
3578 /* init_wait_for_inferior should be called before get_offsets in order
3579 to manage `inserted' flag in bp loc in a correct state.
3580 breakpoint_init_inferior, called from init_wait_for_inferior, set
3581 `inserted' flag to 0, while before breakpoint_re_set, called from
3582 start_remote, set `inserted' flag to 1. In the initialization of
3583 inferior, breakpoint_init_inferior should be called first, and then
3584 breakpoint_re_set can be called. If this order is broken, state of
3585 `inserted' flag is wrong, and cause some problems on breakpoint
3587 init_wait_for_inferior ();
3589 get_offsets (); /* Get text, data & bss offsets. */
3591 /* If we could not find a description using qXfer, and we know
3592 how to do it some other way, try again. This is not
3593 supported for non-stop; it could be, but it is tricky if
3594 there are no stopped threads when we connect. */
3595 if (remote_read_description_p (target)
3596 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3598 target_clear_description ();
3599 target_find_description ();
3602 /* Use the previously fetched status. */
3603 gdb_assert (wait_status != NULL);
3604 strcpy (rs->buf, wait_status);
3605 rs->cached_wait_status = 1;
3608 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3612 /* Clear WFI global state. Do this before finding about new
3613 threads and inferiors, and setting the current inferior.
3614 Otherwise we would clear the proceed status of the current
3615 inferior when we want its stop_soon state to be preserved
3616 (see notice_new_inferior). */
3617 init_wait_for_inferior ();
3619 /* In non-stop, we will either get an "OK", meaning that there
3620 are no stopped threads at this time; or, a regular stop
3621 reply. In the latter case, there may be more than one thread
3622 stopped --- we pull them all out using the vStopped
3624 if (strcmp (rs->buf, "OK") != 0)
3626 struct notif_client *notif = ¬if_client_stop;
3628 /* remote_notif_get_pending_replies acks this one, and gets
3630 rs->notif_state->pending_event[notif_client_stop.id]
3631 = remote_notif_parse (notif, rs->buf);
3632 remote_notif_get_pending_events (notif);
3634 /* Make sure that threads that were stopped remain
3636 iterate_over_threads (set_stop_requested_callback, NULL);
3639 if (target_can_async_p ())
3640 target_async (inferior_event_handler, 0);
3642 if (thread_count () == 0)
3645 error (_("The target is not running (try extended-remote?)"));
3647 /* We're connected, but not running. Drop out before we
3648 call start_remote. */
3649 rs->starting_up = 0;
3653 /* Let the stub know that we want it to return the thread. */
3655 /* Force the stub to choose a thread. */
3656 set_general_thread (null_ptid);
3659 inferior_ptid = remote_current_thread (minus_one_ptid);
3660 if (ptid_equal (inferior_ptid, minus_one_ptid))
3661 error (_("remote didn't report the current thread in non-stop mode"));
3663 get_offsets (); /* Get text, data & bss offsets. */
3665 /* In non-stop mode, any cached wait status will be stored in
3666 the stop reply queue. */
3667 gdb_assert (wait_status == NULL);
3669 /* Report all signals during attach/startup. */
3670 remote_pass_signals (target, 0, NULL);
3673 /* If we connected to a live target, do some additional setup. */
3674 if (target_has_execution)
3676 if (symfile_objfile) /* No use without a symbol-file. */
3677 remote_check_symbols ();
3680 /* Possibly the target has been engaged in a trace run started
3681 previously; find out where things are at. */
3682 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3684 struct uploaded_tp *uploaded_tps = NULL;
3686 if (current_trace_status ()->running)
3687 printf_filtered (_("Trace is already running on the target.\n"));
3689 remote_upload_tracepoints (target, &uploaded_tps);
3691 merge_uploaded_tracepoints (&uploaded_tps);
3694 /* The thread and inferior lists are now synchronized with the
3695 target, our symbols have been relocated, and we're merged the
3696 target's tracepoints with ours. We're done with basic start
3698 rs->starting_up = 0;
3700 /* Maybe breakpoints are global and need to be inserted now. */
3701 if (breakpoints_should_be_inserted_now ())
3702 insert_breakpoints ();
3705 /* Open a connection to a remote debugger.
3706 NAME is the filename used for communication. */
3709 remote_open (const char *name, int from_tty)
3711 remote_open_1 (name, from_tty, &remote_ops, 0);
3714 /* Open a connection to a remote debugger using the extended
3715 remote gdb protocol. NAME is the filename used for communication. */
3718 extended_remote_open (const char *name, int from_tty)
3720 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3723 /* Reset all packets back to "unknown support". Called when opening a
3724 new connection to a remote target. */
3727 reset_all_packet_configs_support (void)
3731 for (i = 0; i < PACKET_MAX; i++)
3732 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3735 /* Initialize all packet configs. */
3738 init_all_packet_configs (void)
3742 for (i = 0; i < PACKET_MAX; i++)
3744 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3745 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3749 /* Symbol look-up. */
3752 remote_check_symbols (void)
3754 struct remote_state *rs = get_remote_state ();
3755 char *msg, *reply, *tmp;
3756 struct bound_minimal_symbol sym;
3759 /* The remote side has no concept of inferiors that aren't running
3760 yet, it only knows about running processes. If we're connected
3761 but our current inferior is not running, we should not invite the
3762 remote target to request symbol lookups related to its
3763 (unrelated) current process. */
3764 if (!target_has_execution)
3767 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3770 /* Make sure the remote is pointing at the right process. Note
3771 there's no way to select "no process". */
3772 set_general_process ();
3774 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3775 because we need both at the same time. */
3776 msg = alloca (get_remote_packet_size ());
3778 /* Invite target to request symbol lookups. */
3780 putpkt ("qSymbol::");
3781 getpkt (&rs->buf, &rs->buf_size, 0);
3782 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3785 while (strncmp (reply, "qSymbol:", 8) == 0)
3787 struct bound_minimal_symbol sym;
3790 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3792 sym = lookup_minimal_symbol (msg, NULL, NULL);
3793 if (sym.minsym == NULL)
3794 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3797 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3798 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
3800 /* If this is a function address, return the start of code
3801 instead of any data function descriptor. */
3802 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3806 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3807 phex_nz (sym_addr, addr_size), &reply[8]);
3811 getpkt (&rs->buf, &rs->buf_size, 0);
3816 static struct serial *
3817 remote_serial_open (const char *name)
3819 static int udp_warning = 0;
3821 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3822 of in ser-tcp.c, because it is the remote protocol assuming that the
3823 serial connection is reliable and not the serial connection promising
3825 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3827 warning (_("The remote protocol may be unreliable over UDP.\n"
3828 "Some events may be lost, rendering further debugging "
3833 return serial_open (name);
3836 /* Inform the target of our permission settings. The permission flags
3837 work without this, but if the target knows the settings, it can do
3838 a couple things. First, it can add its own check, to catch cases
3839 that somehow manage to get by the permissions checks in target
3840 methods. Second, if the target is wired to disallow particular
3841 settings (for instance, a system in the field that is not set up to
3842 be able to stop at a breakpoint), it can object to any unavailable
3846 remote_set_permissions (struct target_ops *self)
3848 struct remote_state *rs = get_remote_state ();
3850 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3851 "WriteReg:%x;WriteMem:%x;"
3852 "InsertBreak:%x;InsertTrace:%x;"
3853 "InsertFastTrace:%x;Stop:%x",
3854 may_write_registers, may_write_memory,
3855 may_insert_breakpoints, may_insert_tracepoints,
3856 may_insert_fast_tracepoints, may_stop);
3858 getpkt (&rs->buf, &rs->buf_size, 0);
3860 /* If the target didn't like the packet, warn the user. Do not try
3861 to undo the user's settings, that would just be maddening. */
3862 if (strcmp (rs->buf, "OK") != 0)
3863 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3866 /* This type describes each known response to the qSupported
3868 struct protocol_feature
3870 /* The name of this protocol feature. */
3873 /* The default for this protocol feature. */
3874 enum packet_support default_support;
3876 /* The function to call when this feature is reported, or after
3877 qSupported processing if the feature is not supported.
3878 The first argument points to this structure. The second
3879 argument indicates whether the packet requested support be
3880 enabled, disabled, or probed (or the default, if this function
3881 is being called at the end of processing and this feature was
3882 not reported). The third argument may be NULL; if not NULL, it
3883 is a NUL-terminated string taken from the packet following
3884 this feature's name and an equals sign. */
3885 void (*func) (const struct protocol_feature *, enum packet_support,
3888 /* The corresponding packet for this feature. Only used if
3889 FUNC is remote_supported_packet. */
3894 remote_supported_packet (const struct protocol_feature *feature,
3895 enum packet_support support,
3896 const char *argument)
3900 warning (_("Remote qSupported response supplied an unexpected value for"
3901 " \"%s\"."), feature->name);
3905 remote_protocol_packets[feature->packet].support = support;
3909 remote_packet_size (const struct protocol_feature *feature,
3910 enum packet_support support, const char *value)
3912 struct remote_state *rs = get_remote_state ();
3917 if (support != PACKET_ENABLE)
3920 if (value == NULL || *value == '\0')
3922 warning (_("Remote target reported \"%s\" without a size."),
3928 packet_size = strtol (value, &value_end, 16);
3929 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3931 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3932 feature->name, value);
3936 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3938 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3939 packet_size, MAX_REMOTE_PACKET_SIZE);
3940 packet_size = MAX_REMOTE_PACKET_SIZE;
3943 /* Record the new maximum packet size. */
3944 rs->explicit_packet_size = packet_size;
3947 static const struct protocol_feature remote_protocol_features[] = {
3948 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3949 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3950 PACKET_qXfer_auxv },
3951 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3952 PACKET_qXfer_features },
3953 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3954 PACKET_qXfer_libraries },
3955 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3956 PACKET_qXfer_libraries_svr4 },
3957 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3958 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
3959 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3960 PACKET_qXfer_memory_map },
3961 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3962 PACKET_qXfer_spu_read },
3963 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3964 PACKET_qXfer_spu_write },
3965 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3966 PACKET_qXfer_osdata },
3967 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3968 PACKET_qXfer_threads },
3969 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3970 PACKET_qXfer_traceframe_info },
3971 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3972 PACKET_QPassSignals },
3973 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3974 PACKET_QProgramSignals },
3975 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3976 PACKET_QStartNoAckMode },
3977 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
3978 PACKET_multiprocess_feature },
3979 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
3980 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3981 PACKET_qXfer_siginfo_read },
3982 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3983 PACKET_qXfer_siginfo_write },
3984 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
3985 PACKET_ConditionalTracepoints },
3986 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3987 PACKET_ConditionalBreakpoints },
3988 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
3989 PACKET_BreakpointCommands },
3990 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
3991 PACKET_FastTracepoints },
3992 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
3993 PACKET_StaticTracepoints },
3994 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
3995 PACKET_InstallInTrace},
3996 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
3997 PACKET_DisconnectedTracing_feature },
3998 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4000 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4002 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4003 PACKET_TracepointSource },
4004 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4006 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4007 PACKET_EnableDisableTracepoints_feature },
4008 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4009 PACKET_qXfer_fdpic },
4010 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4012 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4013 PACKET_QDisableRandomization },
4014 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4015 { "QTBuffer:size", PACKET_DISABLE,
4016 remote_supported_packet, PACKET_QTBuffer_size},
4017 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4018 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4019 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4020 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4021 PACKET_qXfer_btrace },
4022 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4023 PACKET_qXfer_btrace_conf }
4026 static char *remote_support_xml;
4028 /* Register string appended to "xmlRegisters=" in qSupported query. */
4031 register_remote_support_xml (const char *xml)
4033 #if defined(HAVE_LIBEXPAT)
4034 if (remote_support_xml == NULL)
4035 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4038 char *copy = xstrdup (remote_support_xml + 13);
4039 char *p = strtok (copy, ",");
4043 if (strcmp (p, xml) == 0)
4050 while ((p = strtok (NULL, ",")) != NULL);
4053 remote_support_xml = reconcat (remote_support_xml,
4054 remote_support_xml, ",", xml,
4061 remote_query_supported_append (char *msg, const char *append)
4064 return reconcat (msg, msg, ";", append, (char *) NULL);
4066 return xstrdup (append);
4070 remote_query_supported (void)
4072 struct remote_state *rs = get_remote_state ();
4075 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4077 /* The packet support flags are handled differently for this packet
4078 than for most others. We treat an error, a disabled packet, and
4079 an empty response identically: any features which must be reported
4080 to be used will be automatically disabled. An empty buffer
4081 accomplishes this, since that is also the representation for a list
4082 containing no features. */
4085 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4088 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4090 q = remote_query_supported_append (q, "multiprocess+");
4092 if (remote_support_xml)
4093 q = remote_query_supported_append (q, remote_support_xml);
4095 q = remote_query_supported_append (q, "qRelocInsn+");
4097 q = reconcat (q, "qSupported:", q, (char *) NULL);
4100 do_cleanups (old_chain);
4102 getpkt (&rs->buf, &rs->buf_size, 0);
4104 /* If an error occured, warn, but do not return - just reset the
4105 buffer to empty and go on to disable features. */
4106 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4109 warning (_("Remote failure reply: %s"), rs->buf);
4114 memset (seen, 0, sizeof (seen));
4119 enum packet_support is_supported;
4120 char *p, *end, *name_end, *value;
4122 /* First separate out this item from the rest of the packet. If
4123 there's another item after this, we overwrite the separator
4124 (terminated strings are much easier to work with). */
4126 end = strchr (p, ';');
4129 end = p + strlen (p);
4139 warning (_("empty item in \"qSupported\" response"));
4144 name_end = strchr (p, '=');
4147 /* This is a name=value entry. */
4148 is_supported = PACKET_ENABLE;
4149 value = name_end + 1;
4158 is_supported = PACKET_ENABLE;
4162 is_supported = PACKET_DISABLE;
4166 is_supported = PACKET_SUPPORT_UNKNOWN;
4170 warning (_("unrecognized item \"%s\" "
4171 "in \"qSupported\" response"), p);
4177 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4178 if (strcmp (remote_protocol_features[i].name, p) == 0)
4180 const struct protocol_feature *feature;
4183 feature = &remote_protocol_features[i];
4184 feature->func (feature, is_supported, value);
4189 /* If we increased the packet size, make sure to increase the global
4190 buffer size also. We delay this until after parsing the entire
4191 qSupported packet, because this is the same buffer we were
4193 if (rs->buf_size < rs->explicit_packet_size)
4195 rs->buf_size = rs->explicit_packet_size;
4196 rs->buf = xrealloc (rs->buf, rs->buf_size);
4199 /* Handle the defaults for unmentioned features. */
4200 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4203 const struct protocol_feature *feature;
4205 feature = &remote_protocol_features[i];
4206 feature->func (feature, feature->default_support, NULL);
4210 /* Remove any of the remote.c targets from target stack. Upper targets depend
4211 on it so remove them first. */
4214 remote_unpush_target (void)
4216 pop_all_targets_above (process_stratum - 1);
4220 remote_open_1 (const char *name, int from_tty,
4221 struct target_ops *target, int extended_p)
4223 struct remote_state *rs = get_remote_state ();
4226 error (_("To open a remote debug connection, you need to specify what\n"
4227 "serial device is attached to the remote system\n"
4228 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4230 /* See FIXME above. */
4231 if (!target_async_permitted)
4232 wait_forever_enabled_p = 1;
4234 /* If we're connected to a running target, target_preopen will kill it.
4235 Ask this question first, before target_preopen has a chance to kill
4237 if (rs->remote_desc != NULL && !have_inferiors ())
4240 && !query (_("Already connected to a remote target. Disconnect? ")))
4241 error (_("Still connected."));
4244 /* Here the possibly existing remote target gets unpushed. */
4245 target_preopen (from_tty);
4247 /* Make sure we send the passed signals list the next time we resume. */
4248 xfree (rs->last_pass_packet);
4249 rs->last_pass_packet = NULL;
4251 /* Make sure we send the program signals list the next time we
4253 xfree (rs->last_program_signals_packet);
4254 rs->last_program_signals_packet = NULL;
4256 remote_fileio_reset ();
4257 reopen_exec_file ();
4260 rs->remote_desc = remote_serial_open (name);
4261 if (!rs->remote_desc)
4262 perror_with_name (name);
4264 if (baud_rate != -1)
4266 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4268 /* The requested speed could not be set. Error out to
4269 top level after closing remote_desc. Take care to
4270 set remote_desc to NULL to avoid closing remote_desc
4272 serial_close (rs->remote_desc);
4273 rs->remote_desc = NULL;
4274 perror_with_name (name);
4278 serial_raw (rs->remote_desc);
4280 /* If there is something sitting in the buffer we might take it as a
4281 response to a command, which would be bad. */
4282 serial_flush_input (rs->remote_desc);
4286 puts_filtered ("Remote debugging using ");
4287 puts_filtered (name);
4288 puts_filtered ("\n");
4290 push_target (target); /* Switch to using remote target now. */
4292 /* Register extra event sources in the event loop. */
4293 remote_async_inferior_event_token
4294 = create_async_event_handler (remote_async_inferior_event_handler,
4296 rs->notif_state = remote_notif_state_allocate ();
4298 /* Reset the target state; these things will be queried either by
4299 remote_query_supported or as they are needed. */
4300 reset_all_packet_configs_support ();
4301 rs->cached_wait_status = 0;
4302 rs->explicit_packet_size = 0;
4304 rs->extended = extended_p;
4305 rs->waiting_for_stop_reply = 0;
4306 rs->ctrlc_pending_p = 0;
4308 rs->general_thread = not_sent_ptid;
4309 rs->continue_thread = not_sent_ptid;
4310 rs->remote_traceframe_number = -1;
4312 /* Probe for ability to use "ThreadInfo" query, as required. */
4313 rs->use_threadinfo_query = 1;
4314 rs->use_threadextra_query = 1;
4316 if (target_async_permitted)
4318 /* With this target we start out by owning the terminal. */
4319 remote_async_terminal_ours_p = 1;
4321 /* FIXME: cagney/1999-09-23: During the initial connection it is
4322 assumed that the target is already ready and able to respond to
4323 requests. Unfortunately remote_start_remote() eventually calls
4324 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4325 around this. Eventually a mechanism that allows
4326 wait_for_inferior() to expect/get timeouts will be
4328 wait_forever_enabled_p = 0;
4331 /* First delete any symbols previously loaded from shared libraries. */
4332 no_shared_libraries (NULL, 0);
4335 init_thread_list ();
4337 /* Start the remote connection. If error() or QUIT, discard this
4338 target (we'd otherwise be in an inconsistent state) and then
4339 propogate the error on up the exception chain. This ensures that
4340 the caller doesn't stumble along blindly assuming that the
4341 function succeeded. The CLI doesn't have this problem but other
4342 UI's, such as MI do.
4344 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4345 this function should return an error indication letting the
4346 caller restore the previous state. Unfortunately the command
4347 ``target remote'' is directly wired to this function making that
4348 impossible. On a positive note, the CLI side of this problem has
4349 been fixed - the function set_cmd_context() makes it possible for
4350 all the ``target ....'' commands to share a common callback
4351 function. See cli-dump.c. */
4353 volatile struct gdb_exception ex;
4355 TRY_CATCH (ex, RETURN_MASK_ALL)
4357 remote_start_remote (from_tty, target, extended_p);
4361 /* Pop the partially set up target - unless something else did
4362 already before throwing the exception. */
4363 if (rs->remote_desc != NULL)
4364 remote_unpush_target ();
4365 if (target_async_permitted)
4366 wait_forever_enabled_p = 1;
4367 throw_exception (ex);
4371 remote_btrace_reset ();
4373 if (target_async_permitted)
4374 wait_forever_enabled_p = 1;
4377 /* This takes a program previously attached to and detaches it. After
4378 this is done, GDB can be used to debug some other program. We
4379 better not have left any breakpoints in the target program or it'll
4380 die when it hits one. */
4383 remote_detach_1 (const char *args, int from_tty, int extended)
4385 int pid = ptid_get_pid (inferior_ptid);
4386 struct remote_state *rs = get_remote_state ();
4389 error (_("Argument given to \"detach\" when remotely debugging."));
4391 if (!target_has_execution)
4392 error (_("No process to detach from."));
4396 char *exec_file = get_exec_file (0);
4397 if (exec_file == NULL)
4399 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4400 target_pid_to_str (pid_to_ptid (pid)));
4401 gdb_flush (gdb_stdout);
4404 /* Tell the remote target to detach. */
4405 if (remote_multi_process_p (rs))
4406 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4408 strcpy (rs->buf, "D");
4411 getpkt (&rs->buf, &rs->buf_size, 0);
4413 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4415 else if (rs->buf[0] == '\0')
4416 error (_("Remote doesn't know how to detach"));
4418 error (_("Can't detach process."));
4420 if (from_tty && !extended)
4421 puts_filtered (_("Ending remote debugging.\n"));
4423 target_mourn_inferior ();
4427 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4429 remote_detach_1 (args, from_tty, 0);
4433 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4435 remote_detach_1 (args, from_tty, 1);
4438 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4441 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4444 error (_("Argument given to \"disconnect\" when remotely debugging."));
4446 /* Make sure we unpush even the extended remote targets; mourn
4447 won't do it. So call remote_mourn_1 directly instead of
4448 target_mourn_inferior. */
4449 remote_mourn_1 (target);
4452 puts_filtered ("Ending remote debugging.\n");
4455 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4456 be chatty about it. */
4459 extended_remote_attach_1 (struct target_ops *target, const char *args,
4462 struct remote_state *rs = get_remote_state ();
4464 char *wait_status = NULL;
4466 pid = parse_pid_to_attach (args);
4468 /* Remote PID can be freely equal to getpid, do not check it here the same
4469 way as in other targets. */
4471 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4472 error (_("This target does not support attaching to a process"));
4476 char *exec_file = get_exec_file (0);
4479 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4480 target_pid_to_str (pid_to_ptid (pid)));
4482 printf_unfiltered (_("Attaching to %s\n"),
4483 target_pid_to_str (pid_to_ptid (pid)));
4485 gdb_flush (gdb_stdout);
4488 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4490 getpkt (&rs->buf, &rs->buf_size, 0);
4492 switch (packet_ok (rs->buf,
4493 &remote_protocol_packets[PACKET_vAttach]))
4498 /* Save the reply for later. */
4499 wait_status = alloca (strlen (rs->buf) + 1);
4500 strcpy (wait_status, rs->buf);
4502 else if (strcmp (rs->buf, "OK") != 0)
4503 error (_("Attaching to %s failed with: %s"),
4504 target_pid_to_str (pid_to_ptid (pid)),
4507 case PACKET_UNKNOWN:
4508 error (_("This target does not support attaching to a process"));
4510 error (_("Attaching to %s failed"),
4511 target_pid_to_str (pid_to_ptid (pid)));
4514 set_current_inferior (remote_add_inferior (0, pid, 1));
4516 inferior_ptid = pid_to_ptid (pid);
4520 struct thread_info *thread;
4522 /* Get list of threads. */
4523 remote_update_thread_list (target);
4525 thread = first_thread_of_process (pid);
4527 inferior_ptid = thread->ptid;
4529 inferior_ptid = pid_to_ptid (pid);
4531 /* Invalidate our notion of the remote current thread. */
4532 record_currthread (rs, minus_one_ptid);
4536 /* Now, if we have thread information, update inferior_ptid. */
4537 inferior_ptid = remote_current_thread (inferior_ptid);
4539 /* Add the main thread to the thread list. */
4540 add_thread_silent (inferior_ptid);
4543 /* Next, if the target can specify a description, read it. We do
4544 this before anything involving memory or registers. */
4545 target_find_description ();
4549 /* Use the previously fetched status. */
4550 gdb_assert (wait_status != NULL);
4552 if (target_can_async_p ())
4554 struct notif_event *reply
4555 = remote_notif_parse (¬if_client_stop, wait_status);
4557 push_stop_reply ((struct stop_reply *) reply);
4559 target_async (inferior_event_handler, 0);
4563 gdb_assert (wait_status != NULL);
4564 strcpy (rs->buf, wait_status);
4565 rs->cached_wait_status = 1;
4569 gdb_assert (wait_status == NULL);
4573 extended_remote_attach (struct target_ops *ops, const char *args, int from_tty)
4575 extended_remote_attach_1 (ops, args, from_tty);
4578 /* Implementation of the to_post_attach method. */
4581 extended_remote_post_attach (struct target_ops *ops, int pid)
4583 /* In certain cases GDB might not have had the chance to start
4584 symbol lookup up until now. This could happen if the debugged
4585 binary is not using shared libraries, the vsyscall page is not
4586 present (on Linux) and the binary itself hadn't changed since the
4587 debugging process was started. */
4588 if (symfile_objfile != NULL)
4589 remote_check_symbols();
4593 /* Check for the availability of vCont. This function should also check
4597 remote_vcont_probe (struct remote_state *rs)
4601 strcpy (rs->buf, "vCont?");
4603 getpkt (&rs->buf, &rs->buf_size, 0);
4606 /* Make sure that the features we assume are supported. */
4607 if (strncmp (buf, "vCont", 5) == 0)
4610 int support_s, support_S, support_c, support_C;
4616 rs->supports_vCont.t = 0;
4617 rs->supports_vCont.r = 0;
4618 while (p && *p == ';')
4621 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4623 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4625 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4627 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4629 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4630 rs->supports_vCont.t = 1;
4631 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4632 rs->supports_vCont.r = 1;
4634 p = strchr (p, ';');
4637 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4638 BUF will make packet_ok disable the packet. */
4639 if (!support_s || !support_S || !support_c || !support_C)
4643 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4646 /* Helper function for building "vCont" resumptions. Write a
4647 resumption to P. ENDP points to one-passed-the-end of the buffer
4648 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4649 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4650 resumed thread should be single-stepped and/or signalled. If PTID
4651 equals minus_one_ptid, then all threads are resumed; if PTID
4652 represents a process, then all threads of the process are resumed;
4653 the thread to be stepped and/or signalled is given in the global
4657 append_resumption (char *p, char *endp,
4658 ptid_t ptid, int step, enum gdb_signal siggnal)
4660 struct remote_state *rs = get_remote_state ();
4662 if (step && siggnal != GDB_SIGNAL_0)
4663 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4665 /* GDB is willing to range step. */
4666 && use_range_stepping
4667 /* Target supports range stepping. */
4668 && rs->supports_vCont.r
4669 /* We don't currently support range stepping multiple
4670 threads with a wildcard (though the protocol allows it,
4671 so stubs shouldn't make an active effort to forbid
4673 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4675 struct thread_info *tp;
4677 if (ptid_equal (ptid, minus_one_ptid))
4679 /* If we don't know about the target thread's tid, then
4680 we're resuming magic_null_ptid (see caller). */
4681 tp = find_thread_ptid (magic_null_ptid);
4684 tp = find_thread_ptid (ptid);
4685 gdb_assert (tp != NULL);
4687 if (tp->control.may_range_step)
4689 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4691 p += xsnprintf (p, endp - p, ";r%s,%s",
4692 phex_nz (tp->control.step_range_start,
4694 phex_nz (tp->control.step_range_end,
4698 p += xsnprintf (p, endp - p, ";s");
4701 p += xsnprintf (p, endp - p, ";s");
4702 else if (siggnal != GDB_SIGNAL_0)
4703 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4705 p += xsnprintf (p, endp - p, ";c");
4707 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4711 /* All (-1) threads of process. */
4712 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4714 p += xsnprintf (p, endp - p, ":");
4715 p = write_ptid (p, endp, nptid);
4717 else if (!ptid_equal (ptid, minus_one_ptid))
4719 p += xsnprintf (p, endp - p, ":");
4720 p = write_ptid (p, endp, ptid);
4726 /* Append a vCont continue-with-signal action for threads that have a
4727 non-zero stop signal. */
4730 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4732 struct thread_info *thread;
4734 ALL_NON_EXITED_THREADS (thread)
4735 if (ptid_match (thread->ptid, ptid)
4736 && !ptid_equal (inferior_ptid, thread->ptid)
4737 && thread->suspend.stop_signal != GDB_SIGNAL_0)
4739 p = append_resumption (p, endp, thread->ptid,
4740 0, thread->suspend.stop_signal);
4741 thread->suspend.stop_signal = GDB_SIGNAL_0;
4747 /* Resume the remote inferior by using a "vCont" packet. The thread
4748 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4749 resumed thread should be single-stepped and/or signalled. If PTID
4750 equals minus_one_ptid, then all threads are resumed; the thread to
4751 be stepped and/or signalled is given in the global INFERIOR_PTID.
4752 This function returns non-zero iff it resumes the inferior.
4754 This function issues a strict subset of all possible vCont commands at the
4758 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4760 struct remote_state *rs = get_remote_state ();
4764 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4765 remote_vcont_probe (rs);
4767 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
4771 endp = rs->buf + get_remote_packet_size ();
4773 /* If we could generate a wider range of packets, we'd have to worry
4774 about overflowing BUF. Should there be a generic
4775 "multi-part-packet" packet? */
4777 p += xsnprintf (p, endp - p, "vCont");
4779 if (ptid_equal (ptid, magic_null_ptid))
4781 /* MAGIC_NULL_PTID means that we don't have any active threads,
4782 so we don't have any TID numbers the inferior will
4783 understand. Make sure to only send forms that do not specify
4785 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4787 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4789 /* Resume all threads (of all processes, or of a single
4790 process), with preference for INFERIOR_PTID. This assumes
4791 inferior_ptid belongs to the set of all threads we are about
4793 if (step || siggnal != GDB_SIGNAL_0)
4795 /* Step inferior_ptid, with or without signal. */
4796 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4799 /* Also pass down any pending signaled resumption for other
4800 threads not the current. */
4801 p = append_pending_thread_resumptions (p, endp, ptid);
4803 /* And continue others without a signal. */
4804 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4808 /* Scheduler locking; resume only PTID. */
4809 append_resumption (p, endp, ptid, step, siggnal);
4812 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4817 /* In non-stop, the stub replies to vCont with "OK". The stop
4818 reply will be reported asynchronously by means of a `%Stop'
4820 getpkt (&rs->buf, &rs->buf_size, 0);
4821 if (strcmp (rs->buf, "OK") != 0)
4822 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4828 /* Tell the remote machine to resume. */
4831 remote_resume (struct target_ops *ops,
4832 ptid_t ptid, int step, enum gdb_signal siggnal)
4834 struct remote_state *rs = get_remote_state ();
4837 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4838 (explained in remote-notif.c:handle_notification) so
4839 remote_notif_process is not called. We need find a place where
4840 it is safe to start a 'vNotif' sequence. It is good to do it
4841 before resuming inferior, because inferior was stopped and no RSP
4842 traffic at that moment. */
4844 remote_notif_process (rs->notif_state, ¬if_client_stop);
4846 rs->last_sent_signal = siggnal;
4847 rs->last_sent_step = step;
4849 /* The vCont packet doesn't need to specify threads via Hc. */
4850 /* No reverse support (yet) for vCont. */
4851 if (execution_direction != EXEC_REVERSE)
4852 if (remote_vcont_resume (ptid, step, siggnal))
4855 /* All other supported resume packets do use Hc, so set the continue
4857 if (ptid_equal (ptid, minus_one_ptid))
4858 set_continue_thread (any_thread_ptid);
4860 set_continue_thread (ptid);
4863 if (execution_direction == EXEC_REVERSE)
4865 /* We don't pass signals to the target in reverse exec mode. */
4866 if (info_verbose && siggnal != GDB_SIGNAL_0)
4867 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4870 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
4871 error (_("Remote reverse-step not supported."));
4872 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
4873 error (_("Remote reverse-continue not supported."));
4875 strcpy (buf, step ? "bs" : "bc");
4877 else if (siggnal != GDB_SIGNAL_0)
4879 buf[0] = step ? 'S' : 'C';
4880 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4881 buf[2] = tohex (((int) siggnal) & 0xf);
4885 strcpy (buf, step ? "s" : "c");
4890 /* We are about to start executing the inferior, let's register it
4891 with the event loop. NOTE: this is the one place where all the
4892 execution commands end up. We could alternatively do this in each
4893 of the execution commands in infcmd.c. */
4894 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4895 into infcmd.c in order to allow inferior function calls to work
4896 NOT asynchronously. */
4897 if (target_can_async_p ())
4898 target_async (inferior_event_handler, 0);
4900 /* We've just told the target to resume. The remote server will
4901 wait for the inferior to stop, and then send a stop reply. In
4902 the mean time, we can't start another command/query ourselves
4903 because the stub wouldn't be ready to process it. This applies
4904 only to the base all-stop protocol, however. In non-stop (which
4905 only supports vCont), the stub replies with an "OK", and is
4906 immediate able to process further serial input. */
4908 rs->waiting_for_stop_reply = 1;
4912 /* Set up the signal handler for SIGINT, while the target is
4913 executing, ovewriting the 'regular' SIGINT signal handler. */
4915 async_initialize_sigint_signal_handler (void)
4917 signal (SIGINT, async_handle_remote_sigint);
4920 /* Signal handler for SIGINT, while the target is executing. */
4922 async_handle_remote_sigint (int sig)
4924 signal (sig, async_handle_remote_sigint_twice);
4925 /* Note we need to go through gdb_call_async_signal_handler in order
4926 to wake up the event loop on Windows. */
4927 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
4930 /* Signal handler for SIGINT, installed after SIGINT has already been
4931 sent once. It will take effect the second time that the user sends
4934 async_handle_remote_sigint_twice (int sig)
4936 signal (sig, async_handle_remote_sigint);
4937 /* See note in async_handle_remote_sigint. */
4938 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
4941 /* Perform the real interruption of the target execution, in response
4944 async_remote_interrupt (gdb_client_data arg)
4947 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
4949 target_stop (inferior_ptid);
4952 /* Perform interrupt, if the first attempt did not succeed. Just give
4953 up on the target alltogether. */
4955 async_remote_interrupt_twice (gdb_client_data arg)
4958 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
4963 /* Reinstall the usual SIGINT handlers, after the target has
4966 async_cleanup_sigint_signal_handler (void *dummy)
4968 signal (SIGINT, handle_sigint);
4971 /* Send ^C to target to halt it. Target will respond, and send us a
4973 static void (*ofunc) (int);
4975 /* The command line interface's stop routine. This function is installed
4976 as a signal handler for SIGINT. The first time a user requests a
4977 stop, we call remote_stop to send a break or ^C. If there is no
4978 response from the target (it didn't stop when the user requested it),
4979 we ask the user if he'd like to detach from the target. */
4981 sync_remote_interrupt (int signo)
4983 /* If this doesn't work, try more severe steps. */
4984 signal (signo, sync_remote_interrupt_twice);
4986 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
4989 /* The user typed ^C twice. */
4992 sync_remote_interrupt_twice (int signo)
4994 signal (signo, ofunc);
4995 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
4996 signal (signo, sync_remote_interrupt);
4999 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5000 thread, all threads of a remote process, or all threads of all
5004 remote_stop_ns (ptid_t ptid)
5006 struct remote_state *rs = get_remote_state ();
5008 char *endp = rs->buf + get_remote_packet_size ();
5010 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5011 remote_vcont_probe (rs);
5013 if (!rs->supports_vCont.t)
5014 error (_("Remote server does not support stopping threads"));
5016 if (ptid_equal (ptid, minus_one_ptid)
5017 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5018 p += xsnprintf (p, endp - p, "vCont;t");
5023 p += xsnprintf (p, endp - p, "vCont;t:");
5025 if (ptid_is_pid (ptid))
5026 /* All (-1) threads of process. */
5027 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5030 /* Small optimization: if we already have a stop reply for
5031 this thread, no use in telling the stub we want this
5033 if (peek_stop_reply (ptid))
5039 write_ptid (p, endp, nptid);
5042 /* In non-stop, we get an immediate OK reply. The stop reply will
5043 come in asynchronously by notification. */
5045 getpkt (&rs->buf, &rs->buf_size, 0);
5046 if (strcmp (rs->buf, "OK") != 0)
5047 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5050 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5051 remote target. It is undefined which thread of which process
5052 reports the stop. */
5055 remote_stop_as (ptid_t ptid)
5057 struct remote_state *rs = get_remote_state ();
5059 rs->ctrlc_pending_p = 1;
5061 /* If the inferior is stopped already, but the core didn't know
5062 about it yet, just ignore the request. The cached wait status
5063 will be collected in remote_wait. */
5064 if (rs->cached_wait_status)
5067 /* Send interrupt_sequence to remote target. */
5068 send_interrupt_sequence ();
5071 /* This is the generic stop called via the target vector. When a target
5072 interrupt is requested, either by the command line or the GUI, we
5073 will eventually end up here. */
5076 remote_stop (struct target_ops *self, ptid_t ptid)
5079 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5082 remote_stop_ns (ptid);
5084 remote_stop_as (ptid);
5087 /* Ask the user what to do when an interrupt is received. */
5090 interrupt_query (void)
5092 target_terminal_ours ();
5094 if (target_is_async_p ())
5096 signal (SIGINT, handle_sigint);
5101 if (query (_("Interrupted while waiting for the program.\n\
5102 Give up (and stop debugging it)? ")))
5104 remote_unpush_target ();
5109 target_terminal_inferior ();
5112 /* Enable/disable target terminal ownership. Most targets can use
5113 terminal groups to control terminal ownership. Remote targets are
5114 different in that explicit transfer of ownership to/from GDB/target
5118 remote_terminal_inferior (struct target_ops *self)
5120 if (!target_async_permitted)
5121 /* Nothing to do. */
5124 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5125 idempotent. The event-loop GDB talking to an asynchronous target
5126 with a synchronous command calls this function from both
5127 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5128 transfer the terminal to the target when it shouldn't this guard
5130 if (!remote_async_terminal_ours_p)
5132 delete_file_handler (input_fd);
5133 remote_async_terminal_ours_p = 0;
5134 async_initialize_sigint_signal_handler ();
5135 /* NOTE: At this point we could also register our selves as the
5136 recipient of all input. Any characters typed could then be
5137 passed on down to the target. */
5141 remote_terminal_ours (struct target_ops *self)
5143 if (!target_async_permitted)
5144 /* Nothing to do. */
5147 /* See FIXME in remote_terminal_inferior. */
5148 if (remote_async_terminal_ours_p)
5150 async_cleanup_sigint_signal_handler (NULL);
5151 add_file_handler (input_fd, stdin_event_handler, 0);
5152 remote_async_terminal_ours_p = 1;
5156 remote_console_output (char *msg)
5160 for (p = msg; p[0] && p[1]; p += 2)
5163 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5167 fputs_unfiltered (tb, gdb_stdtarg);
5169 gdb_flush (gdb_stdtarg);
5172 typedef struct cached_reg
5175 gdb_byte data[MAX_REGISTER_SIZE];
5178 DEF_VEC_O(cached_reg_t);
5180 typedef struct stop_reply
5182 struct notif_event base;
5184 /* The identifier of the thread about this event */
5187 /* The remote state this event is associated with. When the remote
5188 connection, represented by a remote_state object, is closed,
5189 all the associated stop_reply events should be released. */
5190 struct remote_state *rs;
5192 struct target_waitstatus ws;
5194 /* Expedited registers. This makes remote debugging a bit more
5195 efficient for those targets that provide critical registers as
5196 part of their normal status mechanism (as another roundtrip to
5197 fetch them is avoided). */
5198 VEC(cached_reg_t) *regcache;
5200 int stopped_by_watchpoint_p;
5201 CORE_ADDR watch_data_address;
5206 DECLARE_QUEUE_P (stop_reply_p);
5207 DEFINE_QUEUE_P (stop_reply_p);
5208 /* The list of already fetched and acknowledged stop events. This
5209 queue is used for notification Stop, and other notifications
5210 don't need queue for their events, because the notification events
5211 of Stop can't be consumed immediately, so that events should be
5212 queued first, and be consumed by remote_wait_{ns,as} one per
5213 time. Other notifications can consume their events immediately,
5214 so queue is not needed for them. */
5215 static QUEUE (stop_reply_p) *stop_reply_queue;
5218 stop_reply_xfree (struct stop_reply *r)
5220 notif_event_xfree ((struct notif_event *) r);
5224 remote_notif_stop_parse (struct notif_client *self, char *buf,
5225 struct notif_event *event)
5227 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5231 remote_notif_stop_ack (struct notif_client *self, char *buf,
5232 struct notif_event *event)
5234 struct stop_reply *stop_reply = (struct stop_reply *) event;
5237 putpkt ((char *) self->ack_command);
5239 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5240 /* We got an unknown stop reply. */
5241 error (_("Unknown stop reply"));
5243 push_stop_reply (stop_reply);
5247 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5249 /* We can't get pending events in remote_notif_process for
5250 notification stop, and we have to do this in remote_wait_ns
5251 instead. If we fetch all queued events from stub, remote stub
5252 may exit and we have no chance to process them back in
5254 mark_async_event_handler (remote_async_inferior_event_token);
5259 stop_reply_dtr (struct notif_event *event)
5261 struct stop_reply *r = (struct stop_reply *) event;
5263 VEC_free (cached_reg_t, r->regcache);
5266 static struct notif_event *
5267 remote_notif_stop_alloc_reply (void)
5269 struct notif_event *r
5270 = (struct notif_event *) XNEW (struct stop_reply);
5272 r->dtr = stop_reply_dtr;
5277 /* A client of notification Stop. */
5279 struct notif_client notif_client_stop =
5283 remote_notif_stop_parse,
5284 remote_notif_stop_ack,
5285 remote_notif_stop_can_get_pending_events,
5286 remote_notif_stop_alloc_reply,
5290 /* A parameter to pass data in and out. */
5292 struct queue_iter_param
5295 struct stop_reply *output;
5298 /* Remove stop replies in the queue if its pid is equal to the given
5302 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5303 QUEUE_ITER (stop_reply_p) *iter,
5307 struct queue_iter_param *param = data;
5308 struct inferior *inf = param->input;
5310 if (ptid_get_pid (event->ptid) == inf->pid)
5312 stop_reply_xfree (event);
5313 QUEUE_remove_elem (stop_reply_p, q, iter);
5319 /* Discard all pending stop replies of inferior INF. */
5322 discard_pending_stop_replies (struct inferior *inf)
5325 struct queue_iter_param param;
5326 struct stop_reply *reply;
5327 struct remote_state *rs = get_remote_state ();
5328 struct remote_notif_state *rns = rs->notif_state;
5330 /* This function can be notified when an inferior exists. When the
5331 target is not remote, the notification state is NULL. */
5332 if (rs->remote_desc == NULL)
5335 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5337 /* Discard the in-flight notification. */
5338 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5340 stop_reply_xfree (reply);
5341 rns->pending_event[notif_client_stop.id] = NULL;
5345 param.output = NULL;
5346 /* Discard the stop replies we have already pulled with
5348 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5349 remove_stop_reply_for_inferior, ¶m);
5352 /* If its remote state is equal to the given remote state,
5353 remove EVENT from the stop reply queue. */
5356 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5357 QUEUE_ITER (stop_reply_p) *iter,
5361 struct queue_iter_param *param = data;
5362 struct remote_state *rs = param->input;
5364 if (event->rs == rs)
5366 stop_reply_xfree (event);
5367 QUEUE_remove_elem (stop_reply_p, q, iter);
5373 /* Discard the stop replies for RS in stop_reply_queue. */
5376 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5378 struct queue_iter_param param;
5381 param.output = NULL;
5382 /* Discard the stop replies we have already pulled with
5384 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5385 remove_stop_reply_of_remote_state, ¶m);
5388 /* A parameter to pass data in and out. */
5391 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5392 QUEUE_ITER (stop_reply_p) *iter,
5396 struct queue_iter_param *param = data;
5397 ptid_t *ptid = param->input;
5399 if (ptid_match (event->ptid, *ptid))
5401 param->output = event;
5402 QUEUE_remove_elem (stop_reply_p, q, iter);
5409 /* Remove the first reply in 'stop_reply_queue' which matches
5412 static struct stop_reply *
5413 remote_notif_remove_queued_reply (ptid_t ptid)
5415 struct queue_iter_param param;
5417 param.input = &ptid;
5418 param.output = NULL;
5420 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5421 remote_notif_remove_once_on_match, ¶m);
5423 fprintf_unfiltered (gdb_stdlog,
5424 "notif: discard queued event: 'Stop' in %s\n",
5425 target_pid_to_str (ptid));
5427 return param.output;
5430 /* Look for a queued stop reply belonging to PTID. If one is found,
5431 remove it from the queue, and return it. Returns NULL if none is
5432 found. If there are still queued events left to process, tell the
5433 event loop to get back to target_wait soon. */
5435 static struct stop_reply *
5436 queued_stop_reply (ptid_t ptid)
5438 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5440 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5441 /* There's still at least an event left. */
5442 mark_async_event_handler (remote_async_inferior_event_token);
5447 /* Push a fully parsed stop reply in the stop reply queue. Since we
5448 know that we now have at least one queued event left to pass to the
5449 core side, tell the event loop to get back to target_wait soon. */
5452 push_stop_reply (struct stop_reply *new_event)
5454 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5457 fprintf_unfiltered (gdb_stdlog,
5458 "notif: push 'Stop' %s to queue %d\n",
5459 target_pid_to_str (new_event->ptid),
5460 QUEUE_length (stop_reply_p,
5463 mark_async_event_handler (remote_async_inferior_event_token);
5467 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5468 QUEUE_ITER (stop_reply_p) *iter,
5469 struct stop_reply *event,
5472 ptid_t *ptid = data;
5474 return !(ptid_equal (*ptid, event->ptid)
5475 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5478 /* Returns true if we have a stop reply for PTID. */
5481 peek_stop_reply (ptid_t ptid)
5483 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5484 stop_reply_match_ptid_and_ws, &ptid);
5487 /* Parse the stop reply in BUF. Either the function succeeds, and the
5488 result is stored in EVENT, or throws an error. */
5491 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5493 struct remote_arch_state *rsa = get_remote_arch_state ();
5497 event->ptid = null_ptid;
5498 event->rs = get_remote_state ();
5499 event->ws.kind = TARGET_WAITKIND_IGNORE;
5500 event->ws.value.integer = 0;
5501 event->stopped_by_watchpoint_p = 0;
5502 event->regcache = NULL;
5507 case 'T': /* Status with PC, SP, FP, ... */
5508 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5509 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5511 n... = register number
5512 r... = register contents
5515 p = &buf[3]; /* after Txx */
5523 /* If the packet contains a register number, save it in
5524 pnum and set p1 to point to the character following it.
5525 Otherwise p1 points to p. */
5527 /* If this packet is an awatch packet, don't parse the 'a'
5528 as a register number. */
5530 if (strncmp (p, "awatch", strlen("awatch")) != 0
5531 && strncmp (p, "core", strlen ("core") != 0))
5533 /* Read the ``P'' register number. */
5534 pnum = strtol (p, &p_temp, 16);
5540 if (p1 == p) /* No register number present here. */
5542 p1 = strchr (p, ':');
5544 error (_("Malformed packet(a) (missing colon): %s\n\
5547 if (strncmp (p, "thread", p1 - p) == 0)
5548 event->ptid = read_ptid (++p1, &p);
5549 else if ((strncmp (p, "watch", p1 - p) == 0)
5550 || (strncmp (p, "rwatch", p1 - p) == 0)
5551 || (strncmp (p, "awatch", p1 - p) == 0))
5553 event->stopped_by_watchpoint_p = 1;
5554 p = unpack_varlen_hex (++p1, &addr);
5555 event->watch_data_address = (CORE_ADDR) addr;
5557 else if (strncmp (p, "library", p1 - p) == 0)
5561 while (*p_temp && *p_temp != ';')
5564 event->ws.kind = TARGET_WAITKIND_LOADED;
5567 else if (strncmp (p, "replaylog", p1 - p) == 0)
5569 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5570 /* p1 will indicate "begin" or "end", but it makes
5571 no difference for now, so ignore it. */
5572 p_temp = strchr (p1 + 1, ';');
5576 else if (strncmp (p, "core", p1 - p) == 0)
5580 p = unpack_varlen_hex (++p1, &c);
5585 /* Silently skip unknown optional info. */
5586 p_temp = strchr (p1 + 1, ';');
5593 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5594 cached_reg_t cached_reg;
5599 error (_("Malformed packet(b) (missing colon): %s\n\
5605 error (_("Remote sent bad register number %s: %s\n\
5607 hex_string (pnum), p, buf);
5609 cached_reg.num = reg->regnum;
5611 fieldsize = hex2bin (p, cached_reg.data,
5612 register_size (target_gdbarch (),
5615 if (fieldsize < register_size (target_gdbarch (),
5617 warning (_("Remote reply is too short: %s"), buf);
5619 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5623 error (_("Remote register badly formatted: %s\nhere: %s"),
5628 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5632 case 'S': /* Old style status, just signal only. */
5636 event->ws.kind = TARGET_WAITKIND_STOPPED;
5637 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5638 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5639 event->ws.value.sig = (enum gdb_signal) sig;
5641 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5644 case 'W': /* Target exited. */
5651 /* GDB used to accept only 2 hex chars here. Stubs should
5652 only send more if they detect GDB supports multi-process
5654 p = unpack_varlen_hex (&buf[1], &value);
5658 /* The remote process exited. */
5659 event->ws.kind = TARGET_WAITKIND_EXITED;
5660 event->ws.value.integer = value;
5664 /* The remote process exited with a signal. */
5665 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5666 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5667 event->ws.value.sig = (enum gdb_signal) value;
5669 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5672 /* If no process is specified, assume inferior_ptid. */
5673 pid = ptid_get_pid (inferior_ptid);
5682 else if (strncmp (p,
5683 "process:", sizeof ("process:") - 1) == 0)
5687 p += sizeof ("process:") - 1;
5688 unpack_varlen_hex (p, &upid);
5692 error (_("unknown stop reply packet: %s"), buf);
5695 error (_("unknown stop reply packet: %s"), buf);
5696 event->ptid = pid_to_ptid (pid);
5701 if (non_stop && ptid_equal (event->ptid, null_ptid))
5702 error (_("No process or thread specified in stop reply: %s"), buf);
5705 /* When the stub wants to tell GDB about a new notification reply, it
5706 sends a notification (%Stop, for example). Those can come it at
5707 any time, hence, we have to make sure that any pending
5708 putpkt/getpkt sequence we're making is finished, before querying
5709 the stub for more events with the corresponding ack command
5710 (vStopped, for example). E.g., if we started a vStopped sequence
5711 immediately upon receiving the notification, something like this
5719 1.6) <-- (registers reply to step #1.3)
5721 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5724 To solve this, whenever we parse a %Stop notification successfully,
5725 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5726 doing whatever we were doing:
5732 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5733 2.5) <-- (registers reply to step #2.3)
5735 Eventualy after step #2.5, we return to the event loop, which
5736 notices there's an event on the
5737 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5738 associated callback --- the function below. At this point, we're
5739 always safe to start a vStopped sequence. :
5742 2.7) <-- T05 thread:2
5748 remote_notif_get_pending_events (struct notif_client *nc)
5750 struct remote_state *rs = get_remote_state ();
5752 if (rs->notif_state->pending_event[nc->id] != NULL)
5755 fprintf_unfiltered (gdb_stdlog,
5756 "notif: process: '%s' ack pending event\n",
5760 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5761 rs->notif_state->pending_event[nc->id] = NULL;
5765 getpkt (&rs->buf, &rs->buf_size, 0);
5766 if (strcmp (rs->buf, "OK") == 0)
5769 remote_notif_ack (nc, rs->buf);
5775 fprintf_unfiltered (gdb_stdlog,
5776 "notif: process: '%s' no pending reply\n",
5781 /* Called when it is decided that STOP_REPLY holds the info of the
5782 event that is to be returned to the core. This function always
5783 destroys STOP_REPLY. */
5786 process_stop_reply (struct stop_reply *stop_reply,
5787 struct target_waitstatus *status)
5791 *status = stop_reply->ws;
5792 ptid = stop_reply->ptid;
5794 /* If no thread/process was reported by the stub, assume the current
5796 if (ptid_equal (ptid, null_ptid))
5797 ptid = inferior_ptid;
5799 if (status->kind != TARGET_WAITKIND_EXITED
5800 && status->kind != TARGET_WAITKIND_SIGNALLED)
5802 struct remote_state *rs = get_remote_state ();
5804 /* Expedited registers. */
5805 if (stop_reply->regcache)
5807 struct regcache *regcache
5808 = get_thread_arch_regcache (ptid, target_gdbarch ());
5813 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5815 regcache_raw_supply (regcache, reg->num, reg->data);
5816 VEC_free (cached_reg_t, stop_reply->regcache);
5819 rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5820 rs->remote_watch_data_address = stop_reply->watch_data_address;
5822 remote_notice_new_inferior (ptid, 0);
5823 demand_private_info (ptid)->core = stop_reply->core;
5826 stop_reply_xfree (stop_reply);
5830 /* The non-stop mode version of target_wait. */
5833 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5835 struct remote_state *rs = get_remote_state ();
5836 struct stop_reply *stop_reply;
5840 /* If in non-stop mode, get out of getpkt even if a
5841 notification is received. */
5843 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5844 0 /* forever */, &is_notif);
5847 if (ret != -1 && !is_notif)
5850 case 'E': /* Error of some sort. */
5851 /* We're out of sync with the target now. Did it continue
5852 or not? We can't tell which thread it was in non-stop,
5853 so just ignore this. */
5854 warning (_("Remote failure reply: %s"), rs->buf);
5856 case 'O': /* Console output. */
5857 remote_console_output (rs->buf + 1);
5860 warning (_("Invalid remote reply: %s"), rs->buf);
5864 /* Acknowledge a pending stop reply that may have arrived in the
5866 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
5867 remote_notif_get_pending_events (¬if_client_stop);
5869 /* If indeed we noticed a stop reply, we're done. */
5870 stop_reply = queued_stop_reply (ptid);
5871 if (stop_reply != NULL)
5872 return process_stop_reply (stop_reply, status);
5874 /* Still no event. If we're just polling for an event, then
5875 return to the event loop. */
5876 if (options & TARGET_WNOHANG)
5878 status->kind = TARGET_WAITKIND_IGNORE;
5879 return minus_one_ptid;
5882 /* Otherwise do a blocking wait. */
5883 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5884 1 /* forever */, &is_notif);
5888 /* Wait until the remote machine stops, then return, storing status in
5889 STATUS just as `wait' would. */
5892 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5894 struct remote_state *rs = get_remote_state ();
5895 ptid_t event_ptid = null_ptid;
5897 struct stop_reply *stop_reply;
5901 status->kind = TARGET_WAITKIND_IGNORE;
5902 status->value.integer = 0;
5904 stop_reply = queued_stop_reply (ptid);
5905 if (stop_reply != NULL)
5906 return process_stop_reply (stop_reply, status);
5908 if (rs->cached_wait_status)
5909 /* Use the cached wait status, but only once. */
5910 rs->cached_wait_status = 0;
5916 if (!target_is_async_p ())
5918 ofunc = signal (SIGINT, sync_remote_interrupt);
5919 /* If the user hit C-c before this packet, or between packets,
5920 pretend that it was hit right here. */
5921 if (check_quit_flag ())
5924 sync_remote_interrupt (SIGINT);
5928 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5929 _never_ wait for ever -> test on target_is_async_p().
5930 However, before we do that we need to ensure that the caller
5931 knows how to take the target into/out of async mode. */
5932 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5933 wait_forever_enabled_p, &is_notif);
5935 if (!target_is_async_p ())
5936 signal (SIGINT, ofunc);
5938 /* GDB gets a notification. Return to core as this event is
5940 if (ret != -1 && is_notif)
5941 return minus_one_ptid;
5946 rs->remote_stopped_by_watchpoint_p = 0;
5948 /* We got something. */
5949 rs->waiting_for_stop_reply = 0;
5951 /* Assume that the target has acknowledged Ctrl-C unless we receive
5952 an 'F' or 'O' packet. */
5953 if (buf[0] != 'F' && buf[0] != 'O')
5954 rs->ctrlc_pending_p = 0;
5958 case 'E': /* Error of some sort. */
5959 /* We're out of sync with the target now. Did it continue or
5960 not? Not is more likely, so report a stop. */
5961 warning (_("Remote failure reply: %s"), buf);
5962 status->kind = TARGET_WAITKIND_STOPPED;
5963 status->value.sig = GDB_SIGNAL_0;
5965 case 'F': /* File-I/O request. */
5966 remote_fileio_request (buf, rs->ctrlc_pending_p);
5967 rs->ctrlc_pending_p = 0;
5969 case 'T': case 'S': case 'X': case 'W':
5971 struct stop_reply *stop_reply
5972 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
5975 event_ptid = process_stop_reply (stop_reply, status);
5978 case 'O': /* Console output. */
5979 remote_console_output (buf + 1);
5981 /* The target didn't really stop; keep waiting. */
5982 rs->waiting_for_stop_reply = 1;
5986 if (rs->last_sent_signal != GDB_SIGNAL_0)
5988 /* Zero length reply means that we tried 'S' or 'C' and the
5989 remote system doesn't support it. */
5990 target_terminal_ours_for_output ();
5992 ("Can't send signals to this remote system. %s not sent.\n",
5993 gdb_signal_to_name (rs->last_sent_signal));
5994 rs->last_sent_signal = GDB_SIGNAL_0;
5995 target_terminal_inferior ();
5997 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
5998 putpkt ((char *) buf);
6000 /* We just told the target to resume, so a stop reply is in
6002 rs->waiting_for_stop_reply = 1;
6005 /* else fallthrough */
6007 warning (_("Invalid remote reply: %s"), buf);
6009 rs->waiting_for_stop_reply = 1;
6013 if (status->kind == TARGET_WAITKIND_IGNORE)
6015 /* Nothing interesting happened. If we're doing a non-blocking
6016 poll, we're done. Otherwise, go back to waiting. */
6017 if (options & TARGET_WNOHANG)
6018 return minus_one_ptid;
6022 else if (status->kind != TARGET_WAITKIND_EXITED
6023 && status->kind != TARGET_WAITKIND_SIGNALLED)
6025 if (!ptid_equal (event_ptid, null_ptid))
6026 record_currthread (rs, event_ptid);
6028 event_ptid = inferior_ptid;
6031 /* A process exit. Invalidate our notion of current thread. */
6032 record_currthread (rs, minus_one_ptid);
6037 /* Wait until the remote machine stops, then return, storing status in
6038 STATUS just as `wait' would. */
6041 remote_wait (struct target_ops *ops,
6042 ptid_t ptid, struct target_waitstatus *status, int options)
6047 event_ptid = remote_wait_ns (ptid, status, options);
6049 event_ptid = remote_wait_as (ptid, status, options);
6051 if (target_is_async_p ())
6053 /* If there are are events left in the queue tell the event loop
6055 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6056 mark_async_event_handler (remote_async_inferior_event_token);
6062 /* Fetch a single register using a 'p' packet. */
6065 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6067 struct remote_state *rs = get_remote_state ();
6069 char regp[MAX_REGISTER_SIZE];
6072 if (packet_support (PACKET_p) == PACKET_DISABLE)
6075 if (reg->pnum == -1)
6080 p += hexnumstr (p, reg->pnum);
6083 getpkt (&rs->buf, &rs->buf_size, 0);
6087 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6091 case PACKET_UNKNOWN:
6094 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6095 gdbarch_register_name (get_regcache_arch (regcache),
6100 /* If this register is unfetchable, tell the regcache. */
6103 regcache_raw_supply (regcache, reg->regnum, NULL);
6107 /* Otherwise, parse and supply the value. */
6113 error (_("fetch_register_using_p: early buf termination"));
6115 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6118 regcache_raw_supply (regcache, reg->regnum, regp);
6122 /* Fetch the registers included in the target's 'g' packet. */
6125 send_g_packet (void)
6127 struct remote_state *rs = get_remote_state ();
6130 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6131 remote_send (&rs->buf, &rs->buf_size);
6133 /* We can get out of synch in various cases. If the first character
6134 in the buffer is not a hex character, assume that has happened
6135 and try to fetch another packet to read. */
6136 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6137 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6138 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6139 && rs->buf[0] != 'x') /* New: unavailable register value. */
6142 fprintf_unfiltered (gdb_stdlog,
6143 "Bad register packet; fetching a new packet\n");
6144 getpkt (&rs->buf, &rs->buf_size, 0);
6147 buf_len = strlen (rs->buf);
6149 /* Sanity check the received packet. */
6150 if (buf_len % 2 != 0)
6151 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6157 process_g_packet (struct regcache *regcache)
6159 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6160 struct remote_state *rs = get_remote_state ();
6161 struct remote_arch_state *rsa = get_remote_arch_state ();
6166 buf_len = strlen (rs->buf);
6168 /* Further sanity checks, with knowledge of the architecture. */
6169 if (buf_len > 2 * rsa->sizeof_g_packet)
6170 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6172 /* Save the size of the packet sent to us by the target. It is used
6173 as a heuristic when determining the max size of packets that the
6174 target can safely receive. */
6175 if (rsa->actual_register_packet_size == 0)
6176 rsa->actual_register_packet_size = buf_len;
6178 /* If this is smaller than we guessed the 'g' packet would be,
6179 update our records. A 'g' reply that doesn't include a register's
6180 value implies either that the register is not available, or that
6181 the 'p' packet must be used. */
6182 if (buf_len < 2 * rsa->sizeof_g_packet)
6184 rsa->sizeof_g_packet = buf_len / 2;
6186 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6188 if (rsa->regs[i].pnum == -1)
6191 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6192 rsa->regs[i].in_g_packet = 0;
6194 rsa->regs[i].in_g_packet = 1;
6198 regs = alloca (rsa->sizeof_g_packet);
6200 /* Unimplemented registers read as all bits zero. */
6201 memset (regs, 0, rsa->sizeof_g_packet);
6203 /* Reply describes registers byte by byte, each byte encoded as two
6204 hex characters. Suck them all up, then supply them to the
6205 register cacheing/storage mechanism. */
6208 for (i = 0; i < rsa->sizeof_g_packet; i++)
6210 if (p[0] == 0 || p[1] == 0)
6211 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6212 internal_error (__FILE__, __LINE__,
6213 _("unexpected end of 'g' packet reply"));
6215 if (p[0] == 'x' && p[1] == 'x')
6216 regs[i] = 0; /* 'x' */
6218 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6222 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6224 struct packet_reg *r = &rsa->regs[i];
6228 if (r->offset * 2 >= strlen (rs->buf))
6229 /* This shouldn't happen - we adjusted in_g_packet above. */
6230 internal_error (__FILE__, __LINE__,
6231 _("unexpected end of 'g' packet reply"));
6232 else if (rs->buf[r->offset * 2] == 'x')
6234 gdb_assert (r->offset * 2 < strlen (rs->buf));
6235 /* The register isn't available, mark it as such (at
6236 the same time setting the value to zero). */
6237 regcache_raw_supply (regcache, r->regnum, NULL);
6240 regcache_raw_supply (regcache, r->regnum,
6247 fetch_registers_using_g (struct regcache *regcache)
6250 process_g_packet (regcache);
6253 /* Make the remote selected traceframe match GDB's selected
6257 set_remote_traceframe (void)
6260 struct remote_state *rs = get_remote_state ();
6262 if (rs->remote_traceframe_number == get_traceframe_number ())
6265 /* Avoid recursion, remote_trace_find calls us again. */
6266 rs->remote_traceframe_number = get_traceframe_number ();
6268 newnum = target_trace_find (tfind_number,
6269 get_traceframe_number (), 0, 0, NULL);
6271 /* Should not happen. If it does, all bets are off. */
6272 if (newnum != get_traceframe_number ())
6273 warning (_("could not set remote traceframe"));
6277 remote_fetch_registers (struct target_ops *ops,
6278 struct regcache *regcache, int regnum)
6280 struct remote_arch_state *rsa = get_remote_arch_state ();
6283 set_remote_traceframe ();
6284 set_general_thread (inferior_ptid);
6288 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6290 gdb_assert (reg != NULL);
6292 /* If this register might be in the 'g' packet, try that first -
6293 we are likely to read more than one register. If this is the
6294 first 'g' packet, we might be overly optimistic about its
6295 contents, so fall back to 'p'. */
6296 if (reg->in_g_packet)
6298 fetch_registers_using_g (regcache);
6299 if (reg->in_g_packet)
6303 if (fetch_register_using_p (regcache, reg))
6306 /* This register is not available. */
6307 regcache_raw_supply (regcache, reg->regnum, NULL);
6312 fetch_registers_using_g (regcache);
6314 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6315 if (!rsa->regs[i].in_g_packet)
6316 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6318 /* This register is not available. */
6319 regcache_raw_supply (regcache, i, NULL);
6323 /* Prepare to store registers. Since we may send them all (using a
6324 'G' request), we have to read out the ones we don't want to change
6328 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6330 struct remote_arch_state *rsa = get_remote_arch_state ();
6332 gdb_byte buf[MAX_REGISTER_SIZE];
6334 /* Make sure the entire registers array is valid. */
6335 switch (packet_support (PACKET_P))
6337 case PACKET_DISABLE:
6338 case PACKET_SUPPORT_UNKNOWN:
6339 /* Make sure all the necessary registers are cached. */
6340 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6341 if (rsa->regs[i].in_g_packet)
6342 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6349 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6350 packet was not recognized. */
6353 store_register_using_P (const struct regcache *regcache,
6354 struct packet_reg *reg)
6356 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6357 struct remote_state *rs = get_remote_state ();
6358 /* Try storing a single register. */
6359 char *buf = rs->buf;
6360 gdb_byte regp[MAX_REGISTER_SIZE];
6363 if (packet_support (PACKET_P) == PACKET_DISABLE)
6366 if (reg->pnum == -1)
6369 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6370 p = buf + strlen (buf);
6371 regcache_raw_collect (regcache, reg->regnum, regp);
6372 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6374 getpkt (&rs->buf, &rs->buf_size, 0);
6376 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6381 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6382 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6383 case PACKET_UNKNOWN:
6386 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6390 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6391 contents of the register cache buffer. FIXME: ignores errors. */
6394 store_registers_using_G (const struct regcache *regcache)
6396 struct remote_state *rs = get_remote_state ();
6397 struct remote_arch_state *rsa = get_remote_arch_state ();
6401 /* Extract all the registers in the regcache copying them into a
6406 regs = alloca (rsa->sizeof_g_packet);
6407 memset (regs, 0, rsa->sizeof_g_packet);
6408 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6410 struct packet_reg *r = &rsa->regs[i];
6413 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6417 /* Command describes registers byte by byte,
6418 each byte encoded as two hex characters. */
6421 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6423 bin2hex (regs, p, rsa->sizeof_g_packet);
6425 getpkt (&rs->buf, &rs->buf_size, 0);
6426 if (packet_check_result (rs->buf) == PACKET_ERROR)
6427 error (_("Could not write registers; remote failure reply '%s'"),
6431 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6432 of the register cache buffer. FIXME: ignores errors. */
6435 remote_store_registers (struct target_ops *ops,
6436 struct regcache *regcache, int regnum)
6438 struct remote_arch_state *rsa = get_remote_arch_state ();
6441 set_remote_traceframe ();
6442 set_general_thread (inferior_ptid);
6446 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6448 gdb_assert (reg != NULL);
6450 /* Always prefer to store registers using the 'P' packet if
6451 possible; we often change only a small number of registers.
6452 Sometimes we change a larger number; we'd need help from a
6453 higher layer to know to use 'G'. */
6454 if (store_register_using_P (regcache, reg))
6457 /* For now, don't complain if we have no way to write the
6458 register. GDB loses track of unavailable registers too
6459 easily. Some day, this may be an error. We don't have
6460 any way to read the register, either... */
6461 if (!reg->in_g_packet)
6464 store_registers_using_G (regcache);
6468 store_registers_using_G (regcache);
6470 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6471 if (!rsa->regs[i].in_g_packet)
6472 if (!store_register_using_P (regcache, &rsa->regs[i]))
6473 /* See above for why we do not issue an error here. */
6478 /* Return the number of hex digits in num. */
6481 hexnumlen (ULONGEST num)
6485 for (i = 0; num != 0; i++)
6491 /* Set BUF to the minimum number of hex digits representing NUM. */
6494 hexnumstr (char *buf, ULONGEST num)
6496 int len = hexnumlen (num);
6498 return hexnumnstr (buf, num, len);
6502 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6505 hexnumnstr (char *buf, ULONGEST num, int width)
6511 for (i = width - 1; i >= 0; i--)
6513 buf[i] = "0123456789abcdef"[(num & 0xf)];
6520 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6523 remote_address_masked (CORE_ADDR addr)
6525 unsigned int address_size = remote_address_size;
6527 /* If "remoteaddresssize" was not set, default to target address size. */
6529 address_size = gdbarch_addr_bit (target_gdbarch ());
6531 if (address_size > 0
6532 && address_size < (sizeof (ULONGEST) * 8))
6534 /* Only create a mask when that mask can safely be constructed
6535 in a ULONGEST variable. */
6538 mask = (mask << address_size) - 1;
6544 /* Determine whether the remote target supports binary downloading.
6545 This is accomplished by sending a no-op memory write of zero length
6546 to the target at the specified address. It does not suffice to send
6547 the whole packet, since many stubs strip the eighth bit and
6548 subsequently compute a wrong checksum, which causes real havoc with
6551 NOTE: This can still lose if the serial line is not eight-bit
6552 clean. In cases like this, the user should clear "remote
6556 check_binary_download (CORE_ADDR addr)
6558 struct remote_state *rs = get_remote_state ();
6560 switch (packet_support (PACKET_X))
6562 case PACKET_DISABLE:
6566 case PACKET_SUPPORT_UNKNOWN:
6572 p += hexnumstr (p, (ULONGEST) addr);
6574 p += hexnumstr (p, (ULONGEST) 0);
6578 putpkt_binary (rs->buf, (int) (p - rs->buf));
6579 getpkt (&rs->buf, &rs->buf_size, 0);
6581 if (rs->buf[0] == '\0')
6584 fprintf_unfiltered (gdb_stdlog,
6585 "binary downloading NOT "
6586 "supported by target\n");
6587 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6592 fprintf_unfiltered (gdb_stdlog,
6593 "binary downloading supported by target\n");
6594 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6601 /* Write memory data directly to the remote machine.
6602 This does not inform the data cache; the data cache uses this.
6603 HEADER is the starting part of the packet.
6604 MEMADDR is the address in the remote memory space.
6605 MYADDR is the address of the buffer in our space.
6606 LEN is the number of bytes.
6607 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6608 should send data as binary ('X'), or hex-encoded ('M').
6610 The function creates packet of the form
6611 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6613 where encoding of <DATA> is termined by PACKET_FORMAT.
6615 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6618 Return the transferred status, error or OK (an
6619 'enum target_xfer_status' value). Save the number of bytes
6620 transferred in *XFERED_LEN. Only transfer a single packet. */
6622 static enum target_xfer_status
6623 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6624 const gdb_byte *myaddr, ULONGEST len,
6625 ULONGEST *xfered_len, char packet_format,
6628 struct remote_state *rs = get_remote_state ();
6638 if (packet_format != 'X' && packet_format != 'M')
6639 internal_error (__FILE__, __LINE__,
6640 _("remote_write_bytes_aux: bad packet format"));
6643 return TARGET_XFER_EOF;
6645 payload_size = get_memory_write_packet_size ();
6647 /* The packet buffer will be large enough for the payload;
6648 get_memory_packet_size ensures this. */
6651 /* Compute the size of the actual payload by subtracting out the
6652 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6654 payload_size -= strlen ("$,:#NN");
6656 /* The comma won't be used. */
6658 header_length = strlen (header);
6659 payload_size -= header_length;
6660 payload_size -= hexnumlen (memaddr);
6662 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6664 strcat (rs->buf, header);
6665 p = rs->buf + strlen (header);
6667 /* Compute a best guess of the number of bytes actually transfered. */
6668 if (packet_format == 'X')
6670 /* Best guess at number of bytes that will fit. */
6671 todo = min (len, payload_size);
6673 payload_size -= hexnumlen (todo);
6674 todo = min (todo, payload_size);
6678 /* Num bytes that will fit. */
6679 todo = min (len, payload_size / 2);
6681 payload_size -= hexnumlen (todo);
6682 todo = min (todo, payload_size / 2);
6686 internal_error (__FILE__, __LINE__,
6687 _("minimum packet size too small to write data"));
6689 /* If we already need another packet, then try to align the end
6690 of this packet to a useful boundary. */
6691 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6692 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6694 /* Append "<memaddr>". */
6695 memaddr = remote_address_masked (memaddr);
6696 p += hexnumstr (p, (ULONGEST) memaddr);
6703 /* Append <len>. Retain the location/size of <len>. It may need to
6704 be adjusted once the packet body has been created. */
6706 plenlen = hexnumstr (p, (ULONGEST) todo);
6714 /* Append the packet body. */
6715 if (packet_format == 'X')
6717 /* Binary mode. Send target system values byte by byte, in
6718 increasing byte addresses. Only escape certain critical
6720 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6721 &nr_bytes, payload_size);
6723 /* If not all TODO bytes fit, then we'll need another packet. Make
6724 a second try to keep the end of the packet aligned. Don't do
6725 this if the packet is tiny. */
6726 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6730 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6732 if (new_nr_bytes != nr_bytes)
6733 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6734 (gdb_byte *) p, &nr_bytes,
6738 p += payload_length;
6739 if (use_length && nr_bytes < todo)
6741 /* Escape chars have filled up the buffer prematurely,
6742 and we have actually sent fewer bytes than planned.
6743 Fix-up the length field of the packet. Use the same
6744 number of characters as before. */
6745 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6746 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6751 /* Normal mode: Send target system values byte by byte, in
6752 increasing byte addresses. Each byte is encoded as a two hex
6754 nr_bytes = bin2hex (myaddr, p, todo);
6758 putpkt_binary (rs->buf, (int) (p - rs->buf));
6759 getpkt (&rs->buf, &rs->buf_size, 0);
6761 if (rs->buf[0] == 'E')
6762 return TARGET_XFER_E_IO;
6764 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6765 fewer bytes than we'd planned. */
6766 *xfered_len = (ULONGEST) nr_bytes;
6767 return TARGET_XFER_OK;
6770 /* Write memory data directly to the remote machine.
6771 This does not inform the data cache; the data cache uses this.
6772 MEMADDR is the address in the remote memory space.
6773 MYADDR is the address of the buffer in our space.
6774 LEN is the number of bytes.
6776 Return the transferred status, error or OK (an
6777 'enum target_xfer_status' value). Save the number of bytes
6778 transferred in *XFERED_LEN. Only transfer a single packet. */
6780 static enum target_xfer_status
6781 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6782 ULONGEST *xfered_len)
6784 char *packet_format = 0;
6786 /* Check whether the target supports binary download. */
6787 check_binary_download (memaddr);
6789 switch (packet_support (PACKET_X))
6792 packet_format = "X";
6794 case PACKET_DISABLE:
6795 packet_format = "M";
6797 case PACKET_SUPPORT_UNKNOWN:
6798 internal_error (__FILE__, __LINE__,
6799 _("remote_write_bytes: bad internal state"));
6801 internal_error (__FILE__, __LINE__, _("bad switch"));
6804 return remote_write_bytes_aux (packet_format,
6805 memaddr, myaddr, len, xfered_len,
6806 packet_format[0], 1);
6809 /* Read memory data directly from the remote machine.
6810 This does not use the data cache; the data cache uses this.
6811 MEMADDR is the address in the remote memory space.
6812 MYADDR is the address of the buffer in our space.
6813 LEN is the number of bytes.
6815 Return the transferred status, error or OK (an
6816 'enum target_xfer_status' value). Save the number of bytes
6817 transferred in *XFERED_LEN. */
6819 static enum target_xfer_status
6820 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6821 ULONGEST *xfered_len)
6823 struct remote_state *rs = get_remote_state ();
6824 int max_buf_size; /* Max size of packet output buffer. */
6829 max_buf_size = get_memory_read_packet_size ();
6830 /* The packet buffer will be large enough for the payload;
6831 get_memory_packet_size ensures this. */
6833 /* Number if bytes that will fit. */
6834 todo = min (len, max_buf_size / 2);
6836 /* Construct "m"<memaddr>","<len>". */
6837 memaddr = remote_address_masked (memaddr);
6840 p += hexnumstr (p, (ULONGEST) memaddr);
6842 p += hexnumstr (p, (ULONGEST) todo);
6845 getpkt (&rs->buf, &rs->buf_size, 0);
6846 if (rs->buf[0] == 'E'
6847 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6848 && rs->buf[3] == '\0')
6849 return TARGET_XFER_E_IO;
6850 /* Reply describes memory byte by byte, each byte encoded as two hex
6853 i = hex2bin (p, myaddr, todo);
6854 /* Return what we have. Let higher layers handle partial reads. */
6855 *xfered_len = (ULONGEST) i;
6856 return TARGET_XFER_OK;
6859 /* Using the set of read-only target sections of remote, read live
6862 For interface/parameters/return description see target.h,
6865 static enum target_xfer_status
6866 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6867 ULONGEST memaddr, ULONGEST len,
6868 ULONGEST *xfered_len)
6870 struct target_section *secp;
6871 struct target_section_table *table;
6873 secp = target_section_by_addr (ops, memaddr);
6875 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6876 secp->the_bfd_section)
6879 struct target_section *p;
6880 ULONGEST memend = memaddr + len;
6882 table = target_get_section_table (ops);
6884 for (p = table->sections; p < table->sections_end; p++)
6886 if (memaddr >= p->addr)
6888 if (memend <= p->endaddr)
6890 /* Entire transfer is within this section. */
6891 return remote_read_bytes_1 (memaddr, readbuf, len,
6894 else if (memaddr >= p->endaddr)
6896 /* This section ends before the transfer starts. */
6901 /* This section overlaps the transfer. Just do half. */
6902 len = p->endaddr - memaddr;
6903 return remote_read_bytes_1 (memaddr, readbuf, len,
6910 return TARGET_XFER_EOF;
6913 /* Similar to remote_read_bytes_1, but it reads from the remote stub
6914 first if the requested memory is unavailable in traceframe.
6915 Otherwise, fall back to remote_read_bytes_1. */
6917 static enum target_xfer_status
6918 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6919 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
6922 return TARGET_XFER_EOF;
6924 if (get_traceframe_number () != -1)
6926 VEC(mem_range_s) *available;
6928 /* If we fail to get the set of available memory, then the
6929 target does not support querying traceframe info, and so we
6930 attempt reading from the traceframe anyway (assuming the
6931 target implements the old QTro packet then). */
6932 if (traceframe_available_memory (&available, memaddr, len))
6934 struct cleanup *old_chain;
6936 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6938 if (VEC_empty (mem_range_s, available)
6939 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6941 enum target_xfer_status res;
6943 /* Don't read into the traceframe's available
6945 if (!VEC_empty (mem_range_s, available))
6947 LONGEST oldlen = len;
6949 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
6950 gdb_assert (len <= oldlen);
6953 do_cleanups (old_chain);
6955 /* This goes through the topmost target again. */
6956 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
6958 if (res == TARGET_XFER_OK)
6959 return TARGET_XFER_OK;
6962 /* No use trying further, we know some memory starting
6963 at MEMADDR isn't available. */
6965 return TARGET_XFER_UNAVAILABLE;
6969 /* Don't try to read more than how much is available, in
6970 case the target implements the deprecated QTro packet to
6971 cater for older GDBs (the target's knowledge of read-only
6972 sections may be outdated by now). */
6973 len = VEC_index (mem_range_s, available, 0)->length;
6975 do_cleanups (old_chain);
6979 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
6984 /* Sends a packet with content determined by the printf format string
6985 FORMAT and the remaining arguments, then gets the reply. Returns
6986 whether the packet was a success, a failure, or unknown. */
6988 static enum packet_result
6989 remote_send_printf (const char *format, ...)
6991 struct remote_state *rs = get_remote_state ();
6992 int max_size = get_remote_packet_size ();
6995 va_start (ap, format);
6998 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6999 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7001 if (putpkt (rs->buf) < 0)
7002 error (_("Communication problem with target."));
7005 getpkt (&rs->buf, &rs->buf_size, 0);
7007 return packet_check_result (rs->buf);
7011 restore_remote_timeout (void *p)
7013 int value = *(int *)p;
7015 remote_timeout = value;
7018 /* Flash writing can take quite some time. We'll set
7019 effectively infinite timeout for flash operations.
7020 In future, we'll need to decide on a better approach. */
7021 static const int remote_flash_timeout = 1000;
7024 remote_flash_erase (struct target_ops *ops,
7025 ULONGEST address, LONGEST length)
7027 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7028 int saved_remote_timeout = remote_timeout;
7029 enum packet_result ret;
7030 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7031 &saved_remote_timeout);
7033 remote_timeout = remote_flash_timeout;
7035 ret = remote_send_printf ("vFlashErase:%s,%s",
7036 phex (address, addr_size),
7040 case PACKET_UNKNOWN:
7041 error (_("Remote target does not support flash erase"));
7043 error (_("Error erasing flash with vFlashErase packet"));
7048 do_cleanups (back_to);
7051 static enum target_xfer_status
7052 remote_flash_write (struct target_ops *ops, ULONGEST address,
7053 ULONGEST length, ULONGEST *xfered_len,
7054 const gdb_byte *data)
7056 int saved_remote_timeout = remote_timeout;
7057 enum target_xfer_status ret;
7058 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7059 &saved_remote_timeout);
7061 remote_timeout = remote_flash_timeout;
7062 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7064 do_cleanups (back_to);
7070 remote_flash_done (struct target_ops *ops)
7072 int saved_remote_timeout = remote_timeout;
7074 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7075 &saved_remote_timeout);
7077 remote_timeout = remote_flash_timeout;
7078 ret = remote_send_printf ("vFlashDone");
7079 do_cleanups (back_to);
7083 case PACKET_UNKNOWN:
7084 error (_("Remote target does not support vFlashDone"));
7086 error (_("Error finishing flash operation"));
7093 remote_files_info (struct target_ops *ignore)
7095 puts_filtered ("Debugging a target over a serial line.\n");
7098 /* Stuff for dealing with the packets which are part of this protocol.
7099 See comment at top of file for details. */
7101 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7102 error to higher layers. Called when a serial error is detected.
7103 The exception message is STRING, followed by a colon and a blank,
7104 the system error message for errno at function entry and final dot
7105 for output compatibility with throw_perror_with_name. */
7108 unpush_and_perror (const char *string)
7110 int saved_errno = errno;
7112 remote_unpush_target ();
7113 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7114 safe_strerror (saved_errno));
7117 /* Read a single character from the remote end. */
7120 readchar (int timeout)
7123 struct remote_state *rs = get_remote_state ();
7125 ch = serial_readchar (rs->remote_desc, timeout);
7130 switch ((enum serial_rc) ch)
7133 remote_unpush_target ();
7134 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7137 unpush_and_perror (_("Remote communication error. "
7138 "Target disconnected."));
7140 case SERIAL_TIMEOUT:
7146 /* Wrapper for serial_write that closes the target and throws if
7150 remote_serial_write (const char *str, int len)
7152 struct remote_state *rs = get_remote_state ();
7154 if (serial_write (rs->remote_desc, str, len))
7156 unpush_and_perror (_("Remote communication error. "
7157 "Target disconnected."));
7161 /* Send the command in *BUF to the remote machine, and read the reply
7162 into *BUF. Report an error if we get an error reply. Resize
7163 *BUF using xrealloc if necessary to hold the result, and update
7167 remote_send (char **buf,
7171 getpkt (buf, sizeof_buf, 0);
7173 if ((*buf)[0] == 'E')
7174 error (_("Remote failure reply: %s"), *buf);
7177 /* Return a pointer to an xmalloc'ed string representing an escaped
7178 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7179 etc. The caller is responsible for releasing the returned
7183 escape_buffer (const char *buf, int n)
7185 struct cleanup *old_chain;
7186 struct ui_file *stb;
7189 stb = mem_fileopen ();
7190 old_chain = make_cleanup_ui_file_delete (stb);
7192 fputstrn_unfiltered (buf, n, '\\', stb);
7193 str = ui_file_xstrdup (stb, NULL);
7194 do_cleanups (old_chain);
7198 /* Display a null-terminated packet on stdout, for debugging, using C
7202 print_packet (const char *buf)
7204 puts_filtered ("\"");
7205 fputstr_filtered (buf, '"', gdb_stdout);
7206 puts_filtered ("\"");
7210 putpkt (const char *buf)
7212 return putpkt_binary (buf, strlen (buf));
7215 /* Send a packet to the remote machine, with error checking. The data
7216 of the packet is in BUF. The string in BUF can be at most
7217 get_remote_packet_size () - 5 to account for the $, # and checksum,
7218 and for a possible /0 if we are debugging (remote_debug) and want
7219 to print the sent packet as a string. */
7222 putpkt_binary (const char *buf, int cnt)
7224 struct remote_state *rs = get_remote_state ();
7226 unsigned char csum = 0;
7227 char *buf2 = alloca (cnt + 6);
7234 /* Catch cases like trying to read memory or listing threads while
7235 we're waiting for a stop reply. The remote server wouldn't be
7236 ready to handle this request, so we'd hang and timeout. We don't
7237 have to worry about this in synchronous mode, because in that
7238 case it's not possible to issue a command while the target is
7239 running. This is not a problem in non-stop mode, because in that
7240 case, the stub is always ready to process serial input. */
7241 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7243 error (_("Cannot execute this command while the target is running.\n"
7244 "Use the \"interrupt\" command to stop the target\n"
7245 "and then try again."));
7248 /* We're sending out a new packet. Make sure we don't look at a
7249 stale cached response. */
7250 rs->cached_wait_status = 0;
7252 /* Copy the packet into buffer BUF2, encapsulating it
7253 and giving it a checksum. */
7258 for (i = 0; i < cnt; i++)
7264 *p++ = tohex ((csum >> 4) & 0xf);
7265 *p++ = tohex (csum & 0xf);
7267 /* Send it over and over until we get a positive ack. */
7271 int started_error_output = 0;
7275 struct cleanup *old_chain;
7279 str = escape_buffer (buf2, p - buf2);
7280 old_chain = make_cleanup (xfree, str);
7281 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7282 gdb_flush (gdb_stdlog);
7283 do_cleanups (old_chain);
7285 remote_serial_write (buf2, p - buf2);
7287 /* If this is a no acks version of the remote protocol, send the
7288 packet and move on. */
7292 /* Read until either a timeout occurs (-2) or '+' is read.
7293 Handle any notification that arrives in the mean time. */
7296 ch = readchar (remote_timeout);
7304 case SERIAL_TIMEOUT:
7307 if (started_error_output)
7309 putchar_unfiltered ('\n');
7310 started_error_output = 0;
7319 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7323 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7325 case SERIAL_TIMEOUT:
7329 break; /* Retransmit buffer. */
7333 fprintf_unfiltered (gdb_stdlog,
7334 "Packet instead of Ack, ignoring it\n");
7335 /* It's probably an old response sent because an ACK
7336 was lost. Gobble up the packet and ack it so it
7337 doesn't get retransmitted when we resend this
7340 remote_serial_write ("+", 1);
7341 continue; /* Now, go look for +. */
7348 /* If we got a notification, handle it, and go back to looking
7350 /* We've found the start of a notification. Now
7351 collect the data. */
7352 val = read_frame (&rs->buf, &rs->buf_size);
7357 struct cleanup *old_chain;
7360 str = escape_buffer (rs->buf, val);
7361 old_chain = make_cleanup (xfree, str);
7362 fprintf_unfiltered (gdb_stdlog,
7363 " Notification received: %s\n",
7365 do_cleanups (old_chain);
7367 handle_notification (rs->notif_state, rs->buf);
7368 /* We're in sync now, rewait for the ack. */
7375 if (!started_error_output)
7377 started_error_output = 1;
7378 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7380 fputc_unfiltered (ch & 0177, gdb_stdlog);
7381 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7390 if (!started_error_output)
7392 started_error_output = 1;
7393 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7395 fputc_unfiltered (ch & 0177, gdb_stdlog);
7399 break; /* Here to retransmit. */
7403 /* This is wrong. If doing a long backtrace, the user should be
7404 able to get out next time we call QUIT, without anything as
7405 violent as interrupt_query. If we want to provide a way out of
7406 here without getting to the next QUIT, it should be based on
7407 hitting ^C twice as in remote_wait. */
7418 /* Come here after finding the start of a frame when we expected an
7419 ack. Do our best to discard the rest of this packet. */
7428 c = readchar (remote_timeout);
7431 case SERIAL_TIMEOUT:
7432 /* Nothing we can do. */
7435 /* Discard the two bytes of checksum and stop. */
7436 c = readchar (remote_timeout);
7438 c = readchar (remote_timeout);
7441 case '*': /* Run length encoding. */
7442 /* Discard the repeat count. */
7443 c = readchar (remote_timeout);
7448 /* A regular character. */
7454 /* Come here after finding the start of the frame. Collect the rest
7455 into *BUF, verifying the checksum, length, and handling run-length
7456 compression. NUL terminate the buffer. If there is not enough room,
7457 expand *BUF using xrealloc.
7459 Returns -1 on error, number of characters in buffer (ignoring the
7460 trailing NULL) on success. (could be extended to return one of the
7461 SERIAL status indications). */
7464 read_frame (char **buf_p,
7471 struct remote_state *rs = get_remote_state ();
7478 c = readchar (remote_timeout);
7481 case SERIAL_TIMEOUT:
7483 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7487 fputs_filtered ("Saw new packet start in middle of old one\n",
7489 return -1; /* Start a new packet, count retries. */
7492 unsigned char pktcsum;
7498 check_0 = readchar (remote_timeout);
7500 check_1 = readchar (remote_timeout);
7502 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7505 fputs_filtered ("Timeout in checksum, retrying\n",
7509 else if (check_0 < 0 || check_1 < 0)
7512 fputs_filtered ("Communication error in checksum\n",
7517 /* Don't recompute the checksum; with no ack packets we
7518 don't have any way to indicate a packet retransmission
7523 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7524 if (csum == pktcsum)
7529 struct cleanup *old_chain;
7532 str = escape_buffer (buf, bc);
7533 old_chain = make_cleanup (xfree, str);
7534 fprintf_unfiltered (gdb_stdlog,
7535 "Bad checksum, sentsum=0x%x, "
7536 "csum=0x%x, buf=%s\n",
7537 pktcsum, csum, str);
7538 do_cleanups (old_chain);
7540 /* Number of characters in buffer ignoring trailing
7544 case '*': /* Run length encoding. */
7549 c = readchar (remote_timeout);
7551 repeat = c - ' ' + 3; /* Compute repeat count. */
7553 /* The character before ``*'' is repeated. */
7555 if (repeat > 0 && repeat <= 255 && bc > 0)
7557 if (bc + repeat - 1 >= *sizeof_buf - 1)
7559 /* Make some more room in the buffer. */
7560 *sizeof_buf += repeat;
7561 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7565 memset (&buf[bc], buf[bc - 1], repeat);
7571 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7575 if (bc >= *sizeof_buf - 1)
7577 /* Make some more room in the buffer. */
7579 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7590 /* Read a packet from the remote machine, with error checking, and
7591 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7592 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7593 rather than timing out; this is used (in synchronous mode) to wait
7594 for a target that is is executing user code to stop. */
7595 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7596 don't have to change all the calls to getpkt to deal with the
7597 return value, because at the moment I don't know what the right
7598 thing to do it for those. */
7606 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7610 /* Read a packet from the remote machine, with error checking, and
7611 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7612 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7613 rather than timing out; this is used (in synchronous mode) to wait
7614 for a target that is is executing user code to stop. If FOREVER ==
7615 0, this function is allowed to time out gracefully and return an
7616 indication of this to the caller. Otherwise return the number of
7617 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7618 enough reason to return to the caller. *IS_NOTIF is an output
7619 boolean that indicates whether *BUF holds a notification or not
7620 (a regular packet). */
7623 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7624 int expecting_notif, int *is_notif)
7626 struct remote_state *rs = get_remote_state ();
7632 /* We're reading a new response. Make sure we don't look at a
7633 previously cached response. */
7634 rs->cached_wait_status = 0;
7636 strcpy (*buf, "timeout");
7639 timeout = watchdog > 0 ? watchdog : -1;
7640 else if (expecting_notif)
7641 timeout = 0; /* There should already be a char in the buffer. If
7644 timeout = remote_timeout;
7648 /* Process any number of notifications, and then return when
7652 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
7654 for (tries = 1; tries <= MAX_TRIES; tries++)
7656 /* This can loop forever if the remote side sends us
7657 characters continuously, but if it pauses, we'll get
7658 SERIAL_TIMEOUT from readchar because of timeout. Then
7659 we'll count that as a retry.
7661 Note that even when forever is set, we will only wait
7662 forever prior to the start of a packet. After that, we
7663 expect characters to arrive at a brisk pace. They should
7664 show up within remote_timeout intervals. */
7666 c = readchar (timeout);
7667 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7669 if (c == SERIAL_TIMEOUT)
7671 if (expecting_notif)
7672 return -1; /* Don't complain, it's normal to not get
7673 anything in this case. */
7675 if (forever) /* Watchdog went off? Kill the target. */
7678 remote_unpush_target ();
7679 throw_error (TARGET_CLOSE_ERROR,
7680 _("Watchdog timeout has expired. "
7681 "Target detached."));
7684 fputs_filtered ("Timed out.\n", gdb_stdlog);
7688 /* We've found the start of a packet or notification.
7689 Now collect the data. */
7690 val = read_frame (buf, sizeof_buf);
7695 remote_serial_write ("-", 1);
7698 if (tries > MAX_TRIES)
7700 /* We have tried hard enough, and just can't receive the
7701 packet/notification. Give up. */
7702 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7704 /* Skip the ack char if we're in no-ack mode. */
7705 if (!rs->noack_mode)
7706 remote_serial_write ("+", 1);
7710 /* If we got an ordinary packet, return that to our caller. */
7715 struct cleanup *old_chain;
7718 str = escape_buffer (*buf, val);
7719 old_chain = make_cleanup (xfree, str);
7720 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7721 do_cleanups (old_chain);
7724 /* Skip the ack char if we're in no-ack mode. */
7725 if (!rs->noack_mode)
7726 remote_serial_write ("+", 1);
7727 if (is_notif != NULL)
7732 /* If we got a notification, handle it, and go back to looking
7736 gdb_assert (c == '%');
7740 struct cleanup *old_chain;
7743 str = escape_buffer (*buf, val);
7744 old_chain = make_cleanup (xfree, str);
7745 fprintf_unfiltered (gdb_stdlog,
7746 " Notification received: %s\n",
7748 do_cleanups (old_chain);
7750 if (is_notif != NULL)
7753 handle_notification (rs->notif_state, *buf);
7755 /* Notifications require no acknowledgement. */
7757 if (expecting_notif)
7764 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7766 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7770 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7773 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7779 remote_kill (struct target_ops *ops)
7781 volatile struct gdb_exception ex;
7783 /* Catch errors so the user can quit from gdb even when we
7784 aren't on speaking terms with the remote system. */
7785 TRY_CATCH (ex, RETURN_MASK_ERROR)
7791 if (ex.error == TARGET_CLOSE_ERROR)
7793 /* If we got an (EOF) error that caused the target
7794 to go away, then we're done, that's what we wanted.
7795 "k" is susceptible to cause a premature EOF, given
7796 that the remote server isn't actually required to
7797 reply to "k", and it can happen that it doesn't
7798 even get to reply ACK to the "k". */
7802 /* Otherwise, something went wrong. We didn't actually kill
7803 the target. Just propagate the exception, and let the
7804 user or higher layers decide what to do. */
7805 throw_exception (ex);
7808 /* We've killed the remote end, we get to mourn it. Since this is
7809 target remote, single-process, mourning the inferior also
7810 unpushes remote_ops. */
7811 target_mourn_inferior ();
7815 remote_vkill (int pid, struct remote_state *rs)
7817 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
7820 /* Tell the remote target to detach. */
7821 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7823 getpkt (&rs->buf, &rs->buf_size, 0);
7825 switch (packet_ok (rs->buf,
7826 &remote_protocol_packets[PACKET_vKill]))
7832 case PACKET_UNKNOWN:
7835 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7840 extended_remote_kill (struct target_ops *ops)
7843 int pid = ptid_get_pid (inferior_ptid);
7844 struct remote_state *rs = get_remote_state ();
7846 res = remote_vkill (pid, rs);
7847 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7849 /* Don't try 'k' on a multi-process aware stub -- it has no way
7850 to specify the pid. */
7854 getpkt (&rs->buf, &rs->buf_size, 0);
7855 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7858 /* Don't wait for it to die. I'm not really sure it matters whether
7859 we do or not. For the existing stubs, kill is a noop. */
7865 error (_("Can't kill process"));
7867 target_mourn_inferior ();
7871 remote_mourn (struct target_ops *ops)
7873 remote_mourn_1 (ops);
7876 /* Worker function for remote_mourn. */
7878 remote_mourn_1 (struct target_ops *target)
7880 unpush_target (target);
7882 /* remote_close takes care of doing most of the clean up. */
7883 generic_mourn_inferior ();
7887 extended_remote_mourn_1 (struct target_ops *target)
7889 struct remote_state *rs = get_remote_state ();
7891 /* In case we got here due to an error, but we're going to stay
7893 rs->waiting_for_stop_reply = 0;
7895 /* If the current general thread belonged to the process we just
7896 detached from or has exited, the remote side current general
7897 thread becomes undefined. Considering a case like this:
7899 - We just got here due to a detach.
7900 - The process that we're detaching from happens to immediately
7901 report a global breakpoint being hit in non-stop mode, in the
7902 same thread we had selected before.
7903 - GDB attaches to this process again.
7904 - This event happens to be the next event we handle.
7906 GDB would consider that the current general thread didn't need to
7907 be set on the stub side (with Hg), since for all it knew,
7908 GENERAL_THREAD hadn't changed.
7910 Notice that although in all-stop mode, the remote server always
7911 sets the current thread to the thread reporting the stop event,
7912 that doesn't happen in non-stop mode; in non-stop, the stub *must
7913 not* change the current thread when reporting a breakpoint hit,
7914 due to the decoupling of event reporting and event handling.
7916 To keep things simple, we always invalidate our notion of the
7918 record_currthread (rs, minus_one_ptid);
7920 /* Unlike "target remote", we do not want to unpush the target; then
7921 the next time the user says "run", we won't be connected. */
7923 /* Call common code to mark the inferior as not running. */
7924 generic_mourn_inferior ();
7926 if (!have_inferiors ())
7928 if (!remote_multi_process_p (rs))
7930 /* Check whether the target is running now - some remote stubs
7931 automatically restart after kill. */
7933 getpkt (&rs->buf, &rs->buf_size, 0);
7935 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7937 /* Assume that the target has been restarted. Set
7938 inferior_ptid so that bits of core GDB realizes
7939 there's something here, e.g., so that the user can
7940 say "kill" again. */
7941 inferior_ptid = magic_null_ptid;
7948 extended_remote_mourn (struct target_ops *ops)
7950 extended_remote_mourn_1 (ops);
7954 extended_remote_supports_disable_randomization (struct target_ops *self)
7956 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
7960 extended_remote_disable_randomization (int val)
7962 struct remote_state *rs = get_remote_state ();
7965 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7968 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7970 error (_("Target does not support QDisableRandomization."));
7971 if (strcmp (reply, "OK") != 0)
7972 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7976 extended_remote_run (char *args)
7978 struct remote_state *rs = get_remote_state ();
7981 /* If the user has disabled vRun support, or we have detected that
7982 support is not available, do not try it. */
7983 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
7986 strcpy (rs->buf, "vRun;");
7987 len = strlen (rs->buf);
7989 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7990 error (_("Remote file name too long for run packet"));
7991 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
7992 strlen (remote_exec_file));
7994 gdb_assert (args != NULL);
7997 struct cleanup *back_to;
8001 argv = gdb_buildargv (args);
8002 back_to = make_cleanup_freeargv (argv);
8003 for (i = 0; argv[i] != NULL; i++)
8005 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8006 error (_("Argument list too long for run packet"));
8007 rs->buf[len++] = ';';
8008 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8011 do_cleanups (back_to);
8014 rs->buf[len++] = '\0';
8017 getpkt (&rs->buf, &rs->buf_size, 0);
8019 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8022 /* We have a wait response. All is well. */
8024 case PACKET_UNKNOWN:
8027 if (remote_exec_file[0] == '\0')
8028 error (_("Running the default executable on the remote target failed; "
8029 "try \"set remote exec-file\"?"));
8031 error (_("Running \"%s\" on the remote target failed"),
8034 gdb_assert_not_reached (_("bad switch"));
8038 /* In the extended protocol we want to be able to do things like
8039 "run" and have them basically work as expected. So we need
8040 a special create_inferior function. We support changing the
8041 executable file and the command line arguments, but not the
8045 extended_remote_create_inferior (struct target_ops *ops,
8046 char *exec_file, char *args,
8047 char **env, int from_tty)
8051 struct remote_state *rs = get_remote_state ();
8053 /* If running asynchronously, register the target file descriptor
8054 with the event loop. */
8055 if (target_can_async_p ())
8056 target_async (inferior_event_handler, 0);
8058 /* Disable address space randomization if requested (and supported). */
8059 if (extended_remote_supports_disable_randomization (ops))
8060 extended_remote_disable_randomization (disable_randomization);
8062 /* Now restart the remote server. */
8063 run_worked = extended_remote_run (args) != -1;
8066 /* vRun was not supported. Fail if we need it to do what the
8068 if (remote_exec_file[0])
8069 error (_("Remote target does not support \"set remote exec-file\""));
8071 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8073 /* Fall back to "R". */
8074 extended_remote_restart ();
8077 if (!have_inferiors ())
8079 /* Clean up from the last time we ran, before we mark the target
8080 running again. This will mark breakpoints uninserted, and
8081 get_offsets may insert breakpoints. */
8082 init_thread_list ();
8083 init_wait_for_inferior ();
8086 /* vRun's success return is a stop reply. */
8087 stop_reply = run_worked ? rs->buf : NULL;
8088 add_current_inferior_and_thread (stop_reply);
8090 /* Get updated offsets, if the stub uses qOffsets. */
8095 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8096 the list of conditions (in agent expression bytecode format), if any, the
8097 target needs to evaluate. The output is placed into the packet buffer
8098 started from BUF and ended at BUF_END. */
8101 remote_add_target_side_condition (struct gdbarch *gdbarch,
8102 struct bp_target_info *bp_tgt, char *buf,
8105 struct agent_expr *aexpr = NULL;
8108 char *buf_start = buf;
8110 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8113 buf += strlen (buf);
8114 xsnprintf (buf, buf_end - buf, "%s", ";");
8117 /* Send conditions to the target and free the vector. */
8119 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8122 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8123 buf += strlen (buf);
8124 for (i = 0; i < aexpr->len; ++i)
8125 buf = pack_hex_byte (buf, aexpr->buf[i]);
8132 remote_add_target_side_commands (struct gdbarch *gdbarch,
8133 struct bp_target_info *bp_tgt, char *buf)
8135 struct agent_expr *aexpr = NULL;
8138 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8141 buf += strlen (buf);
8143 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8144 buf += strlen (buf);
8146 /* Concatenate all the agent expressions that are commands into the
8149 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8152 sprintf (buf, "X%x,", aexpr->len);
8153 buf += strlen (buf);
8154 for (i = 0; i < aexpr->len; ++i)
8155 buf = pack_hex_byte (buf, aexpr->buf[i]);
8160 /* Insert a breakpoint. On targets that have software breakpoint
8161 support, we ask the remote target to do the work; on targets
8162 which don't, we insert a traditional memory breakpoint. */
8165 remote_insert_breakpoint (struct target_ops *ops,
8166 struct gdbarch *gdbarch,
8167 struct bp_target_info *bp_tgt)
8169 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8170 If it succeeds, then set the support to PACKET_ENABLE. If it
8171 fails, and the user has explicitly requested the Z support then
8172 report an error, otherwise, mark it disabled and go on. */
8174 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8176 CORE_ADDR addr = bp_tgt->reqstd_address;
8177 struct remote_state *rs;
8180 struct condition_list *cond = NULL;
8182 /* Make sure the remote is pointing at the right process, if
8184 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8185 set_general_process ();
8187 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8189 rs = get_remote_state ();
8191 endbuf = rs->buf + get_remote_packet_size ();
8196 addr = (ULONGEST) remote_address_masked (addr);
8197 p += hexnumstr (p, addr);
8198 xsnprintf (p, endbuf - p, ",%d", bpsize);
8200 if (remote_supports_cond_breakpoints (ops))
8201 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8203 if (remote_can_run_breakpoint_commands (ops))
8204 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8207 getpkt (&rs->buf, &rs->buf_size, 0);
8209 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8214 bp_tgt->placed_address = addr;
8215 bp_tgt->placed_size = bpsize;
8217 case PACKET_UNKNOWN:
8222 /* If this breakpoint has target-side commands but this stub doesn't
8223 support Z0 packets, throw error. */
8224 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8225 throw_error (NOT_SUPPORTED_ERROR, _("\
8226 Target doesn't support breakpoints that have target side commands."));
8228 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8232 remote_remove_breakpoint (struct target_ops *ops,
8233 struct gdbarch *gdbarch,
8234 struct bp_target_info *bp_tgt)
8236 CORE_ADDR addr = bp_tgt->placed_address;
8237 struct remote_state *rs = get_remote_state ();
8239 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8242 char *endbuf = rs->buf + get_remote_packet_size ();
8244 /* Make sure the remote is pointing at the right process, if
8246 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8247 set_general_process ();
8253 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8254 p += hexnumstr (p, addr);
8255 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8258 getpkt (&rs->buf, &rs->buf_size, 0);
8260 return (rs->buf[0] == 'E');
8263 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8267 watchpoint_to_Z_packet (int type)
8272 return Z_PACKET_WRITE_WP;
8275 return Z_PACKET_READ_WP;
8278 return Z_PACKET_ACCESS_WP;
8281 internal_error (__FILE__, __LINE__,
8282 _("hw_bp_to_z: bad watchpoint type %d"), type);
8287 remote_insert_watchpoint (struct target_ops *self,
8288 CORE_ADDR addr, int len, int type,
8289 struct expression *cond)
8291 struct remote_state *rs = get_remote_state ();
8292 char *endbuf = rs->buf + get_remote_packet_size ();
8294 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8296 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8299 /* Make sure the remote is pointing at the right process, if
8301 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8302 set_general_process ();
8304 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8305 p = strchr (rs->buf, '\0');
8306 addr = remote_address_masked (addr);
8307 p += hexnumstr (p, (ULONGEST) addr);
8308 xsnprintf (p, endbuf - p, ",%x", len);
8311 getpkt (&rs->buf, &rs->buf_size, 0);
8313 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8317 case PACKET_UNKNOWN:
8322 internal_error (__FILE__, __LINE__,
8323 _("remote_insert_watchpoint: reached end of function"));
8327 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8328 CORE_ADDR start, int length)
8330 CORE_ADDR diff = remote_address_masked (addr - start);
8332 return diff < length;
8337 remote_remove_watchpoint (struct target_ops *self,
8338 CORE_ADDR addr, int len, int type,
8339 struct expression *cond)
8341 struct remote_state *rs = get_remote_state ();
8342 char *endbuf = rs->buf + get_remote_packet_size ();
8344 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8346 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8349 /* Make sure the remote is pointing at the right process, if
8351 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8352 set_general_process ();
8354 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8355 p = strchr (rs->buf, '\0');
8356 addr = remote_address_masked (addr);
8357 p += hexnumstr (p, (ULONGEST) addr);
8358 xsnprintf (p, endbuf - p, ",%x", len);
8360 getpkt (&rs->buf, &rs->buf_size, 0);
8362 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8365 case PACKET_UNKNOWN:
8370 internal_error (__FILE__, __LINE__,
8371 _("remote_remove_watchpoint: reached end of function"));
8375 int remote_hw_watchpoint_limit = -1;
8376 int remote_hw_watchpoint_length_limit = -1;
8377 int remote_hw_breakpoint_limit = -1;
8380 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8381 CORE_ADDR addr, int len)
8383 if (remote_hw_watchpoint_length_limit == 0)
8385 else if (remote_hw_watchpoint_length_limit < 0)
8387 else if (len <= remote_hw_watchpoint_length_limit)
8394 remote_check_watch_resources (struct target_ops *self,
8395 int type, int cnt, int ot)
8397 if (type == bp_hardware_breakpoint)
8399 if (remote_hw_breakpoint_limit == 0)
8401 else if (remote_hw_breakpoint_limit < 0)
8403 else if (cnt <= remote_hw_breakpoint_limit)
8408 if (remote_hw_watchpoint_limit == 0)
8410 else if (remote_hw_watchpoint_limit < 0)
8414 else if (cnt <= remote_hw_watchpoint_limit)
8421 remote_stopped_by_watchpoint (struct target_ops *ops)
8423 struct remote_state *rs = get_remote_state ();
8425 return rs->remote_stopped_by_watchpoint_p;
8429 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8431 struct remote_state *rs = get_remote_state ();
8434 if (remote_stopped_by_watchpoint (target))
8436 *addr_p = rs->remote_watch_data_address;
8445 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8446 struct bp_target_info *bp_tgt)
8448 CORE_ADDR addr = bp_tgt->reqstd_address;
8449 struct remote_state *rs;
8454 /* The length field should be set to the size of a breakpoint
8455 instruction, even though we aren't inserting one ourselves. */
8457 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8459 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8462 /* Make sure the remote is pointing at the right process, if
8464 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8465 set_general_process ();
8467 rs = get_remote_state ();
8469 endbuf = rs->buf + get_remote_packet_size ();
8475 addr = remote_address_masked (addr);
8476 p += hexnumstr (p, (ULONGEST) addr);
8477 xsnprintf (p, endbuf - p, ",%x", bpsize);
8479 if (remote_supports_cond_breakpoints (self))
8480 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8482 if (remote_can_run_breakpoint_commands (self))
8483 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8486 getpkt (&rs->buf, &rs->buf_size, 0);
8488 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8491 if (rs->buf[1] == '.')
8493 message = strchr (rs->buf + 2, '.');
8495 error (_("Remote failure reply: %s"), message + 1);
8498 case PACKET_UNKNOWN:
8501 bp_tgt->placed_address = addr;
8502 bp_tgt->placed_size = bpsize;
8505 internal_error (__FILE__, __LINE__,
8506 _("remote_insert_hw_breakpoint: reached end of function"));
8511 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8512 struct bp_target_info *bp_tgt)
8515 struct remote_state *rs = get_remote_state ();
8517 char *endbuf = rs->buf + get_remote_packet_size ();
8519 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8522 /* Make sure the remote is pointing at the right process, if
8524 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8525 set_general_process ();
8531 addr = remote_address_masked (bp_tgt->placed_address);
8532 p += hexnumstr (p, (ULONGEST) addr);
8533 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8536 getpkt (&rs->buf, &rs->buf_size, 0);
8538 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8541 case PACKET_UNKNOWN:
8546 internal_error (__FILE__, __LINE__,
8547 _("remote_remove_hw_breakpoint: reached end of function"));
8550 /* Verify memory using the "qCRC:" request. */
8553 remote_verify_memory (struct target_ops *ops,
8554 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8556 struct remote_state *rs = get_remote_state ();
8557 unsigned long host_crc, target_crc;
8560 /* It doesn't make sense to use qCRC if the remote target is
8561 connected but not running. */
8562 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8564 enum packet_result result;
8566 /* Make sure the remote is pointing at the right process. */
8567 set_general_process ();
8569 /* FIXME: assumes lma can fit into long. */
8570 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8571 (long) lma, (long) size);
8574 /* Be clever; compute the host_crc before waiting for target
8576 host_crc = xcrc32 (data, size, 0xffffffff);
8578 getpkt (&rs->buf, &rs->buf_size, 0);
8580 result = packet_ok (rs->buf,
8581 &remote_protocol_packets[PACKET_qCRC]);
8582 if (result == PACKET_ERROR)
8584 else if (result == PACKET_OK)
8586 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8587 target_crc = target_crc * 16 + fromhex (*tmp);
8589 return (host_crc == target_crc);
8593 return simple_verify_memory (ops, data, lma, size);
8596 /* compare-sections command
8598 With no arguments, compares each loadable section in the exec bfd
8599 with the same memory range on the target, and reports mismatches.
8600 Useful for verifying the image on the target against the exec file. */
8603 compare_sections_command (char *args, int from_tty)
8606 struct cleanup *old_chain;
8608 const char *sectname;
8617 error (_("command cannot be used without an exec file"));
8619 /* Make sure the remote is pointing at the right process. */
8620 set_general_process ();
8622 if (args != NULL && strcmp (args, "-r") == 0)
8628 for (s = exec_bfd->sections; s; s = s->next)
8630 if (!(s->flags & SEC_LOAD))
8631 continue; /* Skip non-loadable section. */
8633 if (read_only && (s->flags & SEC_READONLY) == 0)
8634 continue; /* Skip writeable sections */
8636 size = bfd_get_section_size (s);
8638 continue; /* Skip zero-length section. */
8640 sectname = bfd_get_section_name (exec_bfd, s);
8641 if (args && strcmp (args, sectname) != 0)
8642 continue; /* Not the section selected by user. */
8644 matched = 1; /* Do this section. */
8647 sectdata = xmalloc (size);
8648 old_chain = make_cleanup (xfree, sectdata);
8649 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8651 res = target_verify_memory (sectdata, lma, size);
8654 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8655 paddress (target_gdbarch (), lma),
8656 paddress (target_gdbarch (), lma + size));
8658 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8659 paddress (target_gdbarch (), lma),
8660 paddress (target_gdbarch (), lma + size));
8662 printf_filtered ("matched.\n");
8665 printf_filtered ("MIS-MATCHED!\n");
8669 do_cleanups (old_chain);
8672 warning (_("One or more sections of the target image does not match\n\
8673 the loaded file\n"));
8674 if (args && !matched)
8675 printf_filtered (_("No loaded section named '%s'.\n"), args);
8678 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8679 into remote target. The number of bytes written to the remote
8680 target is returned, or -1 for error. */
8682 static enum target_xfer_status
8683 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8684 const char *annex, const gdb_byte *writebuf,
8685 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
8686 struct packet_config *packet)
8690 struct remote_state *rs = get_remote_state ();
8691 int max_size = get_memory_write_packet_size ();
8693 if (packet->support == PACKET_DISABLE)
8694 return TARGET_XFER_E_IO;
8696 /* Insert header. */
8697 i = snprintf (rs->buf, max_size,
8698 "qXfer:%s:write:%s:%s:",
8699 object_name, annex ? annex : "",
8700 phex_nz (offset, sizeof offset));
8701 max_size -= (i + 1);
8703 /* Escape as much data as fits into rs->buf. */
8704 buf_len = remote_escape_output
8705 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8707 if (putpkt_binary (rs->buf, i + buf_len) < 0
8708 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8709 || packet_ok (rs->buf, packet) != PACKET_OK)
8710 return TARGET_XFER_E_IO;
8712 unpack_varlen_hex (rs->buf, &n);
8715 return TARGET_XFER_OK;
8718 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8719 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8720 number of bytes read is returned, or 0 for EOF, or -1 for error.
8721 The number of bytes read may be less than LEN without indicating an
8722 EOF. PACKET is checked and updated to indicate whether the remote
8723 target supports this object. */
8725 static enum target_xfer_status
8726 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8728 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8729 ULONGEST *xfered_len,
8730 struct packet_config *packet)
8732 struct remote_state *rs = get_remote_state ();
8733 LONGEST i, n, packet_len;
8735 if (packet->support == PACKET_DISABLE)
8736 return TARGET_XFER_E_IO;
8738 /* Check whether we've cached an end-of-object packet that matches
8740 if (rs->finished_object)
8742 if (strcmp (object_name, rs->finished_object) == 0
8743 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8744 && offset == rs->finished_offset)
8745 return TARGET_XFER_EOF;
8748 /* Otherwise, we're now reading something different. Discard
8750 xfree (rs->finished_object);
8751 xfree (rs->finished_annex);
8752 rs->finished_object = NULL;
8753 rs->finished_annex = NULL;
8756 /* Request only enough to fit in a single packet. The actual data
8757 may not, since we don't know how much of it will need to be escaped;
8758 the target is free to respond with slightly less data. We subtract
8759 five to account for the response type and the protocol frame. */
8760 n = min (get_remote_packet_size () - 5, len);
8761 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8762 object_name, annex ? annex : "",
8763 phex_nz (offset, sizeof offset),
8764 phex_nz (n, sizeof n));
8765 i = putpkt (rs->buf);
8767 return TARGET_XFER_E_IO;
8770 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8771 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8772 return TARGET_XFER_E_IO;
8774 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8775 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8777 /* 'm' means there is (or at least might be) more data after this
8778 batch. That does not make sense unless there's at least one byte
8779 of data in this reply. */
8780 if (rs->buf[0] == 'm' && packet_len == 1)
8781 error (_("Remote qXfer reply contained no data."));
8783 /* Got some data. */
8784 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8785 packet_len - 1, readbuf, n);
8787 /* 'l' is an EOF marker, possibly including a final block of data,
8788 or possibly empty. If we have the final block of a non-empty
8789 object, record this fact to bypass a subsequent partial read. */
8790 if (rs->buf[0] == 'l' && offset + i > 0)
8792 rs->finished_object = xstrdup (object_name);
8793 rs->finished_annex = xstrdup (annex ? annex : "");
8794 rs->finished_offset = offset + i;
8798 return TARGET_XFER_EOF;
8802 return TARGET_XFER_OK;
8806 static enum target_xfer_status
8807 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8808 const char *annex, gdb_byte *readbuf,
8809 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8810 ULONGEST *xfered_len)
8812 struct remote_state *rs;
8817 set_remote_traceframe ();
8818 set_general_thread (inferior_ptid);
8820 rs = get_remote_state ();
8822 /* Handle memory using the standard memory routines. */
8823 if (object == TARGET_OBJECT_MEMORY)
8825 /* If the remote target is connected but not running, we should
8826 pass this request down to a lower stratum (e.g. the executable
8828 if (!target_has_execution)
8829 return TARGET_XFER_EOF;
8831 if (writebuf != NULL)
8832 return remote_write_bytes (offset, writebuf, len, xfered_len);
8834 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
8837 /* Handle SPU memory using qxfer packets. */
8838 if (object == TARGET_OBJECT_SPU)
8841 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8842 xfered_len, &remote_protocol_packets
8843 [PACKET_qXfer_spu_read]);
8845 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8846 xfered_len, &remote_protocol_packets
8847 [PACKET_qXfer_spu_write]);
8850 /* Handle extra signal info using qxfer packets. */
8851 if (object == TARGET_OBJECT_SIGNAL_INFO)
8854 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8855 xfered_len, &remote_protocol_packets
8856 [PACKET_qXfer_siginfo_read]);
8858 return remote_write_qxfer (ops, "siginfo", annex,
8859 writebuf, offset, len, xfered_len,
8860 &remote_protocol_packets
8861 [PACKET_qXfer_siginfo_write]);
8864 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8867 return remote_read_qxfer (ops, "statictrace", annex,
8868 readbuf, offset, len, xfered_len,
8869 &remote_protocol_packets
8870 [PACKET_qXfer_statictrace_read]);
8872 return TARGET_XFER_E_IO;
8875 /* Only handle flash writes. */
8876 if (writebuf != NULL)
8882 case TARGET_OBJECT_FLASH:
8883 return remote_flash_write (ops, offset, len, xfered_len,
8887 return TARGET_XFER_E_IO;
8891 /* Map pre-existing objects onto letters. DO NOT do this for new
8892 objects!!! Instead specify new query packets. */
8895 case TARGET_OBJECT_AVR:
8899 case TARGET_OBJECT_AUXV:
8900 gdb_assert (annex == NULL);
8901 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8903 &remote_protocol_packets[PACKET_qXfer_auxv]);
8905 case TARGET_OBJECT_AVAILABLE_FEATURES:
8906 return remote_read_qxfer
8907 (ops, "features", annex, readbuf, offset, len, xfered_len,
8908 &remote_protocol_packets[PACKET_qXfer_features]);
8910 case TARGET_OBJECT_LIBRARIES:
8911 return remote_read_qxfer
8912 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
8913 &remote_protocol_packets[PACKET_qXfer_libraries]);
8915 case TARGET_OBJECT_LIBRARIES_SVR4:
8916 return remote_read_qxfer
8917 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
8918 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8920 case TARGET_OBJECT_MEMORY_MAP:
8921 gdb_assert (annex == NULL);
8922 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8924 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8926 case TARGET_OBJECT_OSDATA:
8927 /* Should only get here if we're connected. */
8928 gdb_assert (rs->remote_desc);
8929 return remote_read_qxfer
8930 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
8931 &remote_protocol_packets[PACKET_qXfer_osdata]);
8933 case TARGET_OBJECT_THREADS:
8934 gdb_assert (annex == NULL);
8935 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8937 &remote_protocol_packets[PACKET_qXfer_threads]);
8939 case TARGET_OBJECT_TRACEFRAME_INFO:
8940 gdb_assert (annex == NULL);
8941 return remote_read_qxfer
8942 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
8943 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8945 case TARGET_OBJECT_FDPIC:
8946 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8948 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8950 case TARGET_OBJECT_OPENVMS_UIB:
8951 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
8953 &remote_protocol_packets[PACKET_qXfer_uib]);
8955 case TARGET_OBJECT_BTRACE:
8956 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
8958 &remote_protocol_packets[PACKET_qXfer_btrace]);
8960 case TARGET_OBJECT_BTRACE_CONF:
8961 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
8963 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
8966 return TARGET_XFER_E_IO;
8969 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8970 large enough let the caller deal with it. */
8971 if (len < get_remote_packet_size ())
8972 return TARGET_XFER_E_IO;
8973 len = get_remote_packet_size ();
8975 /* Except for querying the minimum buffer size, target must be open. */
8976 if (!rs->remote_desc)
8977 error (_("remote query is only available after target open"));
8979 gdb_assert (annex != NULL);
8980 gdb_assert (readbuf != NULL);
8986 /* We used one buffer char for the remote protocol q command and
8987 another for the query type. As the remote protocol encapsulation
8988 uses 4 chars plus one extra in case we are debugging
8989 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8992 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8994 /* Bad caller may have sent forbidden characters. */
8995 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9000 gdb_assert (annex[i] == '\0');
9002 i = putpkt (rs->buf);
9004 return TARGET_XFER_E_IO;
9006 getpkt (&rs->buf, &rs->buf_size, 0);
9007 strcpy ((char *) readbuf, rs->buf);
9009 *xfered_len = strlen ((char *) readbuf);
9010 return TARGET_XFER_OK;
9014 remote_search_memory (struct target_ops* ops,
9015 CORE_ADDR start_addr, ULONGEST search_space_len,
9016 const gdb_byte *pattern, ULONGEST pattern_len,
9017 CORE_ADDR *found_addrp)
9019 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9020 struct remote_state *rs = get_remote_state ();
9021 int max_size = get_memory_write_packet_size ();
9022 struct packet_config *packet =
9023 &remote_protocol_packets[PACKET_qSearch_memory];
9024 /* Number of packet bytes used to encode the pattern;
9025 this could be more than PATTERN_LEN due to escape characters. */
9026 int escaped_pattern_len;
9027 /* Amount of pattern that was encodable in the packet. */
9028 int used_pattern_len;
9031 ULONGEST found_addr;
9033 /* Don't go to the target if we don't have to.
9034 This is done before checking packet->support to avoid the possibility that
9035 a success for this edge case means the facility works in general. */
9036 if (pattern_len > search_space_len)
9038 if (pattern_len == 0)
9040 *found_addrp = start_addr;
9044 /* If we already know the packet isn't supported, fall back to the simple
9045 way of searching memory. */
9047 if (packet_config_support (packet) == PACKET_DISABLE)
9049 /* Target doesn't provided special support, fall back and use the
9050 standard support (copy memory and do the search here). */
9051 return simple_search_memory (ops, start_addr, search_space_len,
9052 pattern, pattern_len, found_addrp);
9055 /* Make sure the remote is pointing at the right process. */
9056 set_general_process ();
9058 /* Insert header. */
9059 i = snprintf (rs->buf, max_size,
9060 "qSearch:memory:%s;%s;",
9061 phex_nz (start_addr, addr_size),
9062 phex_nz (search_space_len, sizeof (search_space_len)));
9063 max_size -= (i + 1);
9065 /* Escape as much data as fits into rs->buf. */
9066 escaped_pattern_len =
9067 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9068 &used_pattern_len, max_size);
9070 /* Bail if the pattern is too large. */
9071 if (used_pattern_len != pattern_len)
9072 error (_("Pattern is too large to transmit to remote target."));
9074 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9075 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9076 || packet_ok (rs->buf, packet) != PACKET_OK)
9078 /* The request may not have worked because the command is not
9079 supported. If so, fall back to the simple way. */
9080 if (packet->support == PACKET_DISABLE)
9082 return simple_search_memory (ops, start_addr, search_space_len,
9083 pattern, pattern_len, found_addrp);
9088 if (rs->buf[0] == '0')
9090 else if (rs->buf[0] == '1')
9093 if (rs->buf[1] != ',')
9094 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9095 unpack_varlen_hex (rs->buf + 2, &found_addr);
9096 *found_addrp = found_addr;
9099 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9105 remote_rcmd (struct target_ops *self, const char *command,
9106 struct ui_file *outbuf)
9108 struct remote_state *rs = get_remote_state ();
9111 if (!rs->remote_desc)
9112 error (_("remote rcmd is only available after target open"));
9114 /* Send a NULL command across as an empty command. */
9115 if (command == NULL)
9118 /* The query prefix. */
9119 strcpy (rs->buf, "qRcmd,");
9120 p = strchr (rs->buf, '\0');
9122 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9123 > get_remote_packet_size ())
9124 error (_("\"monitor\" command ``%s'' is too long."), command);
9126 /* Encode the actual command. */
9127 bin2hex ((const gdb_byte *) command, p, strlen (command));
9129 if (putpkt (rs->buf) < 0)
9130 error (_("Communication problem with target."));
9132 /* get/display the response */
9137 /* XXX - see also remote_get_noisy_reply(). */
9138 QUIT; /* Allow user to bail out with ^C. */
9140 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9142 /* Timeout. Continue to (try to) read responses.
9143 This is better than stopping with an error, assuming the stub
9144 is still executing the (long) monitor command.
9145 If needed, the user can interrupt gdb using C-c, obtaining
9146 an effect similar to stop on timeout. */
9151 error (_("Target does not support this command."));
9152 if (buf[0] == 'O' && buf[1] != 'K')
9154 remote_console_output (buf + 1); /* 'O' message from stub. */
9157 if (strcmp (buf, "OK") == 0)
9159 if (strlen (buf) == 3 && buf[0] == 'E'
9160 && isdigit (buf[1]) && isdigit (buf[2]))
9162 error (_("Protocol error with Rcmd"));
9164 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9166 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9168 fputc_unfiltered (c, outbuf);
9174 static VEC(mem_region_s) *
9175 remote_memory_map (struct target_ops *ops)
9177 VEC(mem_region_s) *result = NULL;
9178 char *text = target_read_stralloc (¤t_target,
9179 TARGET_OBJECT_MEMORY_MAP, NULL);
9183 struct cleanup *back_to = make_cleanup (xfree, text);
9185 result = parse_memory_map (text);
9186 do_cleanups (back_to);
9193 packet_command (char *args, int from_tty)
9195 struct remote_state *rs = get_remote_state ();
9197 if (!rs->remote_desc)
9198 error (_("command can only be used with remote target"));
9201 error (_("remote-packet command requires packet text as argument"));
9203 puts_filtered ("sending: ");
9204 print_packet (args);
9205 puts_filtered ("\n");
9208 getpkt (&rs->buf, &rs->buf_size, 0);
9209 puts_filtered ("received: ");
9210 print_packet (rs->buf);
9211 puts_filtered ("\n");
9215 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9217 static void display_thread_info (struct gdb_ext_thread_info *info);
9219 static void threadset_test_cmd (char *cmd, int tty);
9221 static void threadalive_test (char *cmd, int tty);
9223 static void threadlist_test_cmd (char *cmd, int tty);
9225 int get_and_display_threadinfo (threadref *ref);
9227 static void threadinfo_test_cmd (char *cmd, int tty);
9229 static int thread_display_step (threadref *ref, void *context);
9231 static void threadlist_update_test_cmd (char *cmd, int tty);
9233 static void init_remote_threadtests (void);
9235 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9238 threadset_test_cmd (char *cmd, int tty)
9240 int sample_thread = SAMPLE_THREAD;
9242 printf_filtered (_("Remote threadset test\n"));
9243 set_general_thread (sample_thread);
9248 threadalive_test (char *cmd, int tty)
9250 int sample_thread = SAMPLE_THREAD;
9251 int pid = ptid_get_pid (inferior_ptid);
9252 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9254 if (remote_thread_alive (ptid))
9255 printf_filtered ("PASS: Thread alive test\n");
9257 printf_filtered ("FAIL: Thread alive test\n");
9260 void output_threadid (char *title, threadref *ref);
9263 output_threadid (char *title, threadref *ref)
9267 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9269 printf_filtered ("%s %s\n", title, (&hexid[0]));
9273 threadlist_test_cmd (char *cmd, int tty)
9276 threadref nextthread;
9277 int done, result_count;
9278 threadref threadlist[3];
9280 printf_filtered ("Remote Threadlist test\n");
9281 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9282 &result_count, &threadlist[0]))
9283 printf_filtered ("FAIL: threadlist test\n");
9286 threadref *scan = threadlist;
9287 threadref *limit = scan + result_count;
9289 while (scan < limit)
9290 output_threadid (" thread ", scan++);
9295 display_thread_info (struct gdb_ext_thread_info *info)
9297 output_threadid ("Threadid: ", &info->threadid);
9298 printf_filtered ("Name: %s\n ", info->shortname);
9299 printf_filtered ("State: %s\n", info->display);
9300 printf_filtered ("other: %s\n\n", info->more_display);
9304 get_and_display_threadinfo (threadref *ref)
9308 struct gdb_ext_thread_info threadinfo;
9310 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9311 | TAG_MOREDISPLAY | TAG_DISPLAY;
9312 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9313 display_thread_info (&threadinfo);
9318 threadinfo_test_cmd (char *cmd, int tty)
9320 int athread = SAMPLE_THREAD;
9324 int_to_threadref (&thread, athread);
9325 printf_filtered ("Remote Threadinfo test\n");
9326 if (!get_and_display_threadinfo (&thread))
9327 printf_filtered ("FAIL cannot get thread info\n");
9331 thread_display_step (threadref *ref, void *context)
9333 /* output_threadid(" threadstep ",ref); *//* simple test */
9334 return get_and_display_threadinfo (ref);
9338 threadlist_update_test_cmd (char *cmd, int tty)
9340 printf_filtered ("Remote Threadlist update test\n");
9341 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9345 init_remote_threadtests (void)
9347 add_com ("tlist", class_obscure, threadlist_test_cmd,
9348 _("Fetch and print the remote list of "
9349 "thread identifiers, one pkt only"));
9350 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9351 _("Fetch and display info about one thread"));
9352 add_com ("tset", class_obscure, threadset_test_cmd,
9353 _("Test setting to a different thread"));
9354 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9355 _("Iterate through updating all remote thread info"));
9356 add_com ("talive", class_obscure, threadalive_test,
9357 _(" Remote thread alive test "));
9362 /* Convert a thread ID to a string. Returns the string in a static
9366 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9368 static char buf[64];
9369 struct remote_state *rs = get_remote_state ();
9371 if (ptid_equal (ptid, null_ptid))
9372 return normal_pid_to_str (ptid);
9373 else if (ptid_is_pid (ptid))
9375 /* Printing an inferior target id. */
9377 /* When multi-process extensions are off, there's no way in the
9378 remote protocol to know the remote process id, if there's any
9379 at all. There's one exception --- when we're connected with
9380 target extended-remote, and we manually attached to a process
9381 with "attach PID". We don't record anywhere a flag that
9382 allows us to distinguish that case from the case of
9383 connecting with extended-remote and the stub already being
9384 attached to a process, and reporting yes to qAttached, hence
9385 no smart special casing here. */
9386 if (!remote_multi_process_p (rs))
9388 xsnprintf (buf, sizeof buf, "Remote target");
9392 return normal_pid_to_str (ptid);
9396 if (ptid_equal (magic_null_ptid, ptid))
9397 xsnprintf (buf, sizeof buf, "Thread <main>");
9398 else if (rs->extended && remote_multi_process_p (rs))
9399 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9400 ptid_get_pid (ptid), ptid_get_lwp (ptid));
9402 xsnprintf (buf, sizeof buf, "Thread %ld",
9403 ptid_get_lwp (ptid));
9408 /* Get the address of the thread local variable in OBJFILE which is
9409 stored at OFFSET within the thread local storage for thread PTID. */
9412 remote_get_thread_local_address (struct target_ops *ops,
9413 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9415 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
9417 struct remote_state *rs = get_remote_state ();
9419 char *endp = rs->buf + get_remote_packet_size ();
9420 enum packet_result result;
9422 strcpy (p, "qGetTLSAddr:");
9424 p = write_ptid (p, endp, ptid);
9426 p += hexnumstr (p, offset);
9428 p += hexnumstr (p, lm);
9432 getpkt (&rs->buf, &rs->buf_size, 0);
9433 result = packet_ok (rs->buf,
9434 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9435 if (result == PACKET_OK)
9439 unpack_varlen_hex (rs->buf, &result);
9442 else if (result == PACKET_UNKNOWN)
9443 throw_error (TLS_GENERIC_ERROR,
9444 _("Remote target doesn't support qGetTLSAddr packet"));
9446 throw_error (TLS_GENERIC_ERROR,
9447 _("Remote target failed to process qGetTLSAddr request"));
9450 throw_error (TLS_GENERIC_ERROR,
9451 _("TLS not supported or disabled on this target"));
9456 /* Provide thread local base, i.e. Thread Information Block address.
9457 Returns 1 if ptid is found and thread_local_base is non zero. */
9460 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
9462 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
9464 struct remote_state *rs = get_remote_state ();
9466 char *endp = rs->buf + get_remote_packet_size ();
9467 enum packet_result result;
9469 strcpy (p, "qGetTIBAddr:");
9471 p = write_ptid (p, endp, ptid);
9475 getpkt (&rs->buf, &rs->buf_size, 0);
9476 result = packet_ok (rs->buf,
9477 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9478 if (result == PACKET_OK)
9482 unpack_varlen_hex (rs->buf, &result);
9484 *addr = (CORE_ADDR) result;
9487 else if (result == PACKET_UNKNOWN)
9488 error (_("Remote target doesn't support qGetTIBAddr packet"));
9490 error (_("Remote target failed to process qGetTIBAddr request"));
9493 error (_("qGetTIBAddr not supported or disabled on this target"));
9498 /* Support for inferring a target description based on the current
9499 architecture and the size of a 'g' packet. While the 'g' packet
9500 can have any size (since optional registers can be left off the
9501 end), some sizes are easily recognizable given knowledge of the
9502 approximate architecture. */
9504 struct remote_g_packet_guess
9507 const struct target_desc *tdesc;
9509 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9510 DEF_VEC_O(remote_g_packet_guess_s);
9512 struct remote_g_packet_data
9514 VEC(remote_g_packet_guess_s) *guesses;
9517 static struct gdbarch_data *remote_g_packet_data_handle;
9520 remote_g_packet_data_init (struct obstack *obstack)
9522 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9526 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9527 const struct target_desc *tdesc)
9529 struct remote_g_packet_data *data
9530 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9531 struct remote_g_packet_guess new_guess, *guess;
9534 gdb_assert (tdesc != NULL);
9537 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9539 if (guess->bytes == bytes)
9540 internal_error (__FILE__, __LINE__,
9541 _("Duplicate g packet description added for size %d"),
9544 new_guess.bytes = bytes;
9545 new_guess.tdesc = tdesc;
9546 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9549 /* Return 1 if remote_read_description would do anything on this target
9550 and architecture, 0 otherwise. */
9553 remote_read_description_p (struct target_ops *target)
9555 struct remote_g_packet_data *data
9556 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9558 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9564 static const struct target_desc *
9565 remote_read_description (struct target_ops *target)
9567 struct remote_g_packet_data *data
9568 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9570 /* Do not try this during initial connection, when we do not know
9571 whether there is a running but stopped thread. */
9572 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9573 return target->beneath->to_read_description (target->beneath);
9575 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9577 struct remote_g_packet_guess *guess;
9579 int bytes = send_g_packet ();
9582 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9584 if (guess->bytes == bytes)
9585 return guess->tdesc;
9587 /* We discard the g packet. A minor optimization would be to
9588 hold on to it, and fill the register cache once we have selected
9589 an architecture, but it's too tricky to do safely. */
9592 return target->beneath->to_read_description (target->beneath);
9595 /* Remote file transfer support. This is host-initiated I/O, not
9596 target-initiated; for target-initiated, see remote-fileio.c. */
9598 /* If *LEFT is at least the length of STRING, copy STRING to
9599 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9600 decrease *LEFT. Otherwise raise an error. */
9603 remote_buffer_add_string (char **buffer, int *left, char *string)
9605 int len = strlen (string);
9608 error (_("Packet too long for target."));
9610 memcpy (*buffer, string, len);
9614 /* NUL-terminate the buffer as a convenience, if there is
9620 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9621 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9622 decrease *LEFT. Otherwise raise an error. */
9625 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9628 if (2 * len > *left)
9629 error (_("Packet too long for target."));
9631 bin2hex (bytes, *buffer, len);
9635 /* NUL-terminate the buffer as a convenience, if there is
9641 /* If *LEFT is large enough, convert VALUE to hex and add it to
9642 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9643 decrease *LEFT. Otherwise raise an error. */
9646 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9648 int len = hexnumlen (value);
9651 error (_("Packet too long for target."));
9653 hexnumstr (*buffer, value);
9657 /* NUL-terminate the buffer as a convenience, if there is
9663 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9664 value, *REMOTE_ERRNO to the remote error number or zero if none
9665 was included, and *ATTACHMENT to point to the start of the annex
9666 if any. The length of the packet isn't needed here; there may
9667 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9669 Return 0 if the packet could be parsed, -1 if it could not. If
9670 -1 is returned, the other variables may not be initialized. */
9673 remote_hostio_parse_result (char *buffer, int *retcode,
9674 int *remote_errno, char **attachment)
9681 if (buffer[0] != 'F')
9685 *retcode = strtol (&buffer[1], &p, 16);
9686 if (errno != 0 || p == &buffer[1])
9689 /* Check for ",errno". */
9693 *remote_errno = strtol (p + 1, &p2, 16);
9694 if (errno != 0 || p + 1 == p2)
9699 /* Check for ";attachment". If there is no attachment, the
9700 packet should end here. */
9703 *attachment = p + 1;
9706 else if (*p == '\0')
9712 /* Send a prepared I/O packet to the target and read its response.
9713 The prepared packet is in the global RS->BUF before this function
9714 is called, and the answer is there when we return.
9716 COMMAND_BYTES is the length of the request to send, which may include
9717 binary data. WHICH_PACKET is the packet configuration to check
9718 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9719 is set to the error number and -1 is returned. Otherwise the value
9720 returned by the function is returned.
9722 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9723 attachment is expected; an error will be reported if there's a
9724 mismatch. If one is found, *ATTACHMENT will be set to point into
9725 the packet buffer and *ATTACHMENT_LEN will be set to the
9726 attachment's length. */
9729 remote_hostio_send_command (int command_bytes, int which_packet,
9730 int *remote_errno, char **attachment,
9731 int *attachment_len)
9733 struct remote_state *rs = get_remote_state ();
9734 int ret, bytes_read;
9735 char *attachment_tmp;
9737 if (!rs->remote_desc
9738 || packet_support (which_packet) == PACKET_DISABLE)
9740 *remote_errno = FILEIO_ENOSYS;
9744 putpkt_binary (rs->buf, command_bytes);
9745 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9747 /* If it timed out, something is wrong. Don't try to parse the
9751 *remote_errno = FILEIO_EINVAL;
9755 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9758 *remote_errno = FILEIO_EINVAL;
9760 case PACKET_UNKNOWN:
9761 *remote_errno = FILEIO_ENOSYS;
9767 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9770 *remote_errno = FILEIO_EINVAL;
9774 /* Make sure we saw an attachment if and only if we expected one. */
9775 if ((attachment_tmp == NULL && attachment != NULL)
9776 || (attachment_tmp != NULL && attachment == NULL))
9778 *remote_errno = FILEIO_EINVAL;
9782 /* If an attachment was found, it must point into the packet buffer;
9783 work out how many bytes there were. */
9784 if (attachment_tmp != NULL)
9786 *attachment = attachment_tmp;
9787 *attachment_len = bytes_read - (*attachment - rs->buf);
9793 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9794 remote file descriptor, or -1 if an error occurs (and set
9798 remote_hostio_open (struct target_ops *self,
9799 const char *filename, int flags, int mode,
9802 struct remote_state *rs = get_remote_state ();
9804 int left = get_remote_packet_size () - 1;
9806 remote_buffer_add_string (&p, &left, "vFile:open:");
9808 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9810 remote_buffer_add_string (&p, &left, ",");
9812 remote_buffer_add_int (&p, &left, flags);
9813 remote_buffer_add_string (&p, &left, ",");
9815 remote_buffer_add_int (&p, &left, mode);
9817 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9818 remote_errno, NULL, NULL);
9821 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9822 Return the number of bytes written, or -1 if an error occurs (and
9823 set *REMOTE_ERRNO). */
9826 remote_hostio_pwrite (struct target_ops *self,
9827 int fd, const gdb_byte *write_buf, int len,
9828 ULONGEST offset, int *remote_errno)
9830 struct remote_state *rs = get_remote_state ();
9832 int left = get_remote_packet_size ();
9835 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9837 remote_buffer_add_int (&p, &left, fd);
9838 remote_buffer_add_string (&p, &left, ",");
9840 remote_buffer_add_int (&p, &left, offset);
9841 remote_buffer_add_string (&p, &left, ",");
9843 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9844 get_remote_packet_size () - (p - rs->buf));
9846 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9847 remote_errno, NULL, NULL);
9850 /* Read up to LEN bytes FD on the remote target into READ_BUF
9851 Return the number of bytes read, or -1 if an error occurs (and
9852 set *REMOTE_ERRNO). */
9855 remote_hostio_pread (struct target_ops *self,
9856 int fd, gdb_byte *read_buf, int len,
9857 ULONGEST offset, int *remote_errno)
9859 struct remote_state *rs = get_remote_state ();
9862 int left = get_remote_packet_size ();
9863 int ret, attachment_len;
9866 remote_buffer_add_string (&p, &left, "vFile:pread:");
9868 remote_buffer_add_int (&p, &left, fd);
9869 remote_buffer_add_string (&p, &left, ",");
9871 remote_buffer_add_int (&p, &left, len);
9872 remote_buffer_add_string (&p, &left, ",");
9874 remote_buffer_add_int (&p, &left, offset);
9876 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9877 remote_errno, &attachment,
9883 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9885 if (read_len != ret)
9886 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9891 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9892 (and set *REMOTE_ERRNO). */
9895 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
9897 struct remote_state *rs = get_remote_state ();
9899 int left = get_remote_packet_size () - 1;
9901 remote_buffer_add_string (&p, &left, "vFile:close:");
9903 remote_buffer_add_int (&p, &left, fd);
9905 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9906 remote_errno, NULL, NULL);
9909 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9910 occurs (and set *REMOTE_ERRNO). */
9913 remote_hostio_unlink (struct target_ops *self,
9914 const char *filename, int *remote_errno)
9916 struct remote_state *rs = get_remote_state ();
9918 int left = get_remote_packet_size () - 1;
9920 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9922 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9925 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9926 remote_errno, NULL, NULL);
9929 /* Read value of symbolic link FILENAME on the remote target. Return
9930 a null-terminated string allocated via xmalloc, or NULL if an error
9931 occurs (and set *REMOTE_ERRNO). */
9934 remote_hostio_readlink (struct target_ops *self,
9935 const char *filename, int *remote_errno)
9937 struct remote_state *rs = get_remote_state ();
9940 int left = get_remote_packet_size ();
9941 int len, attachment_len;
9945 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9947 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9950 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9951 remote_errno, &attachment,
9957 ret = xmalloc (len + 1);
9959 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9960 (gdb_byte *) ret, len);
9961 if (read_len != len)
9962 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9969 remote_fileio_errno_to_host (int errnum)
9993 case FILEIO_ENOTDIR:
10001 case FILEIO_EMFILE:
10005 case FILEIO_ENOSPC:
10007 case FILEIO_ESPIPE:
10011 case FILEIO_ENOSYS:
10013 case FILEIO_ENAMETOOLONG:
10014 return ENAMETOOLONG;
10020 remote_hostio_error (int errnum)
10022 int host_error = remote_fileio_errno_to_host (errnum);
10024 if (host_error == -1)
10025 error (_("Unknown remote I/O error %d"), errnum);
10027 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10031 remote_hostio_close_cleanup (void *opaque)
10033 int fd = *(int *) opaque;
10036 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10041 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10043 const char *filename = bfd_get_filename (abfd);
10044 int fd, remote_errno;
10047 gdb_assert (remote_filename_p (filename));
10049 fd = remote_hostio_open (find_target_at (process_stratum),
10050 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10053 errno = remote_fileio_errno_to_host (remote_errno);
10054 bfd_set_error (bfd_error_system_call);
10058 stream = xmalloc (sizeof (int));
10064 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10066 int fd = *(int *)stream;
10071 /* Ignore errors on close; these may happen if the remote
10072 connection was already torn down. */
10073 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10075 /* Zero means success. */
10080 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10081 file_ptr nbytes, file_ptr offset)
10083 int fd = *(int *)stream;
10085 file_ptr pos, bytes;
10088 while (nbytes > pos)
10090 bytes = remote_hostio_pread (find_target_at (process_stratum),
10091 fd, (gdb_byte *) buf + pos, nbytes - pos,
10092 offset + pos, &remote_errno);
10094 /* Success, but no bytes, means end-of-file. */
10098 errno = remote_fileio_errno_to_host (remote_errno);
10099 bfd_set_error (bfd_error_system_call);
10110 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10112 /* FIXME: We should probably implement remote_hostio_stat. */
10113 sb->st_size = INT_MAX;
10118 remote_filename_p (const char *filename)
10120 return strncmp (filename,
10121 REMOTE_SYSROOT_PREFIX,
10122 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
10126 remote_bfd_open (const char *remote_file, const char *target)
10128 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10129 remote_bfd_iovec_open, NULL,
10130 remote_bfd_iovec_pread,
10131 remote_bfd_iovec_close,
10132 remote_bfd_iovec_stat);
10138 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10140 struct cleanup *back_to, *close_cleanup;
10141 int retcode, fd, remote_errno, bytes, io_size;
10144 int bytes_in_buffer;
10147 struct remote_state *rs = get_remote_state ();
10149 if (!rs->remote_desc)
10150 error (_("command can only be used with remote target"));
10152 file = gdb_fopen_cloexec (local_file, "rb");
10154 perror_with_name (local_file);
10155 back_to = make_cleanup_fclose (file);
10157 fd = remote_hostio_open (find_target_at (process_stratum),
10158 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10160 0700, &remote_errno);
10162 remote_hostio_error (remote_errno);
10164 /* Send up to this many bytes at once. They won't all fit in the
10165 remote packet limit, so we'll transfer slightly fewer. */
10166 io_size = get_remote_packet_size ();
10167 buffer = xmalloc (io_size);
10168 make_cleanup (xfree, buffer);
10170 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10172 bytes_in_buffer = 0;
10175 while (bytes_in_buffer || !saw_eof)
10179 bytes = fread (buffer + bytes_in_buffer, 1,
10180 io_size - bytes_in_buffer,
10185 error (_("Error reading %s."), local_file);
10188 /* EOF. Unless there is something still in the
10189 buffer from the last iteration, we are done. */
10191 if (bytes_in_buffer == 0)
10199 bytes += bytes_in_buffer;
10200 bytes_in_buffer = 0;
10202 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10204 offset, &remote_errno);
10207 remote_hostio_error (remote_errno);
10208 else if (retcode == 0)
10209 error (_("Remote write of %d bytes returned 0!"), bytes);
10210 else if (retcode < bytes)
10212 /* Short write. Save the rest of the read data for the next
10214 bytes_in_buffer = bytes - retcode;
10215 memmove (buffer, buffer + retcode, bytes_in_buffer);
10221 discard_cleanups (close_cleanup);
10222 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10223 remote_hostio_error (remote_errno);
10226 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10227 do_cleanups (back_to);
10231 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10233 struct cleanup *back_to, *close_cleanup;
10234 int fd, remote_errno, bytes, io_size;
10238 struct remote_state *rs = get_remote_state ();
10240 if (!rs->remote_desc)
10241 error (_("command can only be used with remote target"));
10243 fd = remote_hostio_open (find_target_at (process_stratum),
10244 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10246 remote_hostio_error (remote_errno);
10248 file = gdb_fopen_cloexec (local_file, "wb");
10250 perror_with_name (local_file);
10251 back_to = make_cleanup_fclose (file);
10253 /* Send up to this many bytes at once. They won't all fit in the
10254 remote packet limit, so we'll transfer slightly fewer. */
10255 io_size = get_remote_packet_size ();
10256 buffer = xmalloc (io_size);
10257 make_cleanup (xfree, buffer);
10259 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10264 bytes = remote_hostio_pread (find_target_at (process_stratum),
10265 fd, buffer, io_size, offset, &remote_errno);
10267 /* Success, but no bytes, means end-of-file. */
10270 remote_hostio_error (remote_errno);
10274 bytes = fwrite (buffer, 1, bytes, file);
10276 perror_with_name (local_file);
10279 discard_cleanups (close_cleanup);
10280 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10281 remote_hostio_error (remote_errno);
10284 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10285 do_cleanups (back_to);
10289 remote_file_delete (const char *remote_file, int from_tty)
10291 int retcode, remote_errno;
10292 struct remote_state *rs = get_remote_state ();
10294 if (!rs->remote_desc)
10295 error (_("command can only be used with remote target"));
10297 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10298 remote_file, &remote_errno);
10300 remote_hostio_error (remote_errno);
10303 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10307 remote_put_command (char *args, int from_tty)
10309 struct cleanup *back_to;
10313 error_no_arg (_("file to put"));
10315 argv = gdb_buildargv (args);
10316 back_to = make_cleanup_freeargv (argv);
10317 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10318 error (_("Invalid parameters to remote put"));
10320 remote_file_put (argv[0], argv[1], from_tty);
10322 do_cleanups (back_to);
10326 remote_get_command (char *args, int from_tty)
10328 struct cleanup *back_to;
10332 error_no_arg (_("file to get"));
10334 argv = gdb_buildargv (args);
10335 back_to = make_cleanup_freeargv (argv);
10336 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10337 error (_("Invalid parameters to remote get"));
10339 remote_file_get (argv[0], argv[1], from_tty);
10341 do_cleanups (back_to);
10345 remote_delete_command (char *args, int from_tty)
10347 struct cleanup *back_to;
10351 error_no_arg (_("file to delete"));
10353 argv = gdb_buildargv (args);
10354 back_to = make_cleanup_freeargv (argv);
10355 if (argv[0] == NULL || argv[1] != NULL)
10356 error (_("Invalid parameters to remote delete"));
10358 remote_file_delete (argv[0], from_tty);
10360 do_cleanups (back_to);
10364 remote_command (char *args, int from_tty)
10366 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
10370 remote_can_execute_reverse (struct target_ops *self)
10372 if (packet_support (PACKET_bs) == PACKET_ENABLE
10373 || packet_support (PACKET_bc) == PACKET_ENABLE)
10380 remote_supports_non_stop (struct target_ops *self)
10386 remote_supports_disable_randomization (struct target_ops *self)
10388 /* Only supported in extended mode. */
10393 remote_supports_multi_process (struct target_ops *self)
10395 struct remote_state *rs = get_remote_state ();
10397 /* Only extended-remote handles being attached to multiple
10398 processes, even though plain remote can use the multi-process
10399 thread id extensions, so that GDB knows the target process's
10401 return rs->extended && remote_multi_process_p (rs);
10405 remote_supports_cond_tracepoints (void)
10407 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
10411 remote_supports_cond_breakpoints (struct target_ops *self)
10413 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
10417 remote_supports_fast_tracepoints (void)
10419 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
10423 remote_supports_static_tracepoints (void)
10425 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
10429 remote_supports_install_in_trace (void)
10431 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
10435 remote_supports_enable_disable_tracepoint (struct target_ops *self)
10437 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10442 remote_supports_string_tracing (struct target_ops *self)
10444 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
10448 remote_can_run_breakpoint_commands (struct target_ops *self)
10450 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
10454 remote_trace_init (struct target_ops *self)
10457 remote_get_noisy_reply (&target_buf, &target_buf_size);
10458 if (strcmp (target_buf, "OK") != 0)
10459 error (_("Target does not support this command."));
10462 static void free_actions_list (char **actions_list);
10463 static void free_actions_list_cleanup_wrapper (void *);
10465 free_actions_list_cleanup_wrapper (void *al)
10467 free_actions_list (al);
10471 free_actions_list (char **actions_list)
10475 if (actions_list == 0)
10478 for (ndx = 0; actions_list[ndx]; ndx++)
10479 xfree (actions_list[ndx]);
10481 xfree (actions_list);
10484 /* Recursive routine to walk through command list including loops, and
10485 download packets for each command. */
10488 remote_download_command_source (int num, ULONGEST addr,
10489 struct command_line *cmds)
10491 struct remote_state *rs = get_remote_state ();
10492 struct command_line *cmd;
10494 for (cmd = cmds; cmd; cmd = cmd->next)
10496 QUIT; /* Allow user to bail out with ^C. */
10497 strcpy (rs->buf, "QTDPsrc:");
10498 encode_source_string (num, addr, "cmd", cmd->line,
10499 rs->buf + strlen (rs->buf),
10500 rs->buf_size - strlen (rs->buf));
10502 remote_get_noisy_reply (&target_buf, &target_buf_size);
10503 if (strcmp (target_buf, "OK"))
10504 warning (_("Target does not support source download."));
10506 if (cmd->control_type == while_control
10507 || cmd->control_type == while_stepping_control)
10509 remote_download_command_source (num, addr, *cmd->body_list);
10511 QUIT; /* Allow user to bail out with ^C. */
10512 strcpy (rs->buf, "QTDPsrc:");
10513 encode_source_string (num, addr, "cmd", "end",
10514 rs->buf + strlen (rs->buf),
10515 rs->buf_size - strlen (rs->buf));
10517 remote_get_noisy_reply (&target_buf, &target_buf_size);
10518 if (strcmp (target_buf, "OK"))
10519 warning (_("Target does not support source download."));
10525 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
10527 #define BUF_SIZE 2048
10531 char buf[BUF_SIZE];
10532 char **tdp_actions;
10533 char **stepping_actions;
10535 struct cleanup *old_chain = NULL;
10536 struct agent_expr *aexpr;
10537 struct cleanup *aexpr_chain = NULL;
10539 struct breakpoint *b = loc->owner;
10540 struct tracepoint *t = (struct tracepoint *) b;
10542 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10543 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10545 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10548 tpaddr = loc->address;
10549 sprintf_vma (addrbuf, tpaddr);
10550 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10551 addrbuf, /* address */
10552 (b->enable_state == bp_enabled ? 'E' : 'D'),
10553 t->step_count, t->pass_count);
10554 /* Fast tracepoints are mostly handled by the target, but we can
10555 tell the target how big of an instruction block should be moved
10557 if (b->type == bp_fast_tracepoint)
10559 /* Only test for support at download time; we may not know
10560 target capabilities at definition time. */
10561 if (remote_supports_fast_tracepoints ())
10565 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10566 tpaddr, &isize, NULL))
10567 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10570 /* If it passed validation at definition but fails now,
10571 something is very wrong. */
10572 internal_error (__FILE__, __LINE__,
10573 _("Fast tracepoint not "
10574 "valid during download"));
10577 /* Fast tracepoints are functionally identical to regular
10578 tracepoints, so don't take lack of support as a reason to
10579 give up on the trace run. */
10580 warning (_("Target does not support fast tracepoints, "
10581 "downloading %d as regular tracepoint"), b->number);
10583 else if (b->type == bp_static_tracepoint)
10585 /* Only test for support at download time; we may not know
10586 target capabilities at definition time. */
10587 if (remote_supports_static_tracepoints ())
10589 struct static_tracepoint_marker marker;
10591 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10592 strcat (buf, ":S");
10594 error (_("Static tracepoint not valid during download"));
10597 /* Fast tracepoints are functionally identical to regular
10598 tracepoints, so don't take lack of support as a reason
10599 to give up on the trace run. */
10600 error (_("Target does not support static tracepoints"));
10602 /* If the tracepoint has a conditional, make it into an agent
10603 expression and append to the definition. */
10606 /* Only test support at download time, we may not know target
10607 capabilities at definition time. */
10608 if (remote_supports_cond_tracepoints ())
10610 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10611 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10612 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10614 pkt = buf + strlen (buf);
10615 for (ndx = 0; ndx < aexpr->len; ++ndx)
10616 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10618 do_cleanups (aexpr_chain);
10621 warning (_("Target does not support conditional tracepoints, "
10622 "ignoring tp %d cond"), b->number);
10625 if (b->commands || *default_collect)
10628 remote_get_noisy_reply (&target_buf, &target_buf_size);
10629 if (strcmp (target_buf, "OK"))
10630 error (_("Target does not support tracepoints."));
10632 /* do_single_steps (t); */
10635 for (ndx = 0; tdp_actions[ndx]; ndx++)
10637 QUIT; /* Allow user to bail out with ^C. */
10638 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10639 b->number, addrbuf, /* address */
10641 ((tdp_actions[ndx + 1] || stepping_actions)
10644 remote_get_noisy_reply (&target_buf,
10646 if (strcmp (target_buf, "OK"))
10647 error (_("Error on target while setting tracepoints."));
10650 if (stepping_actions)
10652 for (ndx = 0; stepping_actions[ndx]; ndx++)
10654 QUIT; /* Allow user to bail out with ^C. */
10655 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10656 b->number, addrbuf, /* address */
10657 ((ndx == 0) ? "S" : ""),
10658 stepping_actions[ndx],
10659 (stepping_actions[ndx + 1] ? "-" : ""));
10661 remote_get_noisy_reply (&target_buf,
10663 if (strcmp (target_buf, "OK"))
10664 error (_("Error on target while setting tracepoints."));
10668 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
10670 if (b->addr_string)
10672 strcpy (buf, "QTDPsrc:");
10673 encode_source_string (b->number, loc->address,
10674 "at", b->addr_string, buf + strlen (buf),
10675 2048 - strlen (buf));
10678 remote_get_noisy_reply (&target_buf, &target_buf_size);
10679 if (strcmp (target_buf, "OK"))
10680 warning (_("Target does not support source download."));
10682 if (b->cond_string)
10684 strcpy (buf, "QTDPsrc:");
10685 encode_source_string (b->number, loc->address,
10686 "cond", b->cond_string, buf + strlen (buf),
10687 2048 - strlen (buf));
10689 remote_get_noisy_reply (&target_buf, &target_buf_size);
10690 if (strcmp (target_buf, "OK"))
10691 warning (_("Target does not support source download."));
10693 remote_download_command_source (b->number, loc->address,
10694 breakpoint_commands (b));
10697 do_cleanups (old_chain);
10701 remote_can_download_tracepoint (struct target_ops *self)
10703 struct remote_state *rs = get_remote_state ();
10704 struct trace_status *ts;
10707 /* Don't try to install tracepoints until we've relocated our
10708 symbols, and fetched and merged the target's tracepoint list with
10710 if (rs->starting_up)
10713 ts = current_trace_status ();
10714 status = remote_get_trace_status (self, ts);
10716 if (status == -1 || !ts->running_known || !ts->running)
10719 /* If we are in a tracing experiment, but remote stub doesn't support
10720 installing tracepoint in trace, we have to return. */
10721 if (!remote_supports_install_in_trace ())
10729 remote_download_trace_state_variable (struct target_ops *self,
10730 struct trace_state_variable *tsv)
10732 struct remote_state *rs = get_remote_state ();
10735 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10736 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10738 p = rs->buf + strlen (rs->buf);
10739 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10740 error (_("Trace state variable name too long for tsv definition packet"));
10741 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
10744 remote_get_noisy_reply (&target_buf, &target_buf_size);
10745 if (*target_buf == '\0')
10746 error (_("Target does not support this command."));
10747 if (strcmp (target_buf, "OK") != 0)
10748 error (_("Error on target while downloading trace state variable."));
10752 remote_enable_tracepoint (struct target_ops *self,
10753 struct bp_location *location)
10755 struct remote_state *rs = get_remote_state ();
10758 sprintf_vma (addr_buf, location->address);
10759 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10760 location->owner->number, addr_buf);
10762 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10763 if (*rs->buf == '\0')
10764 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10765 if (strcmp (rs->buf, "OK") != 0)
10766 error (_("Error on target while enabling tracepoint."));
10770 remote_disable_tracepoint (struct target_ops *self,
10771 struct bp_location *location)
10773 struct remote_state *rs = get_remote_state ();
10776 sprintf_vma (addr_buf, location->address);
10777 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10778 location->owner->number, addr_buf);
10780 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10781 if (*rs->buf == '\0')
10782 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10783 if (strcmp (rs->buf, "OK") != 0)
10784 error (_("Error on target while disabling tracepoint."));
10788 remote_trace_set_readonly_regions (struct target_ops *self)
10792 bfd_size_type size;
10798 return; /* No information to give. */
10800 strcpy (target_buf, "QTro");
10801 offset = strlen (target_buf);
10802 for (s = exec_bfd->sections; s; s = s->next)
10804 char tmp1[40], tmp2[40];
10807 if ((s->flags & SEC_LOAD) == 0 ||
10808 /* (s->flags & SEC_CODE) == 0 || */
10809 (s->flags & SEC_READONLY) == 0)
10813 vma = bfd_get_section_vma (abfd, s);
10814 size = bfd_get_section_size (s);
10815 sprintf_vma (tmp1, vma);
10816 sprintf_vma (tmp2, vma + size);
10817 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10818 if (offset + sec_length + 1 > target_buf_size)
10820 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
10822 Too many sections for read-only sections definition packet."));
10825 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10827 offset += sec_length;
10831 putpkt (target_buf);
10832 getpkt (&target_buf, &target_buf_size, 0);
10837 remote_trace_start (struct target_ops *self)
10839 putpkt ("QTStart");
10840 remote_get_noisy_reply (&target_buf, &target_buf_size);
10841 if (*target_buf == '\0')
10842 error (_("Target does not support this command."));
10843 if (strcmp (target_buf, "OK") != 0)
10844 error (_("Bogus reply from target: %s"), target_buf);
10848 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
10850 /* Initialize it just to avoid a GCC false warning. */
10852 /* FIXME we need to get register block size some other way. */
10853 extern int trace_regblock_size;
10854 volatile struct gdb_exception ex;
10855 enum packet_result result;
10857 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
10860 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10862 putpkt ("qTStatus");
10864 TRY_CATCH (ex, RETURN_MASK_ERROR)
10866 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10870 if (ex.error != TARGET_CLOSE_ERROR)
10872 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10875 throw_exception (ex);
10878 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10880 /* If the remote target doesn't do tracing, flag it. */
10881 if (result == PACKET_UNKNOWN)
10884 /* We're working with a live target. */
10885 ts->filename = NULL;
10888 error (_("Bogus trace status reply from target: %s"), target_buf);
10890 /* Function 'parse_trace_status' sets default value of each field of
10891 'ts' at first, so we don't have to do it here. */
10892 parse_trace_status (p, ts);
10894 return ts->running;
10898 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
10899 struct uploaded_tp *utp)
10901 struct remote_state *rs = get_remote_state ();
10903 struct bp_location *loc;
10904 struct tracepoint *tp = (struct tracepoint *) bp;
10905 size_t size = get_remote_packet_size ();
10909 tp->base.hit_count = 0;
10910 tp->traceframe_usage = 0;
10911 for (loc = tp->base.loc; loc; loc = loc->next)
10913 /* If the tracepoint was never downloaded, don't go asking for
10915 if (tp->number_on_target == 0)
10917 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10918 phex_nz (loc->address, 0));
10920 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10921 if (reply && *reply)
10924 parse_tracepoint_status (reply + 1, bp, utp);
10930 utp->hit_count = 0;
10931 utp->traceframe_usage = 0;
10932 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10933 phex_nz (utp->addr, 0));
10935 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10936 if (reply && *reply)
10939 parse_tracepoint_status (reply + 1, bp, utp);
10945 remote_trace_stop (struct target_ops *self)
10948 remote_get_noisy_reply (&target_buf, &target_buf_size);
10949 if (*target_buf == '\0')
10950 error (_("Target does not support this command."));
10951 if (strcmp (target_buf, "OK") != 0)
10952 error (_("Bogus reply from target: %s"), target_buf);
10956 remote_trace_find (struct target_ops *self,
10957 enum trace_find_type type, int num,
10958 CORE_ADDR addr1, CORE_ADDR addr2,
10961 struct remote_state *rs = get_remote_state ();
10962 char *endbuf = rs->buf + get_remote_packet_size ();
10964 int target_frameno = -1, target_tracept = -1;
10966 /* Lookups other than by absolute frame number depend on the current
10967 trace selected, so make sure it is correct on the remote end
10969 if (type != tfind_number)
10970 set_remote_traceframe ();
10973 strcpy (p, "QTFrame:");
10974 p = strchr (p, '\0');
10978 xsnprintf (p, endbuf - p, "%x", num);
10981 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
10984 xsnprintf (p, endbuf - p, "tdp:%x", num);
10987 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10988 phex_nz (addr2, 0));
10990 case tfind_outside:
10991 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10992 phex_nz (addr2, 0));
10995 error (_("Unknown trace find type %d"), type);
10999 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11000 if (*reply == '\0')
11001 error (_("Target does not support this command."));
11003 while (reply && *reply)
11008 target_frameno = (int) strtol (p, &reply, 16);
11010 error (_("Unable to parse trace frame number"));
11011 /* Don't update our remote traceframe number cache on failure
11012 to select a remote traceframe. */
11013 if (target_frameno == -1)
11018 target_tracept = (int) strtol (p, &reply, 16);
11020 error (_("Unable to parse tracepoint number"));
11022 case 'O': /* "OK"? */
11023 if (reply[1] == 'K' && reply[2] == '\0')
11026 error (_("Bogus reply from target: %s"), reply);
11029 error (_("Bogus reply from target: %s"), reply);
11032 *tpp = target_tracept;
11034 rs->remote_traceframe_number = target_frameno;
11035 return target_frameno;
11039 remote_get_trace_state_variable_value (struct target_ops *self,
11040 int tsvnum, LONGEST *val)
11042 struct remote_state *rs = get_remote_state ();
11046 set_remote_traceframe ();
11048 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11050 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11051 if (reply && *reply)
11055 unpack_varlen_hex (reply + 1, &uval);
11056 *val = (LONGEST) uval;
11064 remote_save_trace_data (struct target_ops *self, const char *filename)
11066 struct remote_state *rs = get_remote_state ();
11070 strcpy (p, "QTSave:");
11072 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11073 error (_("Remote file name too long for trace save packet"));
11074 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11077 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11078 if (*reply == '\0')
11079 error (_("Target does not support this command."));
11080 if (strcmp (reply, "OK") != 0)
11081 error (_("Bogus reply from target: %s"), reply);
11085 /* This is basically a memory transfer, but needs to be its own packet
11086 because we don't know how the target actually organizes its trace
11087 memory, plus we want to be able to ask for as much as possible, but
11088 not be unhappy if we don't get as much as we ask for. */
11091 remote_get_raw_trace_data (struct target_ops *self,
11092 gdb_byte *buf, ULONGEST offset, LONGEST len)
11094 struct remote_state *rs = get_remote_state ();
11100 strcpy (p, "qTBuffer:");
11102 p += hexnumstr (p, offset);
11104 p += hexnumstr (p, len);
11108 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11109 if (reply && *reply)
11111 /* 'l' by itself means we're at the end of the buffer and
11112 there is nothing more to get. */
11116 /* Convert the reply into binary. Limit the number of bytes to
11117 convert according to our passed-in buffer size, rather than
11118 what was returned in the packet; if the target is
11119 unexpectedly generous and gives us a bigger reply than we
11120 asked for, we don't want to crash. */
11121 rslt = hex2bin (target_buf, buf, len);
11125 /* Something went wrong, flag as an error. */
11130 remote_set_disconnected_tracing (struct target_ops *self, int val)
11132 struct remote_state *rs = get_remote_state ();
11134 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11138 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11140 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11141 if (*reply == '\0')
11142 error (_("Target does not support this command."));
11143 if (strcmp (reply, "OK") != 0)
11144 error (_("Bogus reply from target: %s"), reply);
11147 warning (_("Target does not support disconnected tracing."));
11151 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11153 struct thread_info *info = find_thread_ptid (ptid);
11155 if (info && info->private)
11156 return info->private->core;
11161 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11163 struct remote_state *rs = get_remote_state ();
11166 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11168 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11169 if (*reply == '\0')
11170 error (_("Target does not support this command."));
11171 if (strcmp (reply, "OK") != 0)
11172 error (_("Bogus reply from target: %s"), reply);
11175 static struct traceframe_info *
11176 remote_traceframe_info (struct target_ops *self)
11180 text = target_read_stralloc (¤t_target,
11181 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11184 struct traceframe_info *info;
11185 struct cleanup *back_to = make_cleanup (xfree, text);
11187 info = parse_traceframe_info (text);
11188 do_cleanups (back_to);
11195 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11196 instruction on which a fast tracepoint may be placed. Returns -1
11197 if the packet is not supported, and 0 if the minimum instruction
11198 length is unknown. */
11201 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11203 struct remote_state *rs = get_remote_state ();
11206 /* If we're not debugging a process yet, the IPA can't be
11208 if (!target_has_execution)
11211 /* Make sure the remote is pointing at the right process. */
11212 set_general_process ();
11214 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11216 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11217 if (*reply == '\0')
11221 ULONGEST min_insn_len;
11223 unpack_varlen_hex (reply, &min_insn_len);
11225 return (int) min_insn_len;
11230 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11232 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11234 struct remote_state *rs = get_remote_state ();
11235 char *buf = rs->buf;
11236 char *endbuf = rs->buf + get_remote_packet_size ();
11237 enum packet_result result;
11239 gdb_assert (val >= 0 || val == -1);
11240 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11241 /* Send -1 as literal "-1" to avoid host size dependency. */
11245 buf += hexnumstr (buf, (ULONGEST) -val);
11248 buf += hexnumstr (buf, (ULONGEST) val);
11251 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11252 result = packet_ok (rs->buf,
11253 &remote_protocol_packets[PACKET_QTBuffer_size]);
11255 if (result != PACKET_OK)
11256 warning (_("Bogus reply from target: %s"), rs->buf);
11261 remote_set_trace_notes (struct target_ops *self,
11262 const char *user, const char *notes,
11263 const char *stop_notes)
11265 struct remote_state *rs = get_remote_state ();
11267 char *buf = rs->buf;
11268 char *endbuf = rs->buf + get_remote_packet_size ();
11271 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11274 buf += xsnprintf (buf, endbuf - buf, "user:");
11275 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11281 buf += xsnprintf (buf, endbuf - buf, "notes:");
11282 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11288 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11289 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11293 /* Ensure the buffer is terminated. */
11297 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11298 if (*reply == '\0')
11301 if (strcmp (reply, "OK") != 0)
11302 error (_("Bogus reply from target: %s"), reply);
11308 remote_use_agent (struct target_ops *self, int use)
11310 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11312 struct remote_state *rs = get_remote_state ();
11314 /* If the stub supports QAgent. */
11315 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11317 getpkt (&rs->buf, &rs->buf_size, 0);
11319 if (strcmp (rs->buf, "OK") == 0)
11330 remote_can_use_agent (struct target_ops *self)
11332 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11335 struct btrace_target_info
11337 /* The ptid of the traced thread. */
11340 /* The obtained branch trace configuration. */
11341 struct btrace_config conf;
11344 /* Reset our idea of our target's btrace configuration. */
11347 remote_btrace_reset (void)
11349 struct remote_state *rs = get_remote_state ();
11351 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11354 /* Check whether the target supports branch tracing. */
11357 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
11359 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
11361 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
11366 case BTRACE_FORMAT_NONE:
11369 case BTRACE_FORMAT_BTS:
11370 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11373 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
11376 /* Synchronize the configuration with the target. */
11379 btrace_sync_conf (const struct btrace_config *conf)
11381 /* Nothing to do for now. */
11384 /* Read the current thread's btrace configuration from the target and
11385 store it into CONF. */
11388 btrace_read_config (struct btrace_config *conf)
11392 xml = target_read_stralloc (¤t_target,
11393 TARGET_OBJECT_BTRACE_CONF, "");
11396 struct cleanup *cleanup;
11398 cleanup = make_cleanup (xfree, xml);
11399 parse_xml_btrace_conf (conf, xml);
11400 do_cleanups (cleanup);
11404 /* Enable branch tracing. */
11406 static struct btrace_target_info *
11407 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11408 const struct btrace_config *conf)
11410 struct btrace_target_info *tinfo = NULL;
11411 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11412 struct remote_state *rs = get_remote_state ();
11413 char *buf = rs->buf;
11414 char *endbuf = rs->buf + get_remote_packet_size ();
11415 volatile struct gdb_exception err;
11417 if (packet_config_support (packet) != PACKET_ENABLE)
11418 error (_("Target does not support branch tracing."));
11420 btrace_sync_conf (conf);
11422 set_general_thread (ptid);
11424 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11426 getpkt (&rs->buf, &rs->buf_size, 0);
11428 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11430 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11431 error (_("Could not enable branch tracing for %s: %s"),
11432 target_pid_to_str (ptid), rs->buf + 2);
11434 error (_("Could not enable branch tracing for %s."),
11435 target_pid_to_str (ptid));
11438 tinfo = xzalloc (sizeof (*tinfo));
11439 tinfo->ptid = ptid;
11441 /* If we fail to read the configuration, we lose some information, but the
11442 tracing itself is not impacted. */
11443 TRY_CATCH (err, RETURN_MASK_ERROR)
11444 btrace_read_config (&tinfo->conf);
11446 if (err.message != NULL)
11447 warning ("%s", err.message);
11452 /* Disable branch tracing. */
11455 remote_disable_btrace (struct target_ops *self,
11456 struct btrace_target_info *tinfo)
11458 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11459 struct remote_state *rs = get_remote_state ();
11460 char *buf = rs->buf;
11461 char *endbuf = rs->buf + get_remote_packet_size ();
11463 if (packet_config_support (packet) != PACKET_ENABLE)
11464 error (_("Target does not support branch tracing."));
11466 set_general_thread (tinfo->ptid);
11468 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11470 getpkt (&rs->buf, &rs->buf_size, 0);
11472 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11474 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11475 error (_("Could not disable branch tracing for %s: %s"),
11476 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11478 error (_("Could not disable branch tracing for %s."),
11479 target_pid_to_str (tinfo->ptid));
11485 /* Teardown branch tracing. */
11488 remote_teardown_btrace (struct target_ops *self,
11489 struct btrace_target_info *tinfo)
11491 /* We must not talk to the target during teardown. */
11495 /* Read the branch trace. */
11497 static enum btrace_error
11498 remote_read_btrace (struct target_ops *self,
11499 struct btrace_data *btrace,
11500 struct btrace_target_info *tinfo,
11501 enum btrace_read_type type)
11503 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11504 struct remote_state *rs = get_remote_state ();
11505 struct cleanup *cleanup;
11509 if (packet_config_support (packet) != PACKET_ENABLE)
11510 error (_("Target does not support branch tracing."));
11512 #if !defined(HAVE_LIBEXPAT)
11513 error (_("Cannot process branch tracing result. XML parsing not supported."));
11518 case BTRACE_READ_ALL:
11521 case BTRACE_READ_NEW:
11524 case BTRACE_READ_DELTA:
11528 internal_error (__FILE__, __LINE__,
11529 _("Bad branch tracing read type: %u."),
11530 (unsigned int) type);
11533 xml = target_read_stralloc (¤t_target,
11534 TARGET_OBJECT_BTRACE, annex);
11536 return BTRACE_ERR_UNKNOWN;
11538 cleanup = make_cleanup (xfree, xml);
11539 parse_xml_btrace (btrace, xml);
11540 do_cleanups (cleanup);
11542 return BTRACE_ERR_NONE;
11545 static const struct btrace_config *
11546 remote_btrace_conf (struct target_ops *self,
11547 const struct btrace_target_info *tinfo)
11549 return &tinfo->conf;
11553 remote_augmented_libraries_svr4_read (struct target_ops *self)
11555 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11559 /* Implementation of to_load. */
11562 remote_load (struct target_ops *self, const char *name, int from_tty)
11564 generic_load (name, from_tty);
11568 init_remote_ops (void)
11570 remote_ops.to_shortname = "remote";
11571 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11572 remote_ops.to_doc =
11573 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11574 Specify the serial device it is connected to\n\
11575 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11576 remote_ops.to_open = remote_open;
11577 remote_ops.to_close = remote_close;
11578 remote_ops.to_detach = remote_detach;
11579 remote_ops.to_disconnect = remote_disconnect;
11580 remote_ops.to_resume = remote_resume;
11581 remote_ops.to_wait = remote_wait;
11582 remote_ops.to_fetch_registers = remote_fetch_registers;
11583 remote_ops.to_store_registers = remote_store_registers;
11584 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11585 remote_ops.to_files_info = remote_files_info;
11586 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11587 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11588 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11589 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11590 remote_ops.to_watchpoint_addr_within_range =
11591 remote_watchpoint_addr_within_range;
11592 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11593 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11594 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11595 remote_ops.to_region_ok_for_hw_watchpoint
11596 = remote_region_ok_for_hw_watchpoint;
11597 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11598 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11599 remote_ops.to_kill = remote_kill;
11600 remote_ops.to_load = remote_load;
11601 remote_ops.to_mourn_inferior = remote_mourn;
11602 remote_ops.to_pass_signals = remote_pass_signals;
11603 remote_ops.to_program_signals = remote_program_signals;
11604 remote_ops.to_thread_alive = remote_thread_alive;
11605 remote_ops.to_update_thread_list = remote_update_thread_list;
11606 remote_ops.to_pid_to_str = remote_pid_to_str;
11607 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11608 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11609 remote_ops.to_stop = remote_stop;
11610 remote_ops.to_xfer_partial = remote_xfer_partial;
11611 remote_ops.to_rcmd = remote_rcmd;
11612 remote_ops.to_log_command = serial_log_command;
11613 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11614 remote_ops.to_stratum = process_stratum;
11615 remote_ops.to_has_all_memory = default_child_has_all_memory;
11616 remote_ops.to_has_memory = default_child_has_memory;
11617 remote_ops.to_has_stack = default_child_has_stack;
11618 remote_ops.to_has_registers = default_child_has_registers;
11619 remote_ops.to_has_execution = default_child_has_execution;
11620 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11621 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11622 remote_ops.to_magic = OPS_MAGIC;
11623 remote_ops.to_memory_map = remote_memory_map;
11624 remote_ops.to_flash_erase = remote_flash_erase;
11625 remote_ops.to_flash_done = remote_flash_done;
11626 remote_ops.to_read_description = remote_read_description;
11627 remote_ops.to_search_memory = remote_search_memory;
11628 remote_ops.to_can_async_p = remote_can_async_p;
11629 remote_ops.to_is_async_p = remote_is_async_p;
11630 remote_ops.to_async = remote_async;
11631 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11632 remote_ops.to_terminal_ours = remote_terminal_ours;
11633 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11634 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11635 remote_ops.to_supports_disable_randomization
11636 = remote_supports_disable_randomization;
11637 remote_ops.to_fileio_open = remote_hostio_open;
11638 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11639 remote_ops.to_fileio_pread = remote_hostio_pread;
11640 remote_ops.to_fileio_close = remote_hostio_close;
11641 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11642 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11643 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11644 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11645 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11646 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11647 remote_ops.to_trace_init = remote_trace_init;
11648 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11649 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11650 remote_ops.to_download_trace_state_variable
11651 = remote_download_trace_state_variable;
11652 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11653 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11654 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11655 remote_ops.to_trace_start = remote_trace_start;
11656 remote_ops.to_get_trace_status = remote_get_trace_status;
11657 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11658 remote_ops.to_trace_stop = remote_trace_stop;
11659 remote_ops.to_trace_find = remote_trace_find;
11660 remote_ops.to_get_trace_state_variable_value
11661 = remote_get_trace_state_variable_value;
11662 remote_ops.to_save_trace_data = remote_save_trace_data;
11663 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11664 remote_ops.to_upload_trace_state_variables
11665 = remote_upload_trace_state_variables;
11666 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11667 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11668 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11669 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11670 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11671 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11672 remote_ops.to_core_of_thread = remote_core_of_thread;
11673 remote_ops.to_verify_memory = remote_verify_memory;
11674 remote_ops.to_get_tib_address = remote_get_tib_address;
11675 remote_ops.to_set_permissions = remote_set_permissions;
11676 remote_ops.to_static_tracepoint_marker_at
11677 = remote_static_tracepoint_marker_at;
11678 remote_ops.to_static_tracepoint_markers_by_strid
11679 = remote_static_tracepoint_markers_by_strid;
11680 remote_ops.to_traceframe_info = remote_traceframe_info;
11681 remote_ops.to_use_agent = remote_use_agent;
11682 remote_ops.to_can_use_agent = remote_can_use_agent;
11683 remote_ops.to_supports_btrace = remote_supports_btrace;
11684 remote_ops.to_enable_btrace = remote_enable_btrace;
11685 remote_ops.to_disable_btrace = remote_disable_btrace;
11686 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11687 remote_ops.to_read_btrace = remote_read_btrace;
11688 remote_ops.to_btrace_conf = remote_btrace_conf;
11689 remote_ops.to_augmented_libraries_svr4_read =
11690 remote_augmented_libraries_svr4_read;
11693 /* Set up the extended remote vector by making a copy of the standard
11694 remote vector and adding to it. */
11697 init_extended_remote_ops (void)
11699 extended_remote_ops = remote_ops;
11701 extended_remote_ops.to_shortname = "extended-remote";
11702 extended_remote_ops.to_longname =
11703 "Extended remote serial target in gdb-specific protocol";
11704 extended_remote_ops.to_doc =
11705 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11706 Specify the serial device it is connected to (e.g. /dev/ttya).";
11707 extended_remote_ops.to_open = extended_remote_open;
11708 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11709 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11710 extended_remote_ops.to_detach = extended_remote_detach;
11711 extended_remote_ops.to_attach = extended_remote_attach;
11712 extended_remote_ops.to_post_attach = extended_remote_post_attach;
11713 extended_remote_ops.to_kill = extended_remote_kill;
11714 extended_remote_ops.to_supports_disable_randomization
11715 = extended_remote_supports_disable_randomization;
11719 remote_can_async_p (struct target_ops *ops)
11721 struct remote_state *rs = get_remote_state ();
11723 if (!target_async_permitted)
11724 /* We only enable async when the user specifically asks for it. */
11727 /* We're async whenever the serial device is. */
11728 return serial_can_async_p (rs->remote_desc);
11732 remote_is_async_p (struct target_ops *ops)
11734 struct remote_state *rs = get_remote_state ();
11736 if (!target_async_permitted)
11737 /* We only enable async when the user specifically asks for it. */
11740 /* We're async whenever the serial device is. */
11741 return serial_is_async_p (rs->remote_desc);
11744 /* Pass the SERIAL event on and up to the client. One day this code
11745 will be able to delay notifying the client of an event until the
11746 point where an entire packet has been received. */
11748 static serial_event_ftype remote_async_serial_handler;
11751 remote_async_serial_handler (struct serial *scb, void *context)
11753 struct remote_state *rs = context;
11755 /* Don't propogate error information up to the client. Instead let
11756 the client find out about the error by querying the target. */
11757 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
11761 remote_async_inferior_event_handler (gdb_client_data data)
11763 inferior_event_handler (INF_REG_EVENT, NULL);
11767 remote_async (struct target_ops *ops,
11768 void (*callback) (enum inferior_event_type event_type,
11772 struct remote_state *rs = get_remote_state ();
11774 if (callback != NULL)
11776 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11777 rs->async_client_callback = callback;
11778 rs->async_client_context = context;
11780 /* If there are pending events in the stop reply queue tell the
11781 event loop to process them. */
11782 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11783 mark_async_event_handler (remote_async_inferior_event_token);
11787 serial_async (rs->remote_desc, NULL, NULL);
11788 clear_async_event_handler (remote_async_inferior_event_token);
11793 set_remote_cmd (char *args, int from_tty)
11795 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
11799 show_remote_cmd (char *args, int from_tty)
11801 /* We can't just use cmd_show_list here, because we want to skip
11802 the redundant "show remote Z-packet" and the legacy aliases. */
11803 struct cleanup *showlist_chain;
11804 struct cmd_list_element *list = remote_show_cmdlist;
11805 struct ui_out *uiout = current_uiout;
11807 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11808 for (; list != NULL; list = list->next)
11809 if (strcmp (list->name, "Z-packet") == 0)
11811 else if (list->type == not_set_cmd)
11812 /* Alias commands are exactly like the original, except they
11813 don't have the normal type. */
11817 struct cleanup *option_chain
11818 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11820 ui_out_field_string (uiout, "name", list->name);
11821 ui_out_text (uiout, ": ");
11822 if (list->type == show_cmd)
11823 do_show_command ((char *) NULL, from_tty, list);
11825 cmd_func (list, NULL, from_tty);
11826 /* Close the tuple. */
11827 do_cleanups (option_chain);
11830 /* Close the tuple. */
11831 do_cleanups (showlist_chain);
11835 /* Function to be called whenever a new objfile (shlib) is detected. */
11837 remote_new_objfile (struct objfile *objfile)
11839 struct remote_state *rs = get_remote_state ();
11841 if (rs->remote_desc != 0) /* Have a remote connection. */
11842 remote_check_symbols ();
11845 /* Pull all the tracepoints defined on the target and create local
11846 data structures representing them. We don't want to create real
11847 tracepoints yet, we don't want to mess up the user's existing
11851 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
11853 struct remote_state *rs = get_remote_state ();
11856 /* Ask for a first packet of tracepoint definition. */
11858 getpkt (&rs->buf, &rs->buf_size, 0);
11860 while (*p && *p != 'l')
11862 parse_tracepoint_definition (p, utpp);
11863 /* Ask for another packet of tracepoint definition. */
11865 getpkt (&rs->buf, &rs->buf_size, 0);
11872 remote_upload_trace_state_variables (struct target_ops *self,
11873 struct uploaded_tsv **utsvp)
11875 struct remote_state *rs = get_remote_state ();
11878 /* Ask for a first packet of variable definition. */
11880 getpkt (&rs->buf, &rs->buf_size, 0);
11882 while (*p && *p != 'l')
11884 parse_tsv_definition (p, utsvp);
11885 /* Ask for another packet of variable definition. */
11887 getpkt (&rs->buf, &rs->buf_size, 0);
11893 /* The "set/show range-stepping" show hook. */
11896 show_range_stepping (struct ui_file *file, int from_tty,
11897 struct cmd_list_element *c,
11900 fprintf_filtered (file,
11901 _("Debugger's willingness to use range stepping "
11902 "is %s.\n"), value);
11905 /* The "set/show range-stepping" set hook. */
11908 set_range_stepping (char *ignore_args, int from_tty,
11909 struct cmd_list_element *c)
11911 struct remote_state *rs = get_remote_state ();
11913 /* Whene enabling, check whether range stepping is actually
11914 supported by the target, and warn if not. */
11915 if (use_range_stepping)
11917 if (rs->remote_desc != NULL)
11919 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
11920 remote_vcont_probe (rs);
11922 if (packet_support (PACKET_vCont) == PACKET_ENABLE
11923 && rs->supports_vCont.r)
11927 warning (_("Range stepping is not supported by the current target"));
11932 _initialize_remote (void)
11934 struct remote_state *rs;
11935 struct cmd_list_element *cmd;
11936 const char *cmd_name;
11938 /* architecture specific data */
11939 remote_gdbarch_data_handle =
11940 gdbarch_data_register_post_init (init_remote_state);
11941 remote_g_packet_data_handle =
11942 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11944 /* Initialize the per-target state. At the moment there is only one
11945 of these, not one per target. Only one target is active at a
11947 remote_state = new_remote_state ();
11949 init_remote_ops ();
11950 add_target (&remote_ops);
11952 init_extended_remote_ops ();
11953 add_target (&extended_remote_ops);
11955 /* Hook into new objfile notification. */
11956 observer_attach_new_objfile (remote_new_objfile);
11957 /* We're no longer interested in notification events of an inferior
11959 observer_attach_inferior_exit (discard_pending_stop_replies);
11961 /* Set up signal handlers. */
11962 async_sigint_remote_token =
11963 create_async_signal_handler (async_remote_interrupt, NULL);
11964 async_sigint_remote_twice_token =
11965 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11968 init_remote_threadtests ();
11971 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11972 /* set/show remote ... */
11974 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11975 Remote protocol specific variables\n\
11976 Configure various remote-protocol specific variables such as\n\
11977 the packets being used"),
11978 &remote_set_cmdlist, "set remote ",
11979 0 /* allow-unknown */, &setlist);
11980 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11981 Remote protocol specific variables\n\
11982 Configure various remote-protocol specific variables such as\n\
11983 the packets being used"),
11984 &remote_show_cmdlist, "show remote ",
11985 0 /* allow-unknown */, &showlist);
11987 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11988 Compare section data on target to the exec file.\n\
11989 Argument is a single section name (default: all loaded sections).\n\
11990 To compare only read-only loaded sections, specify the -r option."),
11993 add_cmd ("packet", class_maintenance, packet_command, _("\
11994 Send an arbitrary packet to a remote target.\n\
11995 maintenance packet TEXT\n\
11996 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11997 this command sends the string TEXT to the inferior, and displays the\n\
11998 response packet. GDB supplies the initial `$' character, and the\n\
11999 terminating `#' character and checksum."),
12002 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12003 Set whether to send break if interrupted."), _("\
12004 Show whether to send break if interrupted."), _("\
12005 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12006 set_remotebreak, show_remotebreak,
12007 &setlist, &showlist);
12008 cmd_name = "remotebreak";
12009 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12010 deprecate_cmd (cmd, "set remote interrupt-sequence");
12011 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12012 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12013 deprecate_cmd (cmd, "show remote interrupt-sequence");
12015 add_setshow_enum_cmd ("interrupt-sequence", class_support,
12016 interrupt_sequence_modes, &interrupt_sequence_mode,
12018 Set interrupt sequence to remote target."), _("\
12019 Show interrupt sequence to remote target."), _("\
12020 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12021 NULL, show_interrupt_sequence,
12022 &remote_set_cmdlist,
12023 &remote_show_cmdlist);
12025 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12026 &interrupt_on_connect, _("\
12027 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12028 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12029 If set, interrupt sequence is sent to remote target."),
12031 &remote_set_cmdlist, &remote_show_cmdlist);
12033 /* Install commands for configuring memory read/write packets. */
12035 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12036 Set the maximum number of bytes per memory write packet (deprecated)."),
12038 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12039 Show the maximum number of bytes per memory write packet (deprecated)."),
12041 add_cmd ("memory-write-packet-size", no_class,
12042 set_memory_write_packet_size, _("\
12043 Set the maximum number of bytes per memory-write packet.\n\
12044 Specify the number of bytes in a packet or 0 (zero) for the\n\
12045 default packet size. The actual limit is further reduced\n\
12046 dependent on the target. Specify ``fixed'' to disable the\n\
12047 further restriction and ``limit'' to enable that restriction."),
12048 &remote_set_cmdlist);
12049 add_cmd ("memory-read-packet-size", no_class,
12050 set_memory_read_packet_size, _("\
12051 Set the maximum number of bytes per memory-read packet.\n\
12052 Specify the number of bytes in a packet or 0 (zero) for the\n\
12053 default packet size. The actual limit is further reduced\n\
12054 dependent on the target. Specify ``fixed'' to disable the\n\
12055 further restriction and ``limit'' to enable that restriction."),
12056 &remote_set_cmdlist);
12057 add_cmd ("memory-write-packet-size", no_class,
12058 show_memory_write_packet_size,
12059 _("Show the maximum number of bytes per memory-write packet."),
12060 &remote_show_cmdlist);
12061 add_cmd ("memory-read-packet-size", no_class,
12062 show_memory_read_packet_size,
12063 _("Show the maximum number of bytes per memory-read packet."),
12064 &remote_show_cmdlist);
12066 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12067 &remote_hw_watchpoint_limit, _("\
12068 Set the maximum number of target hardware watchpoints."), _("\
12069 Show the maximum number of target hardware watchpoints."), _("\
12070 Specify a negative limit for unlimited."),
12071 NULL, NULL, /* FIXME: i18n: The maximum
12072 number of target hardware
12073 watchpoints is %s. */
12074 &remote_set_cmdlist, &remote_show_cmdlist);
12075 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12076 &remote_hw_watchpoint_length_limit, _("\
12077 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12078 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12079 Specify a negative limit for unlimited."),
12080 NULL, NULL, /* FIXME: i18n: The maximum
12081 length (in bytes) of a target
12082 hardware watchpoint is %s. */
12083 &remote_set_cmdlist, &remote_show_cmdlist);
12084 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12085 &remote_hw_breakpoint_limit, _("\
12086 Set the maximum number of target hardware breakpoints."), _("\
12087 Show the maximum number of target hardware breakpoints."), _("\
12088 Specify a negative limit for unlimited."),
12089 NULL, NULL, /* FIXME: i18n: The maximum
12090 number of target hardware
12091 breakpoints is %s. */
12092 &remote_set_cmdlist, &remote_show_cmdlist);
12094 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12095 &remote_address_size, _("\
12096 Set the maximum size of the address (in bits) in a memory packet."), _("\
12097 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12099 NULL, /* FIXME: i18n: */
12100 &setlist, &showlist);
12102 init_all_packet_configs ();
12104 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12105 "X", "binary-download", 1);
12107 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12108 "vCont", "verbose-resume", 0);
12110 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12111 "QPassSignals", "pass-signals", 0);
12113 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12114 "QProgramSignals", "program-signals", 0);
12116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12117 "qSymbol", "symbol-lookup", 0);
12119 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12120 "P", "set-register", 1);
12122 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12123 "p", "fetch-register", 1);
12125 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12126 "Z0", "software-breakpoint", 0);
12128 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12129 "Z1", "hardware-breakpoint", 0);
12131 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12132 "Z2", "write-watchpoint", 0);
12134 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12135 "Z3", "read-watchpoint", 0);
12137 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12138 "Z4", "access-watchpoint", 0);
12140 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12141 "qXfer:auxv:read", "read-aux-vector", 0);
12143 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12144 "qXfer:features:read", "target-features", 0);
12146 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12147 "qXfer:libraries:read", "library-info", 0);
12149 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12150 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12152 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12153 "qXfer:memory-map:read", "memory-map", 0);
12155 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12156 "qXfer:spu:read", "read-spu-object", 0);
12158 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12159 "qXfer:spu:write", "write-spu-object", 0);
12161 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12162 "qXfer:osdata:read", "osdata", 0);
12164 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12165 "qXfer:threads:read", "threads", 0);
12167 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12168 "qXfer:siginfo:read", "read-siginfo-object", 0);
12170 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12171 "qXfer:siginfo:write", "write-siginfo-object", 0);
12173 add_packet_config_cmd
12174 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12175 "qXfer:traceframe-info:read", "traceframe-info", 0);
12177 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12178 "qXfer:uib:read", "unwind-info-block", 0);
12180 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12181 "qGetTLSAddr", "get-thread-local-storage-address",
12184 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12185 "qGetTIBAddr", "get-thread-information-block-address",
12188 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12189 "bc", "reverse-continue", 0);
12191 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12192 "bs", "reverse-step", 0);
12194 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12195 "qSupported", "supported-packets", 0);
12197 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12198 "qSearch:memory", "search-memory", 0);
12200 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12201 "qTStatus", "trace-status", 0);
12203 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12204 "vFile:open", "hostio-open", 0);
12206 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12207 "vFile:pread", "hostio-pread", 0);
12209 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12210 "vFile:pwrite", "hostio-pwrite", 0);
12212 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12213 "vFile:close", "hostio-close", 0);
12215 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12216 "vFile:unlink", "hostio-unlink", 0);
12218 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12219 "vFile:readlink", "hostio-readlink", 0);
12221 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12222 "vAttach", "attach", 0);
12224 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12227 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12228 "QStartNoAckMode", "noack", 0);
12230 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12231 "vKill", "kill", 0);
12233 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12234 "qAttached", "query-attached", 0);
12236 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12237 "ConditionalTracepoints",
12238 "conditional-tracepoints", 0);
12240 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12241 "ConditionalBreakpoints",
12242 "conditional-breakpoints", 0);
12244 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12245 "BreakpointCommands",
12246 "breakpoint-commands", 0);
12248 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12249 "FastTracepoints", "fast-tracepoints", 0);
12251 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12252 "TracepointSource", "TracepointSource", 0);
12254 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12255 "QAllow", "allow", 0);
12257 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12258 "StaticTracepoints", "static-tracepoints", 0);
12260 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12261 "InstallInTrace", "install-in-trace", 0);
12263 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12264 "qXfer:statictrace:read", "read-sdata-object", 0);
12266 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12267 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12269 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12270 "QDisableRandomization", "disable-randomization", 0);
12272 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12273 "QAgent", "agent", 0);
12275 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12276 "QTBuffer:size", "trace-buffer-size", 0);
12278 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12279 "Qbtrace:off", "disable-btrace", 0);
12281 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12282 "Qbtrace:bts", "enable-btrace", 0);
12284 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12285 "qXfer:btrace", "read-btrace", 0);
12287 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12288 "qXfer:btrace-conf", "read-btrace-conf", 0);
12290 /* Assert that we've registered commands for all packet configs. */
12294 for (i = 0; i < PACKET_MAX; i++)
12296 /* Ideally all configs would have a command associated. Some
12297 still don't though. */
12302 case PACKET_QNonStop:
12303 case PACKET_multiprocess_feature:
12304 case PACKET_EnableDisableTracepoints_feature:
12305 case PACKET_tracenz_feature:
12306 case PACKET_DisconnectedTracing_feature:
12307 case PACKET_augmented_libraries_svr4_read_feature:
12309 /* Additions to this list need to be well justified:
12310 pre-existing packets are OK; new packets are not. */
12318 /* This catches both forgetting to add a config command, and
12319 forgetting to remove a packet from the exception list. */
12320 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12324 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12325 Z sub-packet has its own set and show commands, but users may
12326 have sets to this variable in their .gdbinit files (or in their
12328 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12329 &remote_Z_packet_detect, _("\
12330 Set use of remote protocol `Z' packets"), _("\
12331 Show use of remote protocol `Z' packets "), _("\
12332 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12334 set_remote_protocol_Z_packet_cmd,
12335 show_remote_protocol_Z_packet_cmd,
12336 /* FIXME: i18n: Use of remote protocol
12337 `Z' packets is %s. */
12338 &remote_set_cmdlist, &remote_show_cmdlist);
12340 add_prefix_cmd ("remote", class_files, remote_command, _("\
12341 Manipulate files on the remote system\n\
12342 Transfer files to and from the remote target system."),
12343 &remote_cmdlist, "remote ",
12344 0 /* allow-unknown */, &cmdlist);
12346 add_cmd ("put", class_files, remote_put_command,
12347 _("Copy a local file to the remote system."),
12350 add_cmd ("get", class_files, remote_get_command,
12351 _("Copy a remote file to the local system."),
12354 add_cmd ("delete", class_files, remote_delete_command,
12355 _("Delete a remote file."),
12358 remote_exec_file = xstrdup ("");
12359 add_setshow_string_noescape_cmd ("exec-file", class_files,
12360 &remote_exec_file, _("\
12361 Set the remote pathname for \"run\""), _("\
12362 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12363 &remote_set_cmdlist, &remote_show_cmdlist);
12365 add_setshow_boolean_cmd ("range-stepping", class_run,
12366 &use_range_stepping, _("\
12367 Enable or disable range stepping."), _("\
12368 Show whether target-assisted range stepping is enabled."), _("\
12369 If on, and the target supports it, when stepping a source line, GDB\n\
12370 tells the target to step the corresponding range of addresses itself instead\n\
12371 of issuing multiple single-steps. This speeds up source level\n\
12372 stepping. If off, GDB always issues single-steps, even if range\n\
12373 stepping is supported by the target. The default is on."),
12374 set_range_stepping,
12375 show_range_stepping,
12379 /* Eventually initialize fileio. See fileio.c */
12380 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12382 /* Take advantage of the fact that the TID field is not used, to tag
12383 special ptids with it set to != 0. */
12384 magic_null_ptid = ptid_build (42000, -1, 1);
12385 not_sent_ptid = ptid_build (42000, -2, 1);
12386 any_thread_ptid = ptid_build (42000, 0, 1);
12388 target_buf_size = 2048;
12389 target_buf = xmalloc (target_buf_size);