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 "gdb_sys_time.h"
52 #include "event-loop.h"
53 #include "event-top.h"
59 #include "gdbcore.h" /* for exec_bfd */
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
74 /* Temp hacks for tracepoint encoding migration. */
75 static char *target_buf;
76 static long target_buf_size;
78 /* Per-program-space data key. */
79 static const struct program_space_data *remote_pspace_data;
81 /* The variable registered as the control variable used by the
82 remote exec-file commands. While the remote exec-file setting is
83 per-program-space, the set/show machinery uses this as the
84 location of the remote exec-file value. */
85 static char *remote_exec_file_var;
87 /* The size to align memory write packets, when practical. The protocol
88 does not guarantee any alignment, and gdb will generate short
89 writes and unaligned writes, but even as a best-effort attempt this
90 can improve bulk transfers. For instance, if a write is misaligned
91 relative to the target's data bus, the stub may need to make an extra
92 round trip fetching data from the target. This doesn't make a
93 huge difference, but it's easy to do, so we try to be helpful.
95 The alignment chosen is arbitrary; usually data bus width is
96 important here, not the possibly larger cache line size. */
97 enum { REMOTE_ALIGN_WRITES = 16 };
99 /* Prototypes for local functions. */
100 static void async_cleanup_sigint_signal_handler (void *dummy);
101 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
102 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
103 int forever, int *is_notif);
105 static void async_handle_remote_sigint (int);
106 static void async_handle_remote_sigint_twice (int);
108 static void remote_files_info (struct target_ops *ignore);
110 static void remote_prepare_to_store (struct target_ops *self,
111 struct regcache *regcache);
113 static void remote_open_1 (const char *, int, struct target_ops *,
116 static void remote_close (struct target_ops *self);
120 static int remote_vkill (int pid, struct remote_state *rs);
122 static void remote_mourn (struct target_ops *ops);
124 static void extended_remote_restart (void);
126 static void extended_remote_mourn (struct target_ops *);
128 static void remote_send (char **buf, long *sizeof_buf_p);
130 static int readchar (int timeout);
132 static void remote_serial_write (const char *str, int len);
134 static void remote_kill (struct target_ops *ops);
136 static int remote_can_async_p (struct target_ops *);
138 static int remote_is_async_p (struct target_ops *);
140 static void remote_async (struct target_ops *ops, int enable);
142 static void sync_remote_interrupt_twice (int signo);
144 static void interrupt_query (void);
146 static void set_general_thread (struct ptid ptid);
147 static void set_continue_thread (struct ptid ptid);
149 static void get_offsets (void);
151 static void skip_frame (void);
153 static long read_frame (char **buf_p, long *sizeof_buf);
155 static int hexnumlen (ULONGEST num);
157 static void init_remote_ops (void);
159 static void init_extended_remote_ops (void);
161 static void remote_stop (struct target_ops *self, ptid_t);
163 static int stubhex (int ch);
165 static int hexnumstr (char *, ULONGEST);
167 static int hexnumnstr (char *, ULONGEST, int);
169 static CORE_ADDR remote_address_masked (CORE_ADDR);
171 static void print_packet (const char *);
173 static void compare_sections_command (char *, int);
175 static void packet_command (char *, int);
177 static int stub_unpack_int (char *buff, int fieldlength);
179 static ptid_t remote_current_thread (ptid_t oldptid);
181 static int putpkt_binary (const char *buf, int cnt);
183 static void check_binary_download (CORE_ADDR addr);
185 struct packet_config;
187 static void show_packet_config_cmd (struct packet_config *config);
189 static void show_remote_protocol_packet_cmd (struct ui_file *file,
191 struct cmd_list_element *c,
194 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
195 static ptid_t read_ptid (char *buf, char **obuf);
197 static void remote_set_permissions (struct target_ops *self);
199 static int remote_get_trace_status (struct target_ops *self,
200 struct trace_status *ts);
202 static int remote_upload_tracepoints (struct target_ops *self,
203 struct uploaded_tp **utpp);
205 static int remote_upload_trace_state_variables (struct target_ops *self,
206 struct uploaded_tsv **utsvp);
208 static void remote_query_supported (void);
210 static void remote_check_symbols (void);
212 void _initialize_remote (void);
215 static void stop_reply_xfree (struct stop_reply *);
216 static void remote_parse_stop_reply (char *, struct stop_reply *);
217 static void push_stop_reply (struct stop_reply *);
218 static void discard_pending_stop_replies_in_queue (struct remote_state *);
219 static int peek_stop_reply (ptid_t ptid);
221 struct threads_listing_context;
222 static void remove_new_fork_children (struct threads_listing_context *);
224 static void remote_async_inferior_event_handler (gdb_client_data);
226 static void remote_terminal_ours (struct target_ops *self);
228 static int remote_read_description_p (struct target_ops *target);
230 static void remote_console_output (char *msg);
232 static int remote_supports_cond_breakpoints (struct target_ops *self);
234 static int remote_can_run_breakpoint_commands (struct target_ops *self);
236 static void remote_btrace_reset (void);
238 static int stop_reply_queue_length (void);
240 static void readahead_cache_invalidate (void);
244 static struct cmd_list_element *remote_cmdlist;
246 /* For "set remote" and "show remote". */
248 static struct cmd_list_element *remote_set_cmdlist;
249 static struct cmd_list_element *remote_show_cmdlist;
251 /* Stub vCont actions support.
253 Each field is a boolean flag indicating whether the stub reports
254 support for the corresponding action. */
256 struct vCont_action_support
265 /* Controls whether GDB is willing to use range stepping. */
267 static int use_range_stepping = 1;
269 #define OPAQUETHREADBYTES 8
271 /* a 64 bit opaque identifier */
272 typedef unsigned char threadref[OPAQUETHREADBYTES];
274 /* About this many threadisds fit in a packet. */
276 #define MAXTHREADLISTRESULTS 32
278 /* Data for the vFile:pread readahead cache. */
280 struct readahead_cache
282 /* The file descriptor for the file that is being cached. -1 if the
286 /* The offset into the file that the cache buffer corresponds
290 /* The buffer holding the cache contents. */
292 /* The buffer's size. We try to read as much as fits into a packet
296 /* Cache hit and miss counters. */
301 /* Description of the remote protocol state for the currently
302 connected target. This is per-target state, and independent of the
303 selected architecture. */
307 /* A buffer to use for incoming packets, and its current size. The
308 buffer is grown dynamically for larger incoming packets.
309 Outgoing packets may also be constructed in this buffer.
310 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
311 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
316 /* True if we're going through initial connection setup (finding out
317 about the remote side's threads, relocating symbols, etc.). */
320 /* If we negotiated packet size explicitly (and thus can bypass
321 heuristics for the largest packet size that will not overflow
322 a buffer in the stub), this will be set to that packet size.
323 Otherwise zero, meaning to use the guessed size. */
324 long explicit_packet_size;
326 /* remote_wait is normally called when the target is running and
327 waits for a stop reply packet. But sometimes we need to call it
328 when the target is already stopped. We can send a "?" packet
329 and have remote_wait read the response. Or, if we already have
330 the response, we can stash it in BUF and tell remote_wait to
331 skip calling getpkt. This flag is set when BUF contains a
332 stop reply packet and the target is not waiting. */
333 int cached_wait_status;
335 /* True, if in no ack mode. That is, neither GDB nor the stub will
336 expect acks from each other. The connection is assumed to be
340 /* True if we're connected in extended remote mode. */
343 /* True if we resumed the target and we're waiting for the target to
344 stop. In the mean time, we can't start another command/query.
345 The remote server wouldn't be ready to process it, so we'd
346 timeout waiting for a reply that would never come and eventually
347 we'd close the connection. This can happen in asynchronous mode
348 because we allow GDB commands while the target is running. */
349 int waiting_for_stop_reply;
351 /* The status of the stub support for the various vCont actions. */
352 struct vCont_action_support supports_vCont;
354 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
355 responded to that. */
358 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
359 remote_open knows that we don't have a file open when the program
361 struct serial *remote_desc;
363 /* These are the threads which we last sent to the remote system. The
364 TID member will be -1 for all or -2 for not sent yet. */
365 ptid_t general_thread;
366 ptid_t continue_thread;
368 /* This is the traceframe which we last selected on the remote system.
369 It will be -1 if no traceframe is selected. */
370 int remote_traceframe_number;
372 char *last_pass_packet;
374 /* The last QProgramSignals packet sent to the target. We bypass
375 sending a new program signals list down to the target if the new
376 packet is exactly the same as the last we sent. IOW, we only let
377 the target know about program signals list changes. */
378 char *last_program_signals_packet;
380 enum gdb_signal last_sent_signal;
384 char *finished_object;
385 char *finished_annex;
386 ULONGEST finished_offset;
388 /* Should we try the 'ThreadInfo' query packet?
390 This variable (NOT available to the user: auto-detect only!)
391 determines whether GDB will use the new, simpler "ThreadInfo"
392 query or the older, more complex syntax for thread queries.
393 This is an auto-detect variable (set to true at each connect,
394 and set to false when the target fails to recognize it). */
395 int use_threadinfo_query;
396 int use_threadextra_query;
398 /* This is set to the data address of the access causing the target
399 to stop for a watchpoint. */
400 CORE_ADDR remote_watch_data_address;
402 /* Whether the target stopped for a breakpoint/watchpoint. */
403 enum target_stop_reason stop_reason;
405 threadref echo_nextthread;
406 threadref nextthread;
407 threadref resultthreadlist[MAXTHREADLISTRESULTS];
409 /* The state of remote notification. */
410 struct remote_notif_state *notif_state;
412 /* The branch trace configuration. */
413 struct btrace_config btrace_config;
415 /* The argument to the last "vFile:setfs:" packet we sent, used
416 to avoid sending repeated unnecessary "vFile:setfs:" packets.
417 Initialized to -1 to indicate that no "vFile:setfs:" packet
418 has yet been sent. */
421 /* A readahead cache for vFile:pread. Often, reading a binary
422 involves a sequence of small reads. E.g., when parsing an ELF
423 file. A readahead cache helps mostly the case of remote
424 debugging on a connection with higher latency, due to the
425 request/reply nature of the RSP. We only cache data for a single
426 file descriptor at a time. */
427 struct readahead_cache readahead_cache;
430 /* Private data that we'll store in (struct thread_info)->private. */
431 struct private_thread_info
438 free_private_thread_info (struct private_thread_info *info)
444 /* This data could be associated with a target, but we do not always
445 have access to the current target when we need it, so for now it is
446 static. This will be fine for as long as only one target is in use
448 static struct remote_state *remote_state;
450 static struct remote_state *
451 get_remote_state_raw (void)
456 /* Allocate a new struct remote_state with xmalloc, initialize it, and
459 static struct remote_state *
460 new_remote_state (void)
462 struct remote_state *result = XCNEW (struct remote_state);
464 /* The default buffer size is unimportant; it will be expanded
465 whenever a larger buffer is needed. */
466 result->buf_size = 400;
467 result->buf = xmalloc (result->buf_size);
468 result->remote_traceframe_number = -1;
469 result->last_sent_signal = GDB_SIGNAL_0;
475 /* Description of the remote protocol for a given architecture. */
479 long offset; /* Offset into G packet. */
480 long regnum; /* GDB's internal register number. */
481 LONGEST pnum; /* Remote protocol register number. */
482 int in_g_packet; /* Always part of G packet. */
483 /* long size in bytes; == register_size (target_gdbarch (), regnum);
485 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
489 struct remote_arch_state
491 /* Description of the remote protocol registers. */
492 long sizeof_g_packet;
494 /* Description of the remote protocol registers indexed by REGNUM
495 (making an array gdbarch_num_regs in size). */
496 struct packet_reg *regs;
498 /* This is the size (in chars) of the first response to the ``g''
499 packet. It is used as a heuristic when determining the maximum
500 size of memory-read and memory-write packets. A target will
501 typically only reserve a buffer large enough to hold the ``g''
502 packet. The size does not include packet overhead (headers and
504 long actual_register_packet_size;
506 /* This is the maximum size (in chars) of a non read/write packet.
507 It is also used as a cap on the size of read/write packets. */
508 long remote_packet_size;
511 /* Utility: generate error from an incoming stub packet. */
513 trace_error (char *buf)
516 return; /* not an error msg */
519 case '1': /* malformed packet error */
520 if (*++buf == '0') /* general case: */
521 error (_("remote.c: error in outgoing packet."));
523 error (_("remote.c: error in outgoing packet at field #%ld."),
524 strtol (buf, NULL, 16));
526 error (_("Target returns error code '%s'."), buf);
530 /* Utility: wait for reply from stub, while accepting "O" packets. */
532 remote_get_noisy_reply (char **buf_p,
535 do /* Loop on reply from remote stub. */
539 QUIT; /* Allow user to bail out with ^C. */
540 getpkt (buf_p, sizeof_buf, 0);
544 else if (startswith (buf, "qRelocInsn:"))
547 CORE_ADDR from, to, org_to;
549 int adjusted_size = 0;
552 p = buf + strlen ("qRelocInsn:");
553 pp = unpack_varlen_hex (p, &ul);
555 error (_("invalid qRelocInsn packet: %s"), buf);
559 unpack_varlen_hex (p, &ul);
566 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
569 CATCH (ex, RETURN_MASK_ALL)
571 if (ex.error == MEMORY_ERROR)
573 /* Propagate memory errors silently back to the
574 target. The stub may have limited the range of
575 addresses we can write to, for example. */
579 /* Something unexpectedly bad happened. Be verbose
580 so we can tell what, and propagate the error back
581 to the stub, so it doesn't get stuck waiting for
583 exception_fprintf (gdb_stderr, ex,
584 _("warning: relocating instruction: "));
592 adjusted_size = to - org_to;
594 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
598 else if (buf[0] == 'O' && buf[1] != 'K')
599 remote_console_output (buf + 1); /* 'O' message from stub */
601 return buf; /* Here's the actual reply. */
606 /* Handle for retreving the remote protocol data from gdbarch. */
607 static struct gdbarch_data *remote_gdbarch_data_handle;
609 static struct remote_arch_state *
610 get_remote_arch_state (void)
612 gdb_assert (target_gdbarch () != NULL);
613 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
616 /* Fetch the global remote target state. */
618 static struct remote_state *
619 get_remote_state (void)
621 /* Make sure that the remote architecture state has been
622 initialized, because doing so might reallocate rs->buf. Any
623 function which calls getpkt also needs to be mindful of changes
624 to rs->buf, but this call limits the number of places which run
626 get_remote_arch_state ();
628 return get_remote_state_raw ();
631 /* Cleanup routine for the remote module's pspace data. */
634 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
636 char *remote_exec_file = arg;
638 xfree (remote_exec_file);
641 /* Fetch the remote exec-file from the current program space. */
644 get_remote_exec_file (void)
646 char *remote_exec_file;
648 remote_exec_file = program_space_data (current_program_space,
650 if (remote_exec_file == NULL)
653 return remote_exec_file;
656 /* Set the remote exec file for PSPACE. */
659 set_pspace_remote_exec_file (struct program_space *pspace,
660 char *remote_exec_file)
662 char *old_file = program_space_data (pspace, remote_pspace_data);
665 set_program_space_data (pspace, remote_pspace_data,
666 xstrdup (remote_exec_file));
669 /* The "set/show remote exec-file" set command hook. */
672 set_remote_exec_file (char *ignored, int from_tty,
673 struct cmd_list_element *c)
675 gdb_assert (remote_exec_file_var != NULL);
676 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
679 /* The "set/show remote exec-file" show command hook. */
682 show_remote_exec_file (struct ui_file *file, int from_tty,
683 struct cmd_list_element *cmd, const char *value)
685 fprintf_filtered (file, "%s\n", remote_exec_file_var);
689 compare_pnums (const void *lhs_, const void *rhs_)
691 const struct packet_reg * const *lhs = lhs_;
692 const struct packet_reg * const *rhs = rhs_;
694 if ((*lhs)->pnum < (*rhs)->pnum)
696 else if ((*lhs)->pnum == (*rhs)->pnum)
703 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
705 int regnum, num_remote_regs, offset;
706 struct packet_reg **remote_regs;
708 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
710 struct packet_reg *r = ®s[regnum];
712 if (register_size (gdbarch, regnum) == 0)
713 /* Do not try to fetch zero-sized (placeholder) registers. */
716 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
721 /* Define the g/G packet format as the contents of each register
722 with a remote protocol number, in order of ascending protocol
725 remote_regs = alloca (gdbarch_num_regs (gdbarch)
726 * sizeof (struct packet_reg *));
727 for (num_remote_regs = 0, regnum = 0;
728 regnum < gdbarch_num_regs (gdbarch);
730 if (regs[regnum].pnum != -1)
731 remote_regs[num_remote_regs++] = ®s[regnum];
733 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
736 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
738 remote_regs[regnum]->in_g_packet = 1;
739 remote_regs[regnum]->offset = offset;
740 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
746 /* Given the architecture described by GDBARCH, return the remote
747 protocol register's number and the register's offset in the g/G
748 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
749 If the target does not have a mapping for REGNUM, return false,
750 otherwise, return true. */
753 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
754 int *pnum, int *poffset)
757 struct packet_reg *regs;
758 struct cleanup *old_chain;
760 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
762 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
763 old_chain = make_cleanup (xfree, regs);
765 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
767 *pnum = regs[regnum].pnum;
768 *poffset = regs[regnum].offset;
770 do_cleanups (old_chain);
776 init_remote_state (struct gdbarch *gdbarch)
778 struct remote_state *rs = get_remote_state_raw ();
779 struct remote_arch_state *rsa;
781 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
783 /* Use the architecture to build a regnum<->pnum table, which will be
784 1:1 unless a feature set specifies otherwise. */
785 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
786 gdbarch_num_regs (gdbarch),
789 /* Record the maximum possible size of the g packet - it may turn out
791 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
793 /* Default maximum number of characters in a packet body. Many
794 remote stubs have a hardwired buffer size of 400 bytes
795 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
796 as the maximum packet-size to ensure that the packet and an extra
797 NUL character can always fit in the buffer. This stops GDB
798 trashing stubs that try to squeeze an extra NUL into what is
799 already a full buffer (As of 1999-12-04 that was most stubs). */
800 rsa->remote_packet_size = 400 - 1;
802 /* This one is filled in when a ``g'' packet is received. */
803 rsa->actual_register_packet_size = 0;
805 /* Should rsa->sizeof_g_packet needs more space than the
806 default, adjust the size accordingly. Remember that each byte is
807 encoded as two characters. 32 is the overhead for the packet
808 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
809 (``$NN:G...#NN'') is a better guess, the below has been padded a
811 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
812 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
814 /* Make sure that the packet buffer is plenty big enough for
815 this architecture. */
816 if (rs->buf_size < rsa->remote_packet_size)
818 rs->buf_size = 2 * rsa->remote_packet_size;
819 rs->buf = xrealloc (rs->buf, rs->buf_size);
825 /* Return the current allowed size of a remote packet. This is
826 inferred from the current architecture, and should be used to
827 limit the length of outgoing packets. */
829 get_remote_packet_size (void)
831 struct remote_state *rs = get_remote_state ();
832 struct remote_arch_state *rsa = get_remote_arch_state ();
834 if (rs->explicit_packet_size)
835 return rs->explicit_packet_size;
837 return rsa->remote_packet_size;
840 static struct packet_reg *
841 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
843 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
847 struct packet_reg *r = &rsa->regs[regnum];
849 gdb_assert (r->regnum == regnum);
854 static struct packet_reg *
855 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
859 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
861 struct packet_reg *r = &rsa->regs[i];
869 static struct target_ops remote_ops;
871 static struct target_ops extended_remote_ops;
873 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
874 ``forever'' still use the normal timeout mechanism. This is
875 currently used by the ASYNC code to guarentee that target reads
876 during the initial connect always time-out. Once getpkt has been
877 modified to return a timeout indication and, in turn
878 remote_wait()/wait_for_inferior() have gained a timeout parameter
880 static int wait_forever_enabled_p = 1;
882 /* Allow the user to specify what sequence to send to the remote
883 when he requests a program interruption: Although ^C is usually
884 what remote systems expect (this is the default, here), it is
885 sometimes preferable to send a break. On other systems such
886 as the Linux kernel, a break followed by g, which is Magic SysRq g
887 is required in order to interrupt the execution. */
888 const char interrupt_sequence_control_c[] = "Ctrl-C";
889 const char interrupt_sequence_break[] = "BREAK";
890 const char interrupt_sequence_break_g[] = "BREAK-g";
891 static const char *const interrupt_sequence_modes[] =
893 interrupt_sequence_control_c,
894 interrupt_sequence_break,
895 interrupt_sequence_break_g,
898 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
901 show_interrupt_sequence (struct ui_file *file, int from_tty,
902 struct cmd_list_element *c,
905 if (interrupt_sequence_mode == interrupt_sequence_control_c)
906 fprintf_filtered (file,
907 _("Send the ASCII ETX character (Ctrl-c) "
908 "to the remote target to interrupt the "
909 "execution of the program.\n"));
910 else if (interrupt_sequence_mode == interrupt_sequence_break)
911 fprintf_filtered (file,
912 _("send a break signal to the remote target "
913 "to interrupt the execution of the program.\n"));
914 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
915 fprintf_filtered (file,
916 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
917 "the remote target to interrupt the execution "
918 "of Linux kernel.\n"));
920 internal_error (__FILE__, __LINE__,
921 _("Invalid value for interrupt_sequence_mode: %s."),
922 interrupt_sequence_mode);
925 /* This boolean variable specifies whether interrupt_sequence is sent
926 to the remote target when gdb connects to it.
927 This is mostly needed when you debug the Linux kernel: The Linux kernel
928 expects BREAK g which is Magic SysRq g for connecting gdb. */
929 static int interrupt_on_connect = 0;
931 /* This variable is used to implement the "set/show remotebreak" commands.
932 Since these commands are now deprecated in favor of "set/show remote
933 interrupt-sequence", it no longer has any effect on the code. */
934 static int remote_break;
937 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
940 interrupt_sequence_mode = interrupt_sequence_break;
942 interrupt_sequence_mode = interrupt_sequence_control_c;
946 show_remotebreak (struct ui_file *file, int from_tty,
947 struct cmd_list_element *c,
952 /* This variable sets the number of bits in an address that are to be
953 sent in a memory ("M" or "m") packet. Normally, after stripping
954 leading zeros, the entire address would be sent. This variable
955 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
956 initial implementation of remote.c restricted the address sent in
957 memory packets to ``host::sizeof long'' bytes - (typically 32
958 bits). Consequently, for 64 bit targets, the upper 32 bits of an
959 address was never sent. Since fixing this bug may cause a break in
960 some remote targets this variable is principly provided to
961 facilitate backward compatibility. */
963 static unsigned int remote_address_size;
965 /* Temporary to track who currently owns the terminal. See
966 remote_terminal_* for more details. */
968 static int remote_async_terminal_ours_p;
971 /* User configurable variables for the number of characters in a
972 memory read/write packet. MIN (rsa->remote_packet_size,
973 rsa->sizeof_g_packet) is the default. Some targets need smaller
974 values (fifo overruns, et.al.) and some users need larger values
975 (speed up transfers). The variables ``preferred_*'' (the user
976 request), ``current_*'' (what was actually set) and ``forced_*''
977 (Positive - a soft limit, negative - a hard limit). */
979 struct memory_packet_config
986 /* The default max memory-write-packet-size. The 16k is historical.
987 (It came from older GDB's using alloca for buffers and the
988 knowledge (folklore?) that some hosts don't cope very well with
989 large alloca calls.) */
990 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
992 /* The minimum remote packet size for memory transfers. Ensures we
993 can write at least one byte. */
994 #define MIN_MEMORY_PACKET_SIZE 20
996 /* Compute the current size of a read/write packet. Since this makes
997 use of ``actual_register_packet_size'' the computation is dynamic. */
1000 get_memory_packet_size (struct memory_packet_config *config)
1002 struct remote_state *rs = get_remote_state ();
1003 struct remote_arch_state *rsa = get_remote_arch_state ();
1006 if (config->fixed_p)
1008 if (config->size <= 0)
1009 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1011 what_they_get = config->size;
1015 what_they_get = get_remote_packet_size ();
1016 /* Limit the packet to the size specified by the user. */
1017 if (config->size > 0
1018 && what_they_get > config->size)
1019 what_they_get = config->size;
1021 /* Limit it to the size of the targets ``g'' response unless we have
1022 permission from the stub to use a larger packet size. */
1023 if (rs->explicit_packet_size == 0
1024 && rsa->actual_register_packet_size > 0
1025 && what_they_get > rsa->actual_register_packet_size)
1026 what_they_get = rsa->actual_register_packet_size;
1028 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1029 what_they_get = MIN_MEMORY_PACKET_SIZE;
1031 /* Make sure there is room in the global buffer for this packet
1032 (including its trailing NUL byte). */
1033 if (rs->buf_size < what_they_get + 1)
1035 rs->buf_size = 2 * what_they_get;
1036 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
1039 return what_they_get;
1042 /* Update the size of a read/write packet. If they user wants
1043 something really big then do a sanity check. */
1046 set_memory_packet_size (char *args, struct memory_packet_config *config)
1048 int fixed_p = config->fixed_p;
1049 long size = config->size;
1052 error (_("Argument required (integer, `fixed' or `limited')."));
1053 else if (strcmp (args, "hard") == 0
1054 || strcmp (args, "fixed") == 0)
1056 else if (strcmp (args, "soft") == 0
1057 || strcmp (args, "limit") == 0)
1063 size = strtoul (args, &end, 0);
1065 error (_("Invalid %s (bad syntax)."), config->name);
1067 /* Instead of explicitly capping the size of a packet to or
1068 disallowing it, the user is allowed to set the size to
1069 something arbitrarily large. */
1072 /* So that the query shows the correct value. */
1074 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1077 if (fixed_p && !config->fixed_p)
1079 if (! query (_("The target may not be able to correctly handle a %s\n"
1080 "of %ld bytes. Change the packet size? "),
1081 config->name, size))
1082 error (_("Packet size not changed."));
1084 /* Update the config. */
1085 config->fixed_p = fixed_p;
1086 config->size = size;
1090 show_memory_packet_size (struct memory_packet_config *config)
1092 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1093 if (config->fixed_p)
1094 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1095 get_memory_packet_size (config));
1097 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1098 get_memory_packet_size (config));
1101 static struct memory_packet_config memory_write_packet_config =
1103 "memory-write-packet-size",
1107 set_memory_write_packet_size (char *args, int from_tty)
1109 set_memory_packet_size (args, &memory_write_packet_config);
1113 show_memory_write_packet_size (char *args, int from_tty)
1115 show_memory_packet_size (&memory_write_packet_config);
1119 get_memory_write_packet_size (void)
1121 return get_memory_packet_size (&memory_write_packet_config);
1124 static struct memory_packet_config memory_read_packet_config =
1126 "memory-read-packet-size",
1130 set_memory_read_packet_size (char *args, int from_tty)
1132 set_memory_packet_size (args, &memory_read_packet_config);
1136 show_memory_read_packet_size (char *args, int from_tty)
1138 show_memory_packet_size (&memory_read_packet_config);
1142 get_memory_read_packet_size (void)
1144 long size = get_memory_packet_size (&memory_read_packet_config);
1146 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1147 extra buffer size argument before the memory read size can be
1148 increased beyond this. */
1149 if (size > get_remote_packet_size ())
1150 size = get_remote_packet_size ();
1155 /* Generic configuration support for packets the stub optionally
1156 supports. Allows the user to specify the use of the packet as well
1157 as allowing GDB to auto-detect support in the remote stub. */
1161 PACKET_SUPPORT_UNKNOWN = 0,
1166 struct packet_config
1171 /* If auto, GDB auto-detects support for this packet or feature,
1172 either through qSupported, or by trying the packet and looking
1173 at the response. If true, GDB assumes the target supports this
1174 packet. If false, the packet is disabled. Configs that don't
1175 have an associated command always have this set to auto. */
1176 enum auto_boolean detect;
1178 /* Does the target support this packet? */
1179 enum packet_support support;
1182 /* Analyze a packet's return value and update the packet config
1192 static enum packet_support packet_config_support (struct packet_config *config);
1193 static enum packet_support packet_support (int packet);
1196 show_packet_config_cmd (struct packet_config *config)
1198 char *support = "internal-error";
1200 switch (packet_config_support (config))
1203 support = "enabled";
1205 case PACKET_DISABLE:
1206 support = "disabled";
1208 case PACKET_SUPPORT_UNKNOWN:
1209 support = "unknown";
1212 switch (config->detect)
1214 case AUTO_BOOLEAN_AUTO:
1215 printf_filtered (_("Support for the `%s' packet "
1216 "is auto-detected, currently %s.\n"),
1217 config->name, support);
1219 case AUTO_BOOLEAN_TRUE:
1220 case AUTO_BOOLEAN_FALSE:
1221 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1222 config->name, support);
1228 add_packet_config_cmd (struct packet_config *config, const char *name,
1229 const char *title, int legacy)
1235 config->name = name;
1236 config->title = title;
1237 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1239 show_doc = xstrprintf ("Show current use of remote "
1240 "protocol `%s' (%s) packet",
1242 /* set/show TITLE-packet {auto,on,off} */
1243 cmd_name = xstrprintf ("%s-packet", title);
1244 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1245 &config->detect, set_doc,
1246 show_doc, NULL, /* help_doc */
1248 show_remote_protocol_packet_cmd,
1249 &remote_set_cmdlist, &remote_show_cmdlist);
1250 /* The command code copies the documentation strings. */
1253 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1258 legacy_name = xstrprintf ("%s-packet", name);
1259 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1260 &remote_set_cmdlist);
1261 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1262 &remote_show_cmdlist);
1266 static enum packet_result
1267 packet_check_result (const char *buf)
1271 /* The stub recognized the packet request. Check that the
1272 operation succeeded. */
1274 && isxdigit (buf[1]) && isxdigit (buf[2])
1276 /* "Enn" - definitly an error. */
1277 return PACKET_ERROR;
1279 /* Always treat "E." as an error. This will be used for
1280 more verbose error messages, such as E.memtypes. */
1281 if (buf[0] == 'E' && buf[1] == '.')
1282 return PACKET_ERROR;
1284 /* The packet may or may not be OK. Just assume it is. */
1288 /* The stub does not support the packet. */
1289 return PACKET_UNKNOWN;
1292 static enum packet_result
1293 packet_ok (const char *buf, struct packet_config *config)
1295 enum packet_result result;
1297 if (config->detect != AUTO_BOOLEAN_TRUE
1298 && config->support == PACKET_DISABLE)
1299 internal_error (__FILE__, __LINE__,
1300 _("packet_ok: attempt to use a disabled packet"));
1302 result = packet_check_result (buf);
1307 /* The stub recognized the packet request. */
1308 if (config->support == PACKET_SUPPORT_UNKNOWN)
1311 fprintf_unfiltered (gdb_stdlog,
1312 "Packet %s (%s) is supported\n",
1313 config->name, config->title);
1314 config->support = PACKET_ENABLE;
1317 case PACKET_UNKNOWN:
1318 /* The stub does not support the packet. */
1319 if (config->detect == AUTO_BOOLEAN_AUTO
1320 && config->support == PACKET_ENABLE)
1322 /* If the stub previously indicated that the packet was
1323 supported then there is a protocol error. */
1324 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1325 config->name, config->title);
1327 else if (config->detect == AUTO_BOOLEAN_TRUE)
1329 /* The user set it wrong. */
1330 error (_("Enabled packet %s (%s) not recognized by stub"),
1331 config->name, config->title);
1335 fprintf_unfiltered (gdb_stdlog,
1336 "Packet %s (%s) is NOT supported\n",
1337 config->name, config->title);
1338 config->support = PACKET_DISABLE;
1359 PACKET_vFile_pwrite,
1361 PACKET_vFile_unlink,
1362 PACKET_vFile_readlink,
1365 PACKET_qXfer_features,
1366 PACKET_qXfer_exec_file,
1367 PACKET_qXfer_libraries,
1368 PACKET_qXfer_libraries_svr4,
1369 PACKET_qXfer_memory_map,
1370 PACKET_qXfer_spu_read,
1371 PACKET_qXfer_spu_write,
1372 PACKET_qXfer_osdata,
1373 PACKET_qXfer_threads,
1374 PACKET_qXfer_statictrace_read,
1375 PACKET_qXfer_traceframe_info,
1381 PACKET_QPassSignals,
1382 PACKET_QProgramSignals,
1384 PACKET_qSearch_memory,
1387 PACKET_QStartNoAckMode,
1389 PACKET_qXfer_siginfo_read,
1390 PACKET_qXfer_siginfo_write,
1393 /* Support for conditional tracepoints. */
1394 PACKET_ConditionalTracepoints,
1396 /* Support for target-side breakpoint conditions. */
1397 PACKET_ConditionalBreakpoints,
1399 /* Support for target-side breakpoint commands. */
1400 PACKET_BreakpointCommands,
1402 /* Support for fast tracepoints. */
1403 PACKET_FastTracepoints,
1405 /* Support for static tracepoints. */
1406 PACKET_StaticTracepoints,
1408 /* Support for installing tracepoints while a trace experiment is
1410 PACKET_InstallInTrace,
1414 PACKET_TracepointSource,
1417 PACKET_QDisableRandomization,
1419 PACKET_QTBuffer_size,
1423 PACKET_qXfer_btrace,
1425 /* Support for the QNonStop packet. */
1428 /* Support for multi-process extensions. */
1429 PACKET_multiprocess_feature,
1431 /* Support for enabling and disabling tracepoints while a trace
1432 experiment is running. */
1433 PACKET_EnableDisableTracepoints_feature,
1435 /* Support for collecting strings using the tracenz bytecode. */
1436 PACKET_tracenz_feature,
1438 /* Support for continuing to run a trace experiment while GDB is
1440 PACKET_DisconnectedTracing_feature,
1442 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1443 PACKET_augmented_libraries_svr4_read_feature,
1445 /* Support for the qXfer:btrace-conf:read packet. */
1446 PACKET_qXfer_btrace_conf,
1448 /* Support for the Qbtrace-conf:bts:size packet. */
1449 PACKET_Qbtrace_conf_bts_size,
1451 /* Support for swbreak+ feature. */
1452 PACKET_swbreak_feature,
1454 /* Support for hwbreak+ feature. */
1455 PACKET_hwbreak_feature,
1457 /* Support for fork events. */
1458 PACKET_fork_event_feature,
1460 /* Support for vfork events. */
1461 PACKET_vfork_event_feature,
1463 /* Support for the Qbtrace-conf:pt:size packet. */
1464 PACKET_Qbtrace_conf_pt_size,
1466 /* Support for exec events. */
1467 PACKET_exec_event_feature,
1472 static struct packet_config remote_protocol_packets[PACKET_MAX];
1474 /* Returns the packet's corresponding "set remote foo-packet" command
1475 state. See struct packet_config for more details. */
1477 static enum auto_boolean
1478 packet_set_cmd_state (int packet)
1480 return remote_protocol_packets[packet].detect;
1483 /* Returns whether a given packet or feature is supported. This takes
1484 into account the state of the corresponding "set remote foo-packet"
1485 command, which may be used to bypass auto-detection. */
1487 static enum packet_support
1488 packet_config_support (struct packet_config *config)
1490 switch (config->detect)
1492 case AUTO_BOOLEAN_TRUE:
1493 return PACKET_ENABLE;
1494 case AUTO_BOOLEAN_FALSE:
1495 return PACKET_DISABLE;
1496 case AUTO_BOOLEAN_AUTO:
1497 return config->support;
1499 gdb_assert_not_reached (_("bad switch"));
1503 /* Same as packet_config_support, but takes the packet's enum value as
1506 static enum packet_support
1507 packet_support (int packet)
1509 struct packet_config *config = &remote_protocol_packets[packet];
1511 return packet_config_support (config);
1515 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1516 struct cmd_list_element *c,
1519 struct packet_config *packet;
1521 for (packet = remote_protocol_packets;
1522 packet < &remote_protocol_packets[PACKET_MAX];
1525 if (&packet->detect == c->var)
1527 show_packet_config_cmd (packet);
1531 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1535 /* Should we try one of the 'Z' requests? */
1539 Z_PACKET_SOFTWARE_BP,
1540 Z_PACKET_HARDWARE_BP,
1547 /* For compatibility with older distributions. Provide a ``set remote
1548 Z-packet ...'' command that updates all the Z packet types. */
1550 static enum auto_boolean remote_Z_packet_detect;
1553 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1554 struct cmd_list_element *c)
1558 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1559 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1563 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1564 struct cmd_list_element *c,
1569 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1571 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1575 /* Returns true if the multi-process extensions are in effect. */
1578 remote_multi_process_p (struct remote_state *rs)
1580 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1583 /* Returns true if fork events are supported. */
1586 remote_fork_event_p (struct remote_state *rs)
1588 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1591 /* Returns true if vfork events are supported. */
1594 remote_vfork_event_p (struct remote_state *rs)
1596 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1599 /* Returns true if exec events are supported. */
1602 remote_exec_event_p (struct remote_state *rs)
1604 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1607 /* Insert fork catchpoint target routine. If fork events are enabled
1608 then return success, nothing more to do. */
1611 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1613 struct remote_state *rs = get_remote_state ();
1615 return !remote_fork_event_p (rs);
1618 /* Remove fork catchpoint target routine. Nothing to do, just
1622 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1627 /* Insert vfork catchpoint target routine. If vfork events are enabled
1628 then return success, nothing more to do. */
1631 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1633 struct remote_state *rs = get_remote_state ();
1635 return !remote_vfork_event_p (rs);
1638 /* Remove vfork catchpoint target routine. Nothing to do, just
1642 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1647 /* Insert exec catchpoint target routine. If exec events are
1648 enabled, just return success. */
1651 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1653 struct remote_state *rs = get_remote_state ();
1655 return !remote_exec_event_p (rs);
1658 /* Remove exec catchpoint target routine. Nothing to do, just
1662 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1667 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1668 static struct async_signal_handler *async_sigint_remote_twice_token;
1669 static struct async_signal_handler *async_sigint_remote_token;
1672 /* Asynchronous signal handle registered as event loop source for
1673 when we have pending events ready to be passed to the core. */
1675 static struct async_event_handler *remote_async_inferior_event_token;
1679 static ptid_t magic_null_ptid;
1680 static ptid_t not_sent_ptid;
1681 static ptid_t any_thread_ptid;
1683 /* Find out if the stub attached to PID (and hence GDB should offer to
1684 detach instead of killing it when bailing out). */
1687 remote_query_attached (int pid)
1689 struct remote_state *rs = get_remote_state ();
1690 size_t size = get_remote_packet_size ();
1692 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1695 if (remote_multi_process_p (rs))
1696 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1698 xsnprintf (rs->buf, size, "qAttached");
1701 getpkt (&rs->buf, &rs->buf_size, 0);
1703 switch (packet_ok (rs->buf,
1704 &remote_protocol_packets[PACKET_qAttached]))
1707 if (strcmp (rs->buf, "1") == 0)
1711 warning (_("Remote failure reply: %s"), rs->buf);
1713 case PACKET_UNKNOWN:
1720 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1721 has been invented by GDB, instead of reported by the target. Since
1722 we can be connected to a remote system before before knowing about
1723 any inferior, mark the target with execution when we find the first
1724 inferior. If ATTACHED is 1, then we had just attached to this
1725 inferior. If it is 0, then we just created this inferior. If it
1726 is -1, then try querying the remote stub to find out if it had
1727 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1728 attempt to open this inferior's executable as the main executable
1729 if no main executable is open already. */
1731 static struct inferior *
1732 remote_add_inferior (int fake_pid_p, int pid, int attached,
1735 struct inferior *inf;
1737 /* Check whether this process we're learning about is to be
1738 considered attached, or if is to be considered to have been
1739 spawned by the stub. */
1741 attached = remote_query_attached (pid);
1743 if (gdbarch_has_global_solist (target_gdbarch ()))
1745 /* If the target shares code across all inferiors, then every
1746 attach adds a new inferior. */
1747 inf = add_inferior (pid);
1749 /* ... and every inferior is bound to the same program space.
1750 However, each inferior may still have its own address
1752 inf->aspace = maybe_new_address_space ();
1753 inf->pspace = current_program_space;
1757 /* In the traditional debugging scenario, there's a 1-1 match
1758 between program/address spaces. We simply bind the inferior
1759 to the program space's address space. */
1760 inf = current_inferior ();
1761 inferior_appeared (inf, pid);
1764 inf->attach_flag = attached;
1765 inf->fake_pid_p = fake_pid_p;
1767 /* If no main executable is currently open then attempt to
1768 open the file that was executed to create this inferior. */
1769 if (try_open_exec && get_exec_file (0) == NULL)
1770 exec_file_locate_attach (pid, 1);
1775 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1776 according to RUNNING. */
1779 remote_add_thread (ptid_t ptid, int running)
1781 struct remote_state *rs = get_remote_state ();
1783 /* GDB historically didn't pull threads in the initial connection
1784 setup. If the remote target doesn't even have a concept of
1785 threads (e.g., a bare-metal target), even if internally we
1786 consider that a single-threaded target, mentioning a new thread
1787 might be confusing to the user. Be silent then, preserving the
1788 age old behavior. */
1789 if (rs->starting_up)
1790 add_thread_silent (ptid);
1794 set_executing (ptid, running);
1795 set_running (ptid, running);
1798 /* Come here when we learn about a thread id from the remote target.
1799 It may be the first time we hear about such thread, so take the
1800 opportunity to add it to GDB's thread list. In case this is the
1801 first time we're noticing its corresponding inferior, add it to
1802 GDB's inferior list as well. */
1805 remote_notice_new_inferior (ptid_t currthread, int running)
1807 /* If this is a new thread, add it to GDB's thread list.
1808 If we leave it up to WFI to do this, bad things will happen. */
1810 if (in_thread_list (currthread) && is_exited (currthread))
1812 /* We're seeing an event on a thread id we knew had exited.
1813 This has to be a new thread reusing the old id. Add it. */
1814 remote_add_thread (currthread, running);
1818 if (!in_thread_list (currthread))
1820 struct inferior *inf = NULL;
1821 int pid = ptid_get_pid (currthread);
1823 if (ptid_is_pid (inferior_ptid)
1824 && pid == ptid_get_pid (inferior_ptid))
1826 /* inferior_ptid has no thread member yet. This can happen
1827 with the vAttach -> remote_wait,"TAAthread:" path if the
1828 stub doesn't support qC. This is the first stop reported
1829 after an attach, so this is the main thread. Update the
1830 ptid in the thread list. */
1831 if (in_thread_list (pid_to_ptid (pid)))
1832 thread_change_ptid (inferior_ptid, currthread);
1835 remote_add_thread (currthread, running);
1836 inferior_ptid = currthread;
1841 if (ptid_equal (magic_null_ptid, inferior_ptid))
1843 /* inferior_ptid is not set yet. This can happen with the
1844 vRun -> remote_wait,"TAAthread:" path if the stub
1845 doesn't support qC. This is the first stop reported
1846 after an attach, so this is the main thread. Update the
1847 ptid in the thread list. */
1848 thread_change_ptid (inferior_ptid, currthread);
1852 /* When connecting to a target remote, or to a target
1853 extended-remote which already was debugging an inferior, we
1854 may not know about it yet. Add it before adding its child
1855 thread, so notifications are emitted in a sensible order. */
1856 if (!in_inferior_list (ptid_get_pid (currthread)))
1858 struct remote_state *rs = get_remote_state ();
1859 int fake_pid_p = !remote_multi_process_p (rs);
1861 inf = remote_add_inferior (fake_pid_p,
1862 ptid_get_pid (currthread), -1, 1);
1865 /* This is really a new thread. Add it. */
1866 remote_add_thread (currthread, running);
1868 /* If we found a new inferior, let the common code do whatever
1869 it needs to with it (e.g., read shared libraries, insert
1870 breakpoints), unless we're just setting up an all-stop
1874 struct remote_state *rs = get_remote_state ();
1876 if (non_stop || !rs->starting_up)
1877 notice_new_inferior (currthread, running, 0);
1882 /* Return the private thread data, creating it if necessary. */
1884 static struct private_thread_info *
1885 demand_private_info (ptid_t ptid)
1887 struct thread_info *info = find_thread_ptid (ptid);
1893 info->priv = XNEW (struct private_thread_info);
1894 info->private_dtor = free_private_thread_info;
1895 info->priv->core = -1;
1896 info->priv->extra = 0;
1902 /* Call this function as a result of
1903 1) A halt indication (T packet) containing a thread id
1904 2) A direct query of currthread
1905 3) Successful execution of set thread */
1908 record_currthread (struct remote_state *rs, ptid_t currthread)
1910 rs->general_thread = currthread;
1913 /* If 'QPassSignals' is supported, tell the remote stub what signals
1914 it can simply pass through to the inferior without reporting. */
1917 remote_pass_signals (struct target_ops *self,
1918 int numsigs, unsigned char *pass_signals)
1920 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1922 char *pass_packet, *p;
1924 struct remote_state *rs = get_remote_state ();
1926 gdb_assert (numsigs < 256);
1927 for (i = 0; i < numsigs; i++)
1929 if (pass_signals[i])
1932 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1933 strcpy (pass_packet, "QPassSignals:");
1934 p = pass_packet + strlen (pass_packet);
1935 for (i = 0; i < numsigs; i++)
1937 if (pass_signals[i])
1940 *p++ = tohex (i >> 4);
1941 *p++ = tohex (i & 15);
1950 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1952 putpkt (pass_packet);
1953 getpkt (&rs->buf, &rs->buf_size, 0);
1954 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1955 if (rs->last_pass_packet)
1956 xfree (rs->last_pass_packet);
1957 rs->last_pass_packet = pass_packet;
1960 xfree (pass_packet);
1964 /* If 'QProgramSignals' is supported, tell the remote stub what
1965 signals it should pass through to the inferior when detaching. */
1968 remote_program_signals (struct target_ops *self,
1969 int numsigs, unsigned char *signals)
1971 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1975 struct remote_state *rs = get_remote_state ();
1977 gdb_assert (numsigs < 256);
1978 for (i = 0; i < numsigs; i++)
1983 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1984 strcpy (packet, "QProgramSignals:");
1985 p = packet + strlen (packet);
1986 for (i = 0; i < numsigs; i++)
1988 if (signal_pass_state (i))
1991 *p++ = tohex (i >> 4);
1992 *p++ = tohex (i & 15);
2001 if (!rs->last_program_signals_packet
2002 || strcmp (rs->last_program_signals_packet, packet) != 0)
2005 getpkt (&rs->buf, &rs->buf_size, 0);
2006 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2007 xfree (rs->last_program_signals_packet);
2008 rs->last_program_signals_packet = packet;
2015 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2016 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2017 thread. If GEN is set, set the general thread, if not, then set
2018 the step/continue thread. */
2020 set_thread (struct ptid ptid, int gen)
2022 struct remote_state *rs = get_remote_state ();
2023 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2024 char *buf = rs->buf;
2025 char *endbuf = rs->buf + get_remote_packet_size ();
2027 if (ptid_equal (state, ptid))
2031 *buf++ = gen ? 'g' : 'c';
2032 if (ptid_equal (ptid, magic_null_ptid))
2033 xsnprintf (buf, endbuf - buf, "0");
2034 else if (ptid_equal (ptid, any_thread_ptid))
2035 xsnprintf (buf, endbuf - buf, "0");
2036 else if (ptid_equal (ptid, minus_one_ptid))
2037 xsnprintf (buf, endbuf - buf, "-1");
2039 write_ptid (buf, endbuf, ptid);
2041 getpkt (&rs->buf, &rs->buf_size, 0);
2043 rs->general_thread = ptid;
2045 rs->continue_thread = ptid;
2049 set_general_thread (struct ptid ptid)
2051 set_thread (ptid, 1);
2055 set_continue_thread (struct ptid ptid)
2057 set_thread (ptid, 0);
2060 /* Change the remote current process. Which thread within the process
2061 ends up selected isn't important, as long as it is the same process
2062 as what INFERIOR_PTID points to.
2064 This comes from that fact that there is no explicit notion of
2065 "selected process" in the protocol. The selected process for
2066 general operations is the process the selected general thread
2070 set_general_process (void)
2072 struct remote_state *rs = get_remote_state ();
2074 /* If the remote can't handle multiple processes, don't bother. */
2075 if (!rs->extended || !remote_multi_process_p (rs))
2078 /* We only need to change the remote current thread if it's pointing
2079 at some other process. */
2080 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2081 set_general_thread (inferior_ptid);
2085 /* Return nonzero if this is the main thread that we made up ourselves
2086 to model non-threaded targets as single-threaded. */
2089 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2091 struct remote_state *rs = get_remote_state ();
2094 if (ptid_equal (ptid, magic_null_ptid))
2095 /* The main thread is always alive. */
2098 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2099 /* The main thread is always alive. This can happen after a
2100 vAttach, if the remote side doesn't support
2107 /* Return nonzero if the thread PTID is still alive on the remote
2111 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2113 struct remote_state *rs = get_remote_state ();
2116 /* Check if this is a thread that we made up ourselves to model
2117 non-threaded targets as single-threaded. */
2118 if (remote_thread_always_alive (ops, ptid))
2122 endp = rs->buf + get_remote_packet_size ();
2125 write_ptid (p, endp, ptid);
2128 getpkt (&rs->buf, &rs->buf_size, 0);
2129 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2132 /* About these extended threadlist and threadinfo packets. They are
2133 variable length packets but, the fields within them are often fixed
2134 length. They are redundent enough to send over UDP as is the
2135 remote protocol in general. There is a matching unit test module
2138 /* WARNING: This threadref data structure comes from the remote O.S.,
2139 libstub protocol encoding, and remote.c. It is not particularly
2142 /* Right now, the internal structure is int. We want it to be bigger.
2143 Plan to fix this. */
2145 typedef int gdb_threadref; /* Internal GDB thread reference. */
2147 /* gdb_ext_thread_info is an internal GDB data structure which is
2148 equivalent to the reply of the remote threadinfo packet. */
2150 struct gdb_ext_thread_info
2152 threadref threadid; /* External form of thread reference. */
2153 int active; /* Has state interesting to GDB?
2155 char display[256]; /* Brief state display, name,
2156 blocked/suspended. */
2157 char shortname[32]; /* To be used to name threads. */
2158 char more_display[256]; /* Long info, statistics, queue depth,
2162 /* The volume of remote transfers can be limited by submitting
2163 a mask containing bits specifying the desired information.
2164 Use a union of these values as the 'selection' parameter to
2165 get_thread_info. FIXME: Make these TAG names more thread specific. */
2167 #define TAG_THREADID 1
2168 #define TAG_EXISTS 2
2169 #define TAG_DISPLAY 4
2170 #define TAG_THREADNAME 8
2171 #define TAG_MOREDISPLAY 16
2173 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2175 static char *unpack_nibble (char *buf, int *val);
2177 static char *unpack_byte (char *buf, int *value);
2179 static char *pack_int (char *buf, int value);
2181 static char *unpack_int (char *buf, int *value);
2183 static char *unpack_string (char *src, char *dest, int length);
2185 static char *pack_threadid (char *pkt, threadref *id);
2187 static char *unpack_threadid (char *inbuf, threadref *id);
2189 void int_to_threadref (threadref *id, int value);
2191 static int threadref_to_int (threadref *ref);
2193 static void copy_threadref (threadref *dest, threadref *src);
2195 static int threadmatch (threadref *dest, threadref *src);
2197 static char *pack_threadinfo_request (char *pkt, int mode,
2200 static int remote_unpack_thread_info_response (char *pkt,
2201 threadref *expectedref,
2202 struct gdb_ext_thread_info
2206 static int remote_get_threadinfo (threadref *threadid,
2207 int fieldset, /*TAG mask */
2208 struct gdb_ext_thread_info *info);
2210 static char *pack_threadlist_request (char *pkt, int startflag,
2212 threadref *nextthread);
2214 static int parse_threadlist_response (char *pkt,
2216 threadref *original_echo,
2217 threadref *resultlist,
2220 static int remote_get_threadlist (int startflag,
2221 threadref *nextthread,
2225 threadref *threadlist);
2227 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2229 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2230 void *context, int looplimit);
2232 static int remote_newthread_step (threadref *ref, void *context);
2235 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2236 buffer we're allowed to write to. Returns
2237 BUF+CHARACTERS_WRITTEN. */
2240 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2243 struct remote_state *rs = get_remote_state ();
2245 if (remote_multi_process_p (rs))
2247 pid = ptid_get_pid (ptid);
2249 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2251 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2253 tid = ptid_get_lwp (ptid);
2255 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2257 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2262 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2263 passed the last parsed char. Returns null_ptid on error. */
2266 read_ptid (char *buf, char **obuf)
2270 ULONGEST pid = 0, tid = 0;
2274 /* Multi-process ptid. */
2275 pp = unpack_varlen_hex (p + 1, &pid);
2277 error (_("invalid remote ptid: %s"), p);
2280 pp = unpack_varlen_hex (p + 1, &tid);
2283 return ptid_build (pid, tid, 0);
2286 /* No multi-process. Just a tid. */
2287 pp = unpack_varlen_hex (p, &tid);
2289 /* Return null_ptid when no thread id is found. */
2297 /* Since the stub is not sending a process id, then default to
2298 what's in inferior_ptid, unless it's null at this point. If so,
2299 then since there's no way to know the pid of the reported
2300 threads, use the magic number. */
2301 if (ptid_equal (inferior_ptid, null_ptid))
2302 pid = ptid_get_pid (magic_null_ptid);
2304 pid = ptid_get_pid (inferior_ptid);
2308 return ptid_build (pid, tid, 0);
2314 if (ch >= 'a' && ch <= 'f')
2315 return ch - 'a' + 10;
2316 if (ch >= '0' && ch <= '9')
2318 if (ch >= 'A' && ch <= 'F')
2319 return ch - 'A' + 10;
2324 stub_unpack_int (char *buff, int fieldlength)
2331 nibble = stubhex (*buff++);
2335 retval = retval << 4;
2341 unpack_nibble (char *buf, int *val)
2343 *val = fromhex (*buf++);
2348 unpack_byte (char *buf, int *value)
2350 *value = stub_unpack_int (buf, 2);
2355 pack_int (char *buf, int value)
2357 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2358 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2359 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2360 buf = pack_hex_byte (buf, (value & 0xff));
2365 unpack_int (char *buf, int *value)
2367 *value = stub_unpack_int (buf, 8);
2371 #if 0 /* Currently unused, uncomment when needed. */
2372 static char *pack_string (char *pkt, char *string);
2375 pack_string (char *pkt, char *string)
2380 len = strlen (string);
2382 len = 200; /* Bigger than most GDB packets, junk??? */
2383 pkt = pack_hex_byte (pkt, len);
2387 if ((ch == '\0') || (ch == '#'))
2388 ch = '*'; /* Protect encapsulation. */
2393 #endif /* 0 (unused) */
2396 unpack_string (char *src, char *dest, int length)
2405 pack_threadid (char *pkt, threadref *id)
2408 unsigned char *altid;
2410 altid = (unsigned char *) id;
2411 limit = pkt + BUF_THREAD_ID_SIZE;
2413 pkt = pack_hex_byte (pkt, *altid++);
2419 unpack_threadid (char *inbuf, threadref *id)
2422 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2425 altref = (char *) id;
2427 while (inbuf < limit)
2429 x = stubhex (*inbuf++);
2430 y = stubhex (*inbuf++);
2431 *altref++ = (x << 4) | y;
2436 /* Externally, threadrefs are 64 bits but internally, they are still
2437 ints. This is due to a mismatch of specifications. We would like
2438 to use 64bit thread references internally. This is an adapter
2442 int_to_threadref (threadref *id, int value)
2444 unsigned char *scan;
2446 scan = (unsigned char *) id;
2452 *scan++ = (value >> 24) & 0xff;
2453 *scan++ = (value >> 16) & 0xff;
2454 *scan++ = (value >> 8) & 0xff;
2455 *scan++ = (value & 0xff);
2459 threadref_to_int (threadref *ref)
2462 unsigned char *scan;
2468 value = (value << 8) | ((*scan++) & 0xff);
2473 copy_threadref (threadref *dest, threadref *src)
2476 unsigned char *csrc, *cdest;
2478 csrc = (unsigned char *) src;
2479 cdest = (unsigned char *) dest;
2486 threadmatch (threadref *dest, threadref *src)
2488 /* Things are broken right now, so just assume we got a match. */
2490 unsigned char *srcp, *destp;
2492 srcp = (char *) src;
2493 destp = (char *) dest;
2497 result &= (*srcp++ == *destp++) ? 1 : 0;
2504 threadid:1, # always request threadid
2511 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2514 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2516 *pkt++ = 'q'; /* Info Query */
2517 *pkt++ = 'P'; /* process or thread info */
2518 pkt = pack_int (pkt, mode); /* mode */
2519 pkt = pack_threadid (pkt, id); /* threadid */
2520 *pkt = '\0'; /* terminate */
2524 /* These values tag the fields in a thread info response packet. */
2525 /* Tagging the fields allows us to request specific fields and to
2526 add more fields as time goes by. */
2528 #define TAG_THREADID 1 /* Echo the thread identifier. */
2529 #define TAG_EXISTS 2 /* Is this process defined enough to
2530 fetch registers and its stack? */
2531 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2532 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2533 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2537 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2538 struct gdb_ext_thread_info *info)
2540 struct remote_state *rs = get_remote_state ();
2544 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2547 /* info->threadid = 0; FIXME: implement zero_threadref. */
2549 info->display[0] = '\0';
2550 info->shortname[0] = '\0';
2551 info->more_display[0] = '\0';
2553 /* Assume the characters indicating the packet type have been
2555 pkt = unpack_int (pkt, &mask); /* arg mask */
2556 pkt = unpack_threadid (pkt, &ref);
2559 warning (_("Incomplete response to threadinfo request."));
2560 if (!threadmatch (&ref, expectedref))
2561 { /* This is an answer to a different request. */
2562 warning (_("ERROR RMT Thread info mismatch."));
2565 copy_threadref (&info->threadid, &ref);
2567 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2569 /* Packets are terminated with nulls. */
2570 while ((pkt < limit) && mask && *pkt)
2572 pkt = unpack_int (pkt, &tag); /* tag */
2573 pkt = unpack_byte (pkt, &length); /* length */
2574 if (!(tag & mask)) /* Tags out of synch with mask. */
2576 warning (_("ERROR RMT: threadinfo tag mismatch."));
2580 if (tag == TAG_THREADID)
2584 warning (_("ERROR RMT: length of threadid is not 16."));
2588 pkt = unpack_threadid (pkt, &ref);
2589 mask = mask & ~TAG_THREADID;
2592 if (tag == TAG_EXISTS)
2594 info->active = stub_unpack_int (pkt, length);
2596 mask = mask & ~(TAG_EXISTS);
2599 warning (_("ERROR RMT: 'exists' length too long."));
2605 if (tag == TAG_THREADNAME)
2607 pkt = unpack_string (pkt, &info->shortname[0], length);
2608 mask = mask & ~TAG_THREADNAME;
2611 if (tag == TAG_DISPLAY)
2613 pkt = unpack_string (pkt, &info->display[0], length);
2614 mask = mask & ~TAG_DISPLAY;
2617 if (tag == TAG_MOREDISPLAY)
2619 pkt = unpack_string (pkt, &info->more_display[0], length);
2620 mask = mask & ~TAG_MOREDISPLAY;
2623 warning (_("ERROR RMT: unknown thread info tag."));
2624 break; /* Not a tag we know about. */
2630 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2631 struct gdb_ext_thread_info *info)
2633 struct remote_state *rs = get_remote_state ();
2636 pack_threadinfo_request (rs->buf, fieldset, threadid);
2638 getpkt (&rs->buf, &rs->buf_size, 0);
2640 if (rs->buf[0] == '\0')
2643 result = remote_unpack_thread_info_response (rs->buf + 2,
2648 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2651 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2652 threadref *nextthread)
2654 *pkt++ = 'q'; /* info query packet */
2655 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2656 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2657 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2658 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2663 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2666 parse_threadlist_response (char *pkt, int result_limit,
2667 threadref *original_echo, threadref *resultlist,
2670 struct remote_state *rs = get_remote_state ();
2672 int count, resultcount, done;
2675 /* Assume the 'q' and 'M chars have been stripped. */
2676 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2677 /* done parse past here */
2678 pkt = unpack_byte (pkt, &count); /* count field */
2679 pkt = unpack_nibble (pkt, &done);
2680 /* The first threadid is the argument threadid. */
2681 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2682 while ((count-- > 0) && (pkt < limit))
2684 pkt = unpack_threadid (pkt, resultlist++);
2685 if (resultcount++ >= result_limit)
2693 /* Fetch the next batch of threads from the remote. Returns -1 if the
2694 qL packet is not supported, 0 on error and 1 on success. */
2697 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2698 int *done, int *result_count, threadref *threadlist)
2700 struct remote_state *rs = get_remote_state ();
2703 /* Trancate result limit to be smaller than the packet size. */
2704 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2705 >= get_remote_packet_size ())
2706 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2708 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2710 getpkt (&rs->buf, &rs->buf_size, 0);
2711 if (*rs->buf == '\0')
2713 /* Packet not supported. */
2718 parse_threadlist_response (rs->buf + 2, result_limit,
2719 &rs->echo_nextthread, threadlist, done);
2721 if (!threadmatch (&rs->echo_nextthread, nextthread))
2723 /* FIXME: This is a good reason to drop the packet. */
2724 /* Possably, there is a duplicate response. */
2726 retransmit immediatly - race conditions
2727 retransmit after timeout - yes
2729 wait for packet, then exit
2731 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2732 return 0; /* I choose simply exiting. */
2734 if (*result_count <= 0)
2738 warning (_("RMT ERROR : failed to get remote thread list."));
2741 return result; /* break; */
2743 if (*result_count > result_limit)
2746 warning (_("RMT ERROR: threadlist response longer than requested."));
2752 /* Fetch the list of remote threads, with the qL packet, and call
2753 STEPFUNCTION for each thread found. Stops iterating and returns 1
2754 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2755 STEPFUNCTION returns false. If the packet is not supported,
2759 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2762 struct remote_state *rs = get_remote_state ();
2763 int done, i, result_count;
2771 if (loopcount++ > looplimit)
2774 warning (_("Remote fetch threadlist -infinite loop-."));
2777 result = remote_get_threadlist (startflag, &rs->nextthread,
2778 MAXTHREADLISTRESULTS,
2779 &done, &result_count,
2780 rs->resultthreadlist);
2783 /* Clear for later iterations. */
2785 /* Setup to resume next batch of thread references, set nextthread. */
2786 if (result_count >= 1)
2787 copy_threadref (&rs->nextthread,
2788 &rs->resultthreadlist[result_count - 1]);
2790 while (result_count--)
2792 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2802 /* A thread found on the remote target. */
2804 typedef struct thread_item
2806 /* The thread's PTID. */
2809 /* The thread's extra info. May be NULL. */
2812 /* The core the thread was running on. -1 if not known. */
2815 DEF_VEC_O(thread_item_t);
2817 /* Context passed around to the various methods listing remote
2818 threads. As new threads are found, they're added to the ITEMS
2821 struct threads_listing_context
2823 /* The threads found on the remote target. */
2824 VEC (thread_item_t) *items;
2827 /* Discard the contents of the constructed thread listing context. */
2830 clear_threads_listing_context (void *p)
2832 struct threads_listing_context *context = p;
2834 struct thread_item *item;
2836 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2837 xfree (item->extra);
2839 VEC_free (thread_item_t, context->items);
2842 /* Remove the thread specified as the related_pid field of WS
2843 from the CONTEXT list. */
2846 threads_listing_context_remove (struct target_waitstatus *ws,
2847 struct threads_listing_context *context)
2849 struct thread_item *item;
2851 ptid_t child_ptid = ws->value.related_pid;
2853 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2855 if (ptid_equal (item->ptid, child_ptid))
2857 VEC_ordered_remove (thread_item_t, context->items, i);
2864 remote_newthread_step (threadref *ref, void *data)
2866 struct threads_listing_context *context = data;
2867 struct thread_item item;
2868 int pid = ptid_get_pid (inferior_ptid);
2870 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2874 VEC_safe_push (thread_item_t, context->items, &item);
2876 return 1; /* continue iterator */
2879 #define CRAZY_MAX_THREADS 1000
2882 remote_current_thread (ptid_t oldpid)
2884 struct remote_state *rs = get_remote_state ();
2887 getpkt (&rs->buf, &rs->buf_size, 0);
2888 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2893 result = read_ptid (&rs->buf[2], &obuf);
2894 if (*obuf != '\0' && remote_debug)
2895 fprintf_unfiltered (gdb_stdlog,
2896 "warning: garbage in qC reply\n");
2904 /* List remote threads using the deprecated qL packet. */
2907 remote_get_threads_with_ql (struct target_ops *ops,
2908 struct threads_listing_context *context)
2910 if (remote_threadlist_iterator (remote_newthread_step, context,
2911 CRAZY_MAX_THREADS) >= 0)
2917 #if defined(HAVE_LIBEXPAT)
2920 start_thread (struct gdb_xml_parser *parser,
2921 const struct gdb_xml_element *element,
2922 void *user_data, VEC(gdb_xml_value_s) *attributes)
2924 struct threads_listing_context *data = user_data;
2926 struct thread_item item;
2928 struct gdb_xml_value *attr;
2930 id = xml_find_attribute (attributes, "id")->value;
2931 item.ptid = read_ptid (id, NULL);
2933 attr = xml_find_attribute (attributes, "core");
2935 item.core = *(ULONGEST *) attr->value;
2941 VEC_safe_push (thread_item_t, data->items, &item);
2945 end_thread (struct gdb_xml_parser *parser,
2946 const struct gdb_xml_element *element,
2947 void *user_data, const char *body_text)
2949 struct threads_listing_context *data = user_data;
2951 if (body_text && *body_text)
2952 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2955 const struct gdb_xml_attribute thread_attributes[] = {
2956 { "id", GDB_XML_AF_NONE, NULL, NULL },
2957 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2958 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2961 const struct gdb_xml_element thread_children[] = {
2962 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2965 const struct gdb_xml_element threads_children[] = {
2966 { "thread", thread_attributes, thread_children,
2967 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2968 start_thread, end_thread },
2969 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2972 const struct gdb_xml_element threads_elements[] = {
2973 { "threads", NULL, threads_children,
2974 GDB_XML_EF_NONE, NULL, NULL },
2975 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2980 /* List remote threads using qXfer:threads:read. */
2983 remote_get_threads_with_qxfer (struct target_ops *ops,
2984 struct threads_listing_context *context)
2986 #if defined(HAVE_LIBEXPAT)
2987 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2989 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2990 struct cleanup *back_to = make_cleanup (xfree, xml);
2992 if (xml != NULL && *xml != '\0')
2994 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2995 threads_elements, xml, context);
2998 do_cleanups (back_to);
3006 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3009 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3010 struct threads_listing_context *context)
3012 struct remote_state *rs = get_remote_state ();
3014 if (rs->use_threadinfo_query)
3018 putpkt ("qfThreadInfo");
3019 getpkt (&rs->buf, &rs->buf_size, 0);
3021 if (bufp[0] != '\0') /* q packet recognized */
3023 while (*bufp++ == 'm') /* reply contains one or more TID */
3027 struct thread_item item;
3029 item.ptid = read_ptid (bufp, &bufp);
3033 VEC_safe_push (thread_item_t, context->items, &item);
3035 while (*bufp++ == ','); /* comma-separated list */
3036 putpkt ("qsThreadInfo");
3037 getpkt (&rs->buf, &rs->buf_size, 0);
3044 /* Packet not recognized. */
3045 rs->use_threadinfo_query = 0;
3052 /* Implement the to_update_thread_list function for the remote
3056 remote_update_thread_list (struct target_ops *ops)
3058 struct remote_state *rs = get_remote_state ();
3059 struct threads_listing_context context;
3060 struct cleanup *old_chain;
3063 context.items = NULL;
3064 old_chain = make_cleanup (clear_threads_listing_context, &context);
3066 /* We have a few different mechanisms to fetch the thread list. Try
3067 them all, starting with the most preferred one first, falling
3068 back to older methods. */
3069 if (remote_get_threads_with_qxfer (ops, &context)
3070 || remote_get_threads_with_qthreadinfo (ops, &context)
3071 || remote_get_threads_with_ql (ops, &context))
3074 struct thread_item *item;
3075 struct thread_info *tp, *tmp;
3079 if (VEC_empty (thread_item_t, context.items)
3080 && remote_thread_always_alive (ops, inferior_ptid))
3082 /* Some targets don't really support threads, but still
3083 reply an (empty) thread list in response to the thread
3084 listing packets, instead of replying "packet not
3085 supported". Exit early so we don't delete the main
3087 do_cleanups (old_chain);
3091 /* CONTEXT now holds the current thread list on the remote
3092 target end. Delete GDB-side threads no longer found on the
3094 ALL_THREADS_SAFE (tp, tmp)
3097 VEC_iterate (thread_item_t, context.items, i, item);
3100 if (ptid_equal (item->ptid, tp->ptid))
3104 if (i == VEC_length (thread_item_t, context.items))
3107 delete_thread (tp->ptid);
3111 /* Remove any unreported fork child threads from CONTEXT so
3112 that we don't interfere with follow fork, which is where
3113 creation of such threads is handled. */
3114 remove_new_fork_children (&context);
3116 /* And now add threads we don't know about yet to our list. */
3118 VEC_iterate (thread_item_t, context.items, i, item);
3121 if (!ptid_equal (item->ptid, null_ptid))
3123 struct private_thread_info *info;
3124 /* In non-stop mode, we assume new found threads are
3125 running until proven otherwise with a stop reply. In
3126 all-stop, we can only get here if all threads are
3128 int running = non_stop ? 1 : 0;
3130 remote_notice_new_inferior (item->ptid, running);
3132 info = demand_private_info (item->ptid);
3133 info->core = item->core;
3134 info->extra = item->extra;
3142 /* If no thread listing method is supported, then query whether
3143 each known thread is alive, one by one, with the T packet.
3144 If the target doesn't support threads at all, then this is a
3145 no-op. See remote_thread_alive. */
3149 do_cleanups (old_chain);
3153 * Collect a descriptive string about the given thread.
3154 * The target may say anything it wants to about the thread
3155 * (typically info about its blocked / runnable state, name, etc.).
3156 * This string will appear in the info threads display.
3158 * Optional: targets are not required to implement this function.
3162 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3164 struct remote_state *rs = get_remote_state ();
3168 struct gdb_ext_thread_info threadinfo;
3169 static char display_buf[100]; /* arbitrary... */
3170 int n = 0; /* position in display_buf */
3172 if (rs->remote_desc == 0) /* paranoia */
3173 internal_error (__FILE__, __LINE__,
3174 _("remote_threads_extra_info"));
3176 if (ptid_equal (tp->ptid, magic_null_ptid)
3177 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3178 /* This is the main thread which was added by GDB. The remote
3179 server doesn't know about it. */
3182 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3184 struct thread_info *info = find_thread_ptid (tp->ptid);
3186 if (info && info->priv)
3187 return info->priv->extra;
3192 if (rs->use_threadextra_query)
3195 char *endb = rs->buf + get_remote_packet_size ();
3197 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3199 write_ptid (b, endb, tp->ptid);
3202 getpkt (&rs->buf, &rs->buf_size, 0);
3203 if (rs->buf[0] != 0)
3205 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3206 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3207 display_buf [result] = '\0';
3212 /* If the above query fails, fall back to the old method. */
3213 rs->use_threadextra_query = 0;
3214 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3215 | TAG_MOREDISPLAY | TAG_DISPLAY;
3216 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3217 if (remote_get_threadinfo (&id, set, &threadinfo))
3218 if (threadinfo.active)
3220 if (*threadinfo.shortname)
3221 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3222 " Name: %s,", threadinfo.shortname);
3223 if (*threadinfo.display)
3224 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3225 " State: %s,", threadinfo.display);
3226 if (*threadinfo.more_display)
3227 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3228 " Priority: %s", threadinfo.more_display);
3232 /* For purely cosmetic reasons, clear up trailing commas. */
3233 if (',' == display_buf[n-1])
3234 display_buf[n-1] = ' ';
3243 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3244 struct static_tracepoint_marker *marker)
3246 struct remote_state *rs = get_remote_state ();
3249 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3251 p += hexnumstr (p, addr);
3253 getpkt (&rs->buf, &rs->buf_size, 0);
3257 error (_("Remote failure reply: %s"), p);
3261 parse_static_tracepoint_marker_definition (p, &p, marker);
3268 static VEC(static_tracepoint_marker_p) *
3269 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3272 struct remote_state *rs = get_remote_state ();
3273 VEC(static_tracepoint_marker_p) *markers = NULL;
3274 struct static_tracepoint_marker *marker = NULL;
3275 struct cleanup *old_chain;
3278 /* Ask for a first packet of static tracepoint marker
3281 getpkt (&rs->buf, &rs->buf_size, 0);
3284 error (_("Remote failure reply: %s"), p);
3286 old_chain = make_cleanup (free_current_marker, &marker);
3291 marker = XCNEW (struct static_tracepoint_marker);
3295 parse_static_tracepoint_marker_definition (p, &p, marker);
3297 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3299 VEC_safe_push (static_tracepoint_marker_p,
3305 release_static_tracepoint_marker (marker);
3306 memset (marker, 0, sizeof (*marker));
3309 while (*p++ == ','); /* comma-separated list */
3310 /* Ask for another packet of static tracepoint definition. */
3312 getpkt (&rs->buf, &rs->buf_size, 0);
3316 do_cleanups (old_chain);
3321 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3324 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3326 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3330 /* Restart the remote side; this is an extended protocol operation. */
3333 extended_remote_restart (void)
3335 struct remote_state *rs = get_remote_state ();
3337 /* Send the restart command; for reasons I don't understand the
3338 remote side really expects a number after the "R". */
3339 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3342 remote_fileio_reset ();
3345 /* Clean up connection to a remote debugger. */
3348 remote_close (struct target_ops *self)
3350 struct remote_state *rs = get_remote_state ();
3352 if (rs->remote_desc == NULL)
3353 return; /* already closed */
3355 /* Make sure we leave stdin registered in the event loop, and we
3356 don't leave the async SIGINT signal handler installed. */
3357 remote_terminal_ours (self);
3359 serial_close (rs->remote_desc);
3360 rs->remote_desc = NULL;
3362 /* We don't have a connection to the remote stub anymore. Get rid
3363 of all the inferiors and their threads we were controlling.
3364 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3365 will be unable to find the thread corresponding to (pid, 0, 0). */
3366 inferior_ptid = null_ptid;
3367 discard_all_inferiors ();
3369 /* We are closing the remote target, so we should discard
3370 everything of this target. */
3371 discard_pending_stop_replies_in_queue (rs);
3373 if (remote_async_inferior_event_token)
3374 delete_async_event_handler (&remote_async_inferior_event_token);
3376 remote_notif_state_xfree (rs->notif_state);
3378 trace_reset_local_state ();
3381 /* Query the remote side for the text, data and bss offsets. */
3386 struct remote_state *rs = get_remote_state ();
3389 int lose, num_segments = 0, do_sections, do_segments;
3390 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3391 struct section_offsets *offs;
3392 struct symfile_segment_data *data;
3394 if (symfile_objfile == NULL)
3397 putpkt ("qOffsets");
3398 getpkt (&rs->buf, &rs->buf_size, 0);
3401 if (buf[0] == '\000')
3402 return; /* Return silently. Stub doesn't support
3406 warning (_("Remote failure reply: %s"), buf);
3410 /* Pick up each field in turn. This used to be done with scanf, but
3411 scanf will make trouble if CORE_ADDR size doesn't match
3412 conversion directives correctly. The following code will work
3413 with any size of CORE_ADDR. */
3414 text_addr = data_addr = bss_addr = 0;
3418 if (startswith (ptr, "Text="))
3421 /* Don't use strtol, could lose on big values. */
3422 while (*ptr && *ptr != ';')
3423 text_addr = (text_addr << 4) + fromhex (*ptr++);
3425 if (startswith (ptr, ";Data="))
3428 while (*ptr && *ptr != ';')
3429 data_addr = (data_addr << 4) + fromhex (*ptr++);
3434 if (!lose && startswith (ptr, ";Bss="))
3437 while (*ptr && *ptr != ';')
3438 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3440 if (bss_addr != data_addr)
3441 warning (_("Target reported unsupported offsets: %s"), buf);
3446 else if (startswith (ptr, "TextSeg="))
3449 /* Don't use strtol, could lose on big values. */
3450 while (*ptr && *ptr != ';')
3451 text_addr = (text_addr << 4) + fromhex (*ptr++);
3454 if (startswith (ptr, ";DataSeg="))
3457 while (*ptr && *ptr != ';')
3458 data_addr = (data_addr << 4) + fromhex (*ptr++);
3466 error (_("Malformed response to offset query, %s"), buf);
3467 else if (*ptr != '\0')
3468 warning (_("Target reported unsupported offsets: %s"), buf);
3470 offs = ((struct section_offsets *)
3471 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3472 memcpy (offs, symfile_objfile->section_offsets,
3473 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3475 data = get_symfile_segment_data (symfile_objfile->obfd);
3476 do_segments = (data != NULL);
3477 do_sections = num_segments == 0;
3479 if (num_segments > 0)
3481 segments[0] = text_addr;
3482 segments[1] = data_addr;
3484 /* If we have two segments, we can still try to relocate everything
3485 by assuming that the .text and .data offsets apply to the whole
3486 text and data segments. Convert the offsets given in the packet
3487 to base addresses for symfile_map_offsets_to_segments. */
3488 else if (data && data->num_segments == 2)
3490 segments[0] = data->segment_bases[0] + text_addr;
3491 segments[1] = data->segment_bases[1] + data_addr;
3494 /* If the object file has only one segment, assume that it is text
3495 rather than data; main programs with no writable data are rare,
3496 but programs with no code are useless. Of course the code might
3497 have ended up in the data segment... to detect that we would need
3498 the permissions here. */
3499 else if (data && data->num_segments == 1)
3501 segments[0] = data->segment_bases[0] + text_addr;
3504 /* There's no way to relocate by segment. */
3510 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3511 offs, num_segments, segments);
3513 if (ret == 0 && !do_sections)
3514 error (_("Can not handle qOffsets TextSeg "
3515 "response with this symbol file"));
3522 free_symfile_segment_data (data);
3526 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3528 /* This is a temporary kludge to force data and bss to use the
3529 same offsets because that's what nlmconv does now. The real
3530 solution requires changes to the stub and remote.c that I
3531 don't have time to do right now. */
3533 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3534 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3537 objfile_relocate (symfile_objfile, offs);
3540 /* Send interrupt_sequence to remote target. */
3542 send_interrupt_sequence (void)
3544 struct remote_state *rs = get_remote_state ();
3546 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3547 remote_serial_write ("\x03", 1);
3548 else if (interrupt_sequence_mode == interrupt_sequence_break)
3549 serial_send_break (rs->remote_desc);
3550 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3552 serial_send_break (rs->remote_desc);
3553 remote_serial_write ("g", 1);
3556 internal_error (__FILE__, __LINE__,
3557 _("Invalid value for interrupt_sequence_mode: %s."),
3558 interrupt_sequence_mode);
3562 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3563 and extract the PTID. Returns NULL_PTID if not found. */
3566 stop_reply_extract_thread (char *stop_reply)
3568 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3572 /* Txx r:val ; r:val (...) */
3575 /* Look for "register" named "thread". */
3580 p1 = strchr (p, ':');
3584 if (strncmp (p, "thread", p1 - p) == 0)
3585 return read_ptid (++p1, &p);
3587 p1 = strchr (p, ';');
3599 /* Determine the remote side's current thread. If we have a stop
3600 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3601 "thread" register we can extract the current thread from. If not,
3602 ask the remote which is the current thread with qC. The former
3603 method avoids a roundtrip. */
3606 get_current_thread (char *wait_status)
3608 ptid_t ptid = null_ptid;
3610 /* Note we don't use remote_parse_stop_reply as that makes use of
3611 the target architecture, which we haven't yet fully determined at
3613 if (wait_status != NULL)
3614 ptid = stop_reply_extract_thread (wait_status);
3615 if (ptid_equal (ptid, null_ptid))
3616 ptid = remote_current_thread (inferior_ptid);
3621 /* Query the remote target for which is the current thread/process,
3622 add it to our tables, and update INFERIOR_PTID. The caller is
3623 responsible for setting the state such that the remote end is ready
3624 to return the current thread.
3626 This function is called after handling the '?' or 'vRun' packets,
3627 whose response is a stop reply from which we can also try
3628 extracting the thread. If the target doesn't support the explicit
3629 qC query, we infer the current thread from that stop reply, passed
3630 in in WAIT_STATUS, which may be NULL. */
3633 add_current_inferior_and_thread (char *wait_status)
3635 struct remote_state *rs = get_remote_state ();
3639 inferior_ptid = null_ptid;
3641 /* Now, if we have thread information, update inferior_ptid. */
3642 ptid = get_current_thread (wait_status);
3644 if (!ptid_equal (ptid, null_ptid))
3646 if (!remote_multi_process_p (rs))
3649 inferior_ptid = ptid;
3653 /* Without this, some commands which require an active target
3654 (such as kill) won't work. This variable serves (at least)
3655 double duty as both the pid of the target process (if it has
3656 such), and as a flag indicating that a target is active. */
3657 inferior_ptid = magic_null_ptid;
3661 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3663 /* Add the main thread. */
3664 add_thread_silent (inferior_ptid);
3667 /* Process all initial stop replies the remote side sent in response
3668 to the ? packet. These indicate threads that were already stopped
3669 on initial connection. We mark these threads as stopped and print
3670 their current frame before giving the user the prompt. */
3673 process_initial_stop_replies (void)
3675 int pending_stop_replies = stop_reply_queue_length ();
3677 /* Consume the initial pending events. */
3678 while (pending_stop_replies-- > 0)
3680 ptid_t waiton_ptid = minus_one_ptid;
3682 struct target_waitstatus ws;
3683 int ignore_event = 0;
3685 memset (&ws, 0, sizeof (ws));
3686 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3688 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3692 case TARGET_WAITKIND_IGNORE:
3693 case TARGET_WAITKIND_NO_RESUMED:
3694 case TARGET_WAITKIND_SIGNALLED:
3695 case TARGET_WAITKIND_EXITED:
3696 /* We shouldn't see these, but if we do, just ignore. */
3698 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3702 case TARGET_WAITKIND_EXECD:
3703 xfree (ws.value.execd_pathname);
3712 switch_to_thread (event_ptid);
3713 set_executing (event_ptid, 0);
3714 set_running (event_ptid, 0);
3716 stop_pc = get_frame_pc (get_current_frame ());
3717 set_current_sal_from_frame (get_current_frame ());
3719 if (ws.kind == TARGET_WAITKIND_STOPPED)
3721 enum gdb_signal sig = ws.value.sig;
3723 /* Stubs traditionally report SIGTRAP as initial signal,
3724 instead of signal 0. Suppress it. */
3725 if (sig == GDB_SIGNAL_TRAP)
3727 inferior_thread ()->suspend.stop_signal = sig;
3729 if (signal_print_state (sig))
3730 observer_notify_signal_received (sig);
3733 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
3734 observer_notify_normal_stop (NULL, 1);
3739 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3741 struct remote_state *rs = get_remote_state ();
3742 struct packet_config *noack_config;
3743 char *wait_status = NULL;
3745 immediate_quit++; /* Allow user to interrupt it. */
3748 if (interrupt_on_connect)
3749 send_interrupt_sequence ();
3751 /* Ack any packet which the remote side has already sent. */
3752 serial_write (rs->remote_desc, "+", 1);
3754 /* Signal other parts that we're going through the initial setup,
3755 and so things may not be stable yet. */
3756 rs->starting_up = 1;
3758 /* The first packet we send to the target is the optional "supported
3759 packets" request. If the target can answer this, it will tell us
3760 which later probes to skip. */
3761 remote_query_supported ();
3763 /* If the stub wants to get a QAllow, compose one and send it. */
3764 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3765 remote_set_permissions (target);
3767 /* Next, we possibly activate noack mode.
3769 If the QStartNoAckMode packet configuration is set to AUTO,
3770 enable noack mode if the stub reported a wish for it with
3773 If set to TRUE, then enable noack mode even if the stub didn't
3774 report it in qSupported. If the stub doesn't reply OK, the
3775 session ends with an error.
3777 If FALSE, then don't activate noack mode, regardless of what the
3778 stub claimed should be the default with qSupported. */
3780 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3781 if (packet_config_support (noack_config) != PACKET_DISABLE)
3783 putpkt ("QStartNoAckMode");
3784 getpkt (&rs->buf, &rs->buf_size, 0);
3785 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3791 /* Tell the remote that we are using the extended protocol. */
3793 getpkt (&rs->buf, &rs->buf_size, 0);
3796 /* Let the target know which signals it is allowed to pass down to
3798 update_signals_program_target ();
3800 /* Next, if the target can specify a description, read it. We do
3801 this before anything involving memory or registers. */
3802 target_find_description ();
3804 /* Next, now that we know something about the target, update the
3805 address spaces in the program spaces. */
3806 update_address_spaces ();
3808 /* On OSs where the list of libraries is global to all
3809 processes, we fetch them early. */
3810 if (gdbarch_has_global_solist (target_gdbarch ()))
3811 solib_add (NULL, from_tty, target, auto_solib_add);
3815 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3816 error (_("Non-stop mode requested, but remote "
3817 "does not support non-stop"));
3819 putpkt ("QNonStop:1");
3820 getpkt (&rs->buf, &rs->buf_size, 0);
3822 if (strcmp (rs->buf, "OK") != 0)
3823 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3825 /* Find about threads and processes the stub is already
3826 controlling. We default to adding them in the running state.
3827 The '?' query below will then tell us about which threads are
3829 remote_update_thread_list (target);
3831 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3833 /* Don't assume that the stub can operate in all-stop mode.
3834 Request it explicitly. */
3835 putpkt ("QNonStop:0");
3836 getpkt (&rs->buf, &rs->buf_size, 0);
3838 if (strcmp (rs->buf, "OK") != 0)
3839 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3842 /* Upload TSVs regardless of whether the target is running or not. The
3843 remote stub, such as GDBserver, may have some predefined or builtin
3844 TSVs, even if the target is not running. */
3845 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3847 struct uploaded_tsv *uploaded_tsvs = NULL;
3849 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3850 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3853 /* Check whether the target is running now. */
3855 getpkt (&rs->buf, &rs->buf_size, 0);
3861 struct inferior *inf;
3863 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3866 error (_("The target is not running (try extended-remote?)"));
3868 /* We're connected, but not running. Drop out before we
3869 call start_remote. */
3870 rs->starting_up = 0;
3875 /* Save the reply for later. */
3876 wait_status = alloca (strlen (rs->buf) + 1);
3877 strcpy (wait_status, rs->buf);
3880 /* Fetch thread list. */
3881 target_update_thread_list ();
3883 /* Let the stub know that we want it to return the thread. */
3884 set_continue_thread (minus_one_ptid);
3886 if (thread_count () == 0)
3888 /* Target has no concept of threads at all. GDB treats
3889 non-threaded target as single-threaded; add a main
3891 add_current_inferior_and_thread (wait_status);
3895 /* We have thread information; select the thread the target
3896 says should be current. If we're reconnecting to a
3897 multi-threaded program, this will ideally be the thread
3898 that last reported an event before GDB disconnected. */
3899 inferior_ptid = get_current_thread (wait_status);
3900 if (ptid_equal (inferior_ptid, null_ptid))
3902 /* Odd... The target was able to list threads, but not
3903 tell us which thread was current (no "thread"
3904 register in T stop reply?). Just pick the first
3905 thread in the thread list then. */
3908 fprintf_unfiltered (gdb_stdlog,
3909 "warning: couldn't determine remote "
3910 "current thread; picking first in list.\n");
3912 inferior_ptid = thread_list->ptid;
3916 /* init_wait_for_inferior should be called before get_offsets in order
3917 to manage `inserted' flag in bp loc in a correct state.
3918 breakpoint_init_inferior, called from init_wait_for_inferior, set
3919 `inserted' flag to 0, while before breakpoint_re_set, called from
3920 start_remote, set `inserted' flag to 1. In the initialization of
3921 inferior, breakpoint_init_inferior should be called first, and then
3922 breakpoint_re_set can be called. If this order is broken, state of
3923 `inserted' flag is wrong, and cause some problems on breakpoint
3925 init_wait_for_inferior ();
3927 get_offsets (); /* Get text, data & bss offsets. */
3929 /* If we could not find a description using qXfer, and we know
3930 how to do it some other way, try again. This is not
3931 supported for non-stop; it could be, but it is tricky if
3932 there are no stopped threads when we connect. */
3933 if (remote_read_description_p (target)
3934 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3936 target_clear_description ();
3937 target_find_description ();
3940 /* Use the previously fetched status. */
3941 gdb_assert (wait_status != NULL);
3942 strcpy (rs->buf, wait_status);
3943 rs->cached_wait_status = 1;
3946 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3950 ptid_t current_ptid;
3952 /* Clear WFI global state. Do this before finding about new
3953 threads and inferiors, and setting the current inferior.
3954 Otherwise we would clear the proceed status of the current
3955 inferior when we want its stop_soon state to be preserved
3956 (see notice_new_inferior). */
3957 init_wait_for_inferior ();
3959 /* In non-stop, we will either get an "OK", meaning that there
3960 are no stopped threads at this time; or, a regular stop
3961 reply. In the latter case, there may be more than one thread
3962 stopped --- we pull them all out using the vStopped
3964 if (strcmp (rs->buf, "OK") != 0)
3966 struct notif_client *notif = ¬if_client_stop;
3968 /* remote_notif_get_pending_replies acks this one, and gets
3970 rs->notif_state->pending_event[notif_client_stop.id]
3971 = remote_notif_parse (notif, rs->buf);
3972 remote_notif_get_pending_events (notif);
3975 if (thread_count () == 0)
3978 error (_("The target is not running (try extended-remote?)"));
3980 /* We're connected, but not running. Drop out before we
3981 call start_remote. */
3982 rs->starting_up = 0;
3986 /* Let the stub know that we want it to return the thread. */
3988 /* Force the stub to choose a thread. */
3989 set_general_thread (null_ptid);
3992 current_ptid = remote_current_thread (minus_one_ptid);
3993 if (ptid_equal (inferior_ptid, minus_one_ptid))
3994 error (_("remote didn't report the current thread in non-stop mode"));
3996 inferior_ptid = current_ptid;
3997 get_offsets (); /* Get text, data & bss offsets. */
3999 /* In non-stop mode, any cached wait status will be stored in
4000 the stop reply queue. */
4001 gdb_assert (wait_status == NULL);
4003 /* Report all signals during attach/startup. */
4004 remote_pass_signals (target, 0, NULL);
4006 /* If there are already stopped threads, mark them stopped and
4007 report their stops before giving the prompt to the user. */
4008 process_initial_stop_replies ();
4010 switch_to_thread (current_ptid);
4012 if (target_can_async_p ())
4016 /* If we connected to a live target, do some additional setup. */
4017 if (target_has_execution)
4019 if (symfile_objfile) /* No use without a symbol-file. */
4020 remote_check_symbols ();
4023 /* Possibly the target has been engaged in a trace run started
4024 previously; find out where things are at. */
4025 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4027 struct uploaded_tp *uploaded_tps = NULL;
4029 if (current_trace_status ()->running)
4030 printf_filtered (_("Trace is already running on the target.\n"));
4032 remote_upload_tracepoints (target, &uploaded_tps);
4034 merge_uploaded_tracepoints (&uploaded_tps);
4037 /* The thread and inferior lists are now synchronized with the
4038 target, our symbols have been relocated, and we're merged the
4039 target's tracepoints with ours. We're done with basic start
4041 rs->starting_up = 0;
4043 /* Maybe breakpoints are global and need to be inserted now. */
4044 if (breakpoints_should_be_inserted_now ())
4045 insert_breakpoints ();
4048 /* Open a connection to a remote debugger.
4049 NAME is the filename used for communication. */
4052 remote_open (const char *name, int from_tty)
4054 remote_open_1 (name, from_tty, &remote_ops, 0);
4057 /* Open a connection to a remote debugger using the extended
4058 remote gdb protocol. NAME is the filename used for communication. */
4061 extended_remote_open (const char *name, int from_tty)
4063 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4066 /* Reset all packets back to "unknown support". Called when opening a
4067 new connection to a remote target. */
4070 reset_all_packet_configs_support (void)
4074 for (i = 0; i < PACKET_MAX; i++)
4075 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4078 /* Initialize all packet configs. */
4081 init_all_packet_configs (void)
4085 for (i = 0; i < PACKET_MAX; i++)
4087 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4088 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4092 /* Symbol look-up. */
4095 remote_check_symbols (void)
4097 struct remote_state *rs = get_remote_state ();
4098 char *msg, *reply, *tmp;
4099 struct bound_minimal_symbol sym;
4101 struct cleanup *old_chain;
4103 /* The remote side has no concept of inferiors that aren't running
4104 yet, it only knows about running processes. If we're connected
4105 but our current inferior is not running, we should not invite the
4106 remote target to request symbol lookups related to its
4107 (unrelated) current process. */
4108 if (!target_has_execution)
4111 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4114 /* Make sure the remote is pointing at the right process. Note
4115 there's no way to select "no process". */
4116 set_general_process ();
4118 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4119 because we need both at the same time. */
4120 msg = xmalloc (get_remote_packet_size ());
4121 old_chain = make_cleanup (xfree, msg);
4123 /* Invite target to request symbol lookups. */
4125 putpkt ("qSymbol::");
4126 getpkt (&rs->buf, &rs->buf_size, 0);
4127 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4130 while (startswith (reply, "qSymbol:"))
4132 struct bound_minimal_symbol sym;
4135 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4137 sym = lookup_minimal_symbol (msg, NULL, NULL);
4138 if (sym.minsym == NULL)
4139 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4142 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4143 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4145 /* If this is a function address, return the start of code
4146 instead of any data function descriptor. */
4147 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4151 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4152 phex_nz (sym_addr, addr_size), &reply[8]);
4156 getpkt (&rs->buf, &rs->buf_size, 0);
4160 do_cleanups (old_chain);
4163 static struct serial *
4164 remote_serial_open (const char *name)
4166 static int udp_warning = 0;
4168 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4169 of in ser-tcp.c, because it is the remote protocol assuming that the
4170 serial connection is reliable and not the serial connection promising
4172 if (!udp_warning && startswith (name, "udp:"))
4174 warning (_("The remote protocol may be unreliable over UDP.\n"
4175 "Some events may be lost, rendering further debugging "
4180 return serial_open (name);
4183 /* Inform the target of our permission settings. The permission flags
4184 work without this, but if the target knows the settings, it can do
4185 a couple things. First, it can add its own check, to catch cases
4186 that somehow manage to get by the permissions checks in target
4187 methods. Second, if the target is wired to disallow particular
4188 settings (for instance, a system in the field that is not set up to
4189 be able to stop at a breakpoint), it can object to any unavailable
4193 remote_set_permissions (struct target_ops *self)
4195 struct remote_state *rs = get_remote_state ();
4197 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4198 "WriteReg:%x;WriteMem:%x;"
4199 "InsertBreak:%x;InsertTrace:%x;"
4200 "InsertFastTrace:%x;Stop:%x",
4201 may_write_registers, may_write_memory,
4202 may_insert_breakpoints, may_insert_tracepoints,
4203 may_insert_fast_tracepoints, may_stop);
4205 getpkt (&rs->buf, &rs->buf_size, 0);
4207 /* If the target didn't like the packet, warn the user. Do not try
4208 to undo the user's settings, that would just be maddening. */
4209 if (strcmp (rs->buf, "OK") != 0)
4210 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4213 /* This type describes each known response to the qSupported
4215 struct protocol_feature
4217 /* The name of this protocol feature. */
4220 /* The default for this protocol feature. */
4221 enum packet_support default_support;
4223 /* The function to call when this feature is reported, or after
4224 qSupported processing if the feature is not supported.
4225 The first argument points to this structure. The second
4226 argument indicates whether the packet requested support be
4227 enabled, disabled, or probed (or the default, if this function
4228 is being called at the end of processing and this feature was
4229 not reported). The third argument may be NULL; if not NULL, it
4230 is a NUL-terminated string taken from the packet following
4231 this feature's name and an equals sign. */
4232 void (*func) (const struct protocol_feature *, enum packet_support,
4235 /* The corresponding packet for this feature. Only used if
4236 FUNC is remote_supported_packet. */
4241 remote_supported_packet (const struct protocol_feature *feature,
4242 enum packet_support support,
4243 const char *argument)
4247 warning (_("Remote qSupported response supplied an unexpected value for"
4248 " \"%s\"."), feature->name);
4252 remote_protocol_packets[feature->packet].support = support;
4256 remote_packet_size (const struct protocol_feature *feature,
4257 enum packet_support support, const char *value)
4259 struct remote_state *rs = get_remote_state ();
4264 if (support != PACKET_ENABLE)
4267 if (value == NULL || *value == '\0')
4269 warning (_("Remote target reported \"%s\" without a size."),
4275 packet_size = strtol (value, &value_end, 16);
4276 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4278 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4279 feature->name, value);
4283 /* Record the new maximum packet size. */
4284 rs->explicit_packet_size = packet_size;
4287 static const struct protocol_feature remote_protocol_features[] = {
4288 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4289 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4290 PACKET_qXfer_auxv },
4291 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4292 PACKET_qXfer_exec_file },
4293 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4294 PACKET_qXfer_features },
4295 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4296 PACKET_qXfer_libraries },
4297 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4298 PACKET_qXfer_libraries_svr4 },
4299 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4300 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4301 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4302 PACKET_qXfer_memory_map },
4303 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4304 PACKET_qXfer_spu_read },
4305 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4306 PACKET_qXfer_spu_write },
4307 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4308 PACKET_qXfer_osdata },
4309 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4310 PACKET_qXfer_threads },
4311 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4312 PACKET_qXfer_traceframe_info },
4313 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4314 PACKET_QPassSignals },
4315 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4316 PACKET_QProgramSignals },
4317 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4318 PACKET_QStartNoAckMode },
4319 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4320 PACKET_multiprocess_feature },
4321 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4322 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4323 PACKET_qXfer_siginfo_read },
4324 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4325 PACKET_qXfer_siginfo_write },
4326 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4327 PACKET_ConditionalTracepoints },
4328 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4329 PACKET_ConditionalBreakpoints },
4330 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4331 PACKET_BreakpointCommands },
4332 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4333 PACKET_FastTracepoints },
4334 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4335 PACKET_StaticTracepoints },
4336 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4337 PACKET_InstallInTrace},
4338 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4339 PACKET_DisconnectedTracing_feature },
4340 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4342 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4344 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4345 PACKET_TracepointSource },
4346 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4348 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4349 PACKET_EnableDisableTracepoints_feature },
4350 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4351 PACKET_qXfer_fdpic },
4352 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4354 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4355 PACKET_QDisableRandomization },
4356 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4357 { "QTBuffer:size", PACKET_DISABLE,
4358 remote_supported_packet, PACKET_QTBuffer_size},
4359 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4360 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4361 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4362 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4363 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4364 PACKET_qXfer_btrace },
4365 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4366 PACKET_qXfer_btrace_conf },
4367 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4368 PACKET_Qbtrace_conf_bts_size },
4369 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4370 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4371 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4372 PACKET_fork_event_feature },
4373 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4374 PACKET_vfork_event_feature },
4375 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4376 PACKET_exec_event_feature },
4377 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4378 PACKET_Qbtrace_conf_pt_size }
4381 static char *remote_support_xml;
4383 /* Register string appended to "xmlRegisters=" in qSupported query. */
4386 register_remote_support_xml (const char *xml)
4388 #if defined(HAVE_LIBEXPAT)
4389 if (remote_support_xml == NULL)
4390 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4393 char *copy = xstrdup (remote_support_xml + 13);
4394 char *p = strtok (copy, ",");
4398 if (strcmp (p, xml) == 0)
4405 while ((p = strtok (NULL, ",")) != NULL);
4408 remote_support_xml = reconcat (remote_support_xml,
4409 remote_support_xml, ",", xml,
4416 remote_query_supported_append (char *msg, const char *append)
4419 return reconcat (msg, msg, ";", append, (char *) NULL);
4421 return xstrdup (append);
4425 remote_query_supported (void)
4427 struct remote_state *rs = get_remote_state ();
4430 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4432 /* The packet support flags are handled differently for this packet
4433 than for most others. We treat an error, a disabled packet, and
4434 an empty response identically: any features which must be reported
4435 to be used will be automatically disabled. An empty buffer
4436 accomplishes this, since that is also the representation for a list
4437 containing no features. */
4440 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4443 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4445 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4446 q = remote_query_supported_append (q, "multiprocess+");
4448 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4449 q = remote_query_supported_append (q, "swbreak+");
4450 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4451 q = remote_query_supported_append (q, "hwbreak+");
4453 if (remote_support_xml)
4454 q = remote_query_supported_append (q, remote_support_xml);
4456 q = remote_query_supported_append (q, "qRelocInsn+");
4460 if (packet_set_cmd_state (PACKET_fork_event_feature)
4461 != AUTO_BOOLEAN_FALSE)
4462 q = remote_query_supported_append (q, "fork-events+");
4463 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4464 != AUTO_BOOLEAN_FALSE)
4465 q = remote_query_supported_append (q, "vfork-events+");
4466 if (packet_set_cmd_state (PACKET_exec_event_feature)
4467 != AUTO_BOOLEAN_FALSE)
4468 q = remote_query_supported_append (q, "exec-events+");
4471 q = reconcat (q, "qSupported:", q, (char *) NULL);
4474 do_cleanups (old_chain);
4476 getpkt (&rs->buf, &rs->buf_size, 0);
4478 /* If an error occured, warn, but do not return - just reset the
4479 buffer to empty and go on to disable features. */
4480 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4483 warning (_("Remote failure reply: %s"), rs->buf);
4488 memset (seen, 0, sizeof (seen));
4493 enum packet_support is_supported;
4494 char *p, *end, *name_end, *value;
4496 /* First separate out this item from the rest of the packet. If
4497 there's another item after this, we overwrite the separator
4498 (terminated strings are much easier to work with). */
4500 end = strchr (p, ';');
4503 end = p + strlen (p);
4513 warning (_("empty item in \"qSupported\" response"));
4518 name_end = strchr (p, '=');
4521 /* This is a name=value entry. */
4522 is_supported = PACKET_ENABLE;
4523 value = name_end + 1;
4532 is_supported = PACKET_ENABLE;
4536 is_supported = PACKET_DISABLE;
4540 is_supported = PACKET_SUPPORT_UNKNOWN;
4544 warning (_("unrecognized item \"%s\" "
4545 "in \"qSupported\" response"), p);
4551 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4552 if (strcmp (remote_protocol_features[i].name, p) == 0)
4554 const struct protocol_feature *feature;
4557 feature = &remote_protocol_features[i];
4558 feature->func (feature, is_supported, value);
4563 /* If we increased the packet size, make sure to increase the global
4564 buffer size also. We delay this until after parsing the entire
4565 qSupported packet, because this is the same buffer we were
4567 if (rs->buf_size < rs->explicit_packet_size)
4569 rs->buf_size = rs->explicit_packet_size;
4570 rs->buf = xrealloc (rs->buf, rs->buf_size);
4573 /* Handle the defaults for unmentioned features. */
4574 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4577 const struct protocol_feature *feature;
4579 feature = &remote_protocol_features[i];
4580 feature->func (feature, feature->default_support, NULL);
4584 /* Remove any of the remote.c targets from target stack. Upper targets depend
4585 on it so remove them first. */
4588 remote_unpush_target (void)
4590 pop_all_targets_above (process_stratum - 1);
4594 remote_open_1 (const char *name, int from_tty,
4595 struct target_ops *target, int extended_p)
4597 struct remote_state *rs = get_remote_state ();
4600 error (_("To open a remote debug connection, you need to specify what\n"
4601 "serial device is attached to the remote system\n"
4602 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4604 /* See FIXME above. */
4605 if (!target_async_permitted)
4606 wait_forever_enabled_p = 1;
4608 /* If we're connected to a running target, target_preopen will kill it.
4609 Ask this question first, before target_preopen has a chance to kill
4611 if (rs->remote_desc != NULL && !have_inferiors ())
4614 && !query (_("Already connected to a remote target. Disconnect? ")))
4615 error (_("Still connected."));
4618 /* Here the possibly existing remote target gets unpushed. */
4619 target_preopen (from_tty);
4621 /* Make sure we send the passed signals list the next time we resume. */
4622 xfree (rs->last_pass_packet);
4623 rs->last_pass_packet = NULL;
4625 /* Make sure we send the program signals list the next time we
4627 xfree (rs->last_program_signals_packet);
4628 rs->last_program_signals_packet = NULL;
4630 remote_fileio_reset ();
4631 reopen_exec_file ();
4634 rs->remote_desc = remote_serial_open (name);
4635 if (!rs->remote_desc)
4636 perror_with_name (name);
4638 if (baud_rate != -1)
4640 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4642 /* The requested speed could not be set. Error out to
4643 top level after closing remote_desc. Take care to
4644 set remote_desc to NULL to avoid closing remote_desc
4646 serial_close (rs->remote_desc);
4647 rs->remote_desc = NULL;
4648 perror_with_name (name);
4652 serial_setparity (rs->remote_desc, serial_parity);
4653 serial_raw (rs->remote_desc);
4655 /* If there is something sitting in the buffer we might take it as a
4656 response to a command, which would be bad. */
4657 serial_flush_input (rs->remote_desc);
4661 puts_filtered ("Remote debugging using ");
4662 puts_filtered (name);
4663 puts_filtered ("\n");
4665 push_target (target); /* Switch to using remote target now. */
4667 /* Register extra event sources in the event loop. */
4668 remote_async_inferior_event_token
4669 = create_async_event_handler (remote_async_inferior_event_handler,
4671 rs->notif_state = remote_notif_state_allocate ();
4673 /* Reset the target state; these things will be queried either by
4674 remote_query_supported or as they are needed. */
4675 reset_all_packet_configs_support ();
4676 rs->cached_wait_status = 0;
4677 rs->explicit_packet_size = 0;
4679 rs->extended = extended_p;
4680 rs->waiting_for_stop_reply = 0;
4681 rs->ctrlc_pending_p = 0;
4683 rs->general_thread = not_sent_ptid;
4684 rs->continue_thread = not_sent_ptid;
4685 rs->remote_traceframe_number = -1;
4687 /* Probe for ability to use "ThreadInfo" query, as required. */
4688 rs->use_threadinfo_query = 1;
4689 rs->use_threadextra_query = 1;
4691 readahead_cache_invalidate ();
4693 if (target_async_permitted)
4695 /* With this target we start out by owning the terminal. */
4696 remote_async_terminal_ours_p = 1;
4698 /* FIXME: cagney/1999-09-23: During the initial connection it is
4699 assumed that the target is already ready and able to respond to
4700 requests. Unfortunately remote_start_remote() eventually calls
4701 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4702 around this. Eventually a mechanism that allows
4703 wait_for_inferior() to expect/get timeouts will be
4705 wait_forever_enabled_p = 0;
4708 /* First delete any symbols previously loaded from shared libraries. */
4709 no_shared_libraries (NULL, 0);
4712 init_thread_list ();
4714 /* Start the remote connection. If error() or QUIT, discard this
4715 target (we'd otherwise be in an inconsistent state) and then
4716 propogate the error on up the exception chain. This ensures that
4717 the caller doesn't stumble along blindly assuming that the
4718 function succeeded. The CLI doesn't have this problem but other
4719 UI's, such as MI do.
4721 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4722 this function should return an error indication letting the
4723 caller restore the previous state. Unfortunately the command
4724 ``target remote'' is directly wired to this function making that
4725 impossible. On a positive note, the CLI side of this problem has
4726 been fixed - the function set_cmd_context() makes it possible for
4727 all the ``target ....'' commands to share a common callback
4728 function. See cli-dump.c. */
4733 remote_start_remote (from_tty, target, extended_p);
4735 CATCH (ex, RETURN_MASK_ALL)
4737 /* Pop the partially set up target - unless something else did
4738 already before throwing the exception. */
4739 if (rs->remote_desc != NULL)
4740 remote_unpush_target ();
4741 if (target_async_permitted)
4742 wait_forever_enabled_p = 1;
4743 throw_exception (ex);
4748 remote_btrace_reset ();
4750 if (target_async_permitted)
4751 wait_forever_enabled_p = 1;
4754 /* Detach the specified process. */
4757 remote_detach_pid (int pid)
4759 struct remote_state *rs = get_remote_state ();
4761 if (remote_multi_process_p (rs))
4762 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4764 strcpy (rs->buf, "D");
4767 getpkt (&rs->buf, &rs->buf_size, 0);
4769 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4771 else if (rs->buf[0] == '\0')
4772 error (_("Remote doesn't know how to detach"));
4774 error (_("Can't detach process."));
4777 /* This detaches a program to which we previously attached, using
4778 inferior_ptid to identify the process. After this is done, GDB
4779 can be used to debug some other program. We better not have left
4780 any breakpoints in the target program or it'll die when it hits
4784 remote_detach_1 (const char *args, int from_tty)
4786 int pid = ptid_get_pid (inferior_ptid);
4787 struct remote_state *rs = get_remote_state ();
4788 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4792 error (_("Argument given to \"detach\" when remotely debugging."));
4794 if (!target_has_execution)
4795 error (_("No process to detach from."));
4799 char *exec_file = get_exec_file (0);
4800 if (exec_file == NULL)
4802 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4803 target_pid_to_str (pid_to_ptid (pid)));
4804 gdb_flush (gdb_stdout);
4807 /* Tell the remote target to detach. */
4808 remote_detach_pid (pid);
4810 if (from_tty && !rs->extended)
4811 puts_filtered (_("Ending remote debugging.\n"));
4813 /* Check to see if we are detaching a fork parent. Note that if we
4814 are detaching a fork child, tp == NULL. */
4815 is_fork_parent = (tp != NULL
4816 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4818 /* If doing detach-on-fork, we don't mourn, because that will delete
4819 breakpoints that should be available for the followed inferior. */
4820 if (!is_fork_parent)
4821 target_mourn_inferior ();
4824 inferior_ptid = null_ptid;
4825 detach_inferior (pid);
4830 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4832 remote_detach_1 (args, from_tty);
4836 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4838 remote_detach_1 (args, from_tty);
4841 /* Target follow-fork function for remote targets. On entry, and
4842 at return, the current inferior is the fork parent.
4844 Note that although this is currently only used for extended-remote,
4845 it is named remote_follow_fork in anticipation of using it for the
4846 remote target as well. */
4849 remote_follow_fork (struct target_ops *ops, int follow_child,
4852 struct remote_state *rs = get_remote_state ();
4853 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
4855 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4856 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
4858 /* When following the parent and detaching the child, we detach
4859 the child here. For the case of following the child and
4860 detaching the parent, the detach is done in the target-
4861 independent follow fork code in infrun.c. We can't use
4862 target_detach when detaching an unfollowed child because
4863 the client side doesn't know anything about the child. */
4864 if (detach_fork && !follow_child)
4866 /* Detach the fork child. */
4870 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4871 child_pid = ptid_get_pid (child_ptid);
4873 remote_detach_pid (child_pid);
4874 detach_inferior (child_pid);
4880 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
4881 in the program space of the new inferior. On entry and at return the
4882 current inferior is the exec'ing inferior. INF is the new exec'd
4883 inferior, which may be the same as the exec'ing inferior unless
4884 follow-exec-mode is "new". */
4887 remote_follow_exec (struct target_ops *ops,
4888 struct inferior *inf, char *execd_pathname)
4890 /* We know that this is a target file name, so if it has the "target:"
4891 prefix we strip it off before saving it in the program space. */
4892 if (is_target_filename (execd_pathname))
4893 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
4895 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
4898 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4901 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4904 error (_("Argument given to \"disconnect\" when remotely debugging."));
4906 /* Make sure we unpush even the extended remote targets; mourn
4907 won't do it. So call remote_mourn directly instead of
4908 target_mourn_inferior. */
4909 remote_mourn (target);
4912 puts_filtered ("Ending remote debugging.\n");
4915 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4916 be chatty about it. */
4919 extended_remote_attach (struct target_ops *target, const char *args,
4922 struct remote_state *rs = get_remote_state ();
4924 char *wait_status = NULL;
4926 pid = parse_pid_to_attach (args);
4928 /* Remote PID can be freely equal to getpid, do not check it here the same
4929 way as in other targets. */
4931 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4932 error (_("This target does not support attaching to a process"));
4936 char *exec_file = get_exec_file (0);
4939 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4940 target_pid_to_str (pid_to_ptid (pid)));
4942 printf_unfiltered (_("Attaching to %s\n"),
4943 target_pid_to_str (pid_to_ptid (pid)));
4945 gdb_flush (gdb_stdout);
4948 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4950 getpkt (&rs->buf, &rs->buf_size, 0);
4952 switch (packet_ok (rs->buf,
4953 &remote_protocol_packets[PACKET_vAttach]))
4958 /* Save the reply for later. */
4959 wait_status = alloca (strlen (rs->buf) + 1);
4960 strcpy (wait_status, rs->buf);
4962 else if (strcmp (rs->buf, "OK") != 0)
4963 error (_("Attaching to %s failed with: %s"),
4964 target_pid_to_str (pid_to_ptid (pid)),
4967 case PACKET_UNKNOWN:
4968 error (_("This target does not support attaching to a process"));
4970 error (_("Attaching to %s failed"),
4971 target_pid_to_str (pid_to_ptid (pid)));
4974 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
4976 inferior_ptid = pid_to_ptid (pid);
4980 struct thread_info *thread;
4982 /* Get list of threads. */
4983 remote_update_thread_list (target);
4985 thread = first_thread_of_process (pid);
4987 inferior_ptid = thread->ptid;
4989 inferior_ptid = pid_to_ptid (pid);
4991 /* Invalidate our notion of the remote current thread. */
4992 record_currthread (rs, minus_one_ptid);
4996 /* Now, if we have thread information, update inferior_ptid. */
4997 inferior_ptid = remote_current_thread (inferior_ptid);
4999 /* Add the main thread to the thread list. */
5000 add_thread_silent (inferior_ptid);
5003 /* Next, if the target can specify a description, read it. We do
5004 this before anything involving memory or registers. */
5005 target_find_description ();
5009 /* Use the previously fetched status. */
5010 gdb_assert (wait_status != NULL);
5012 if (target_can_async_p ())
5014 struct notif_event *reply
5015 = remote_notif_parse (¬if_client_stop, wait_status);
5017 push_stop_reply ((struct stop_reply *) reply);
5023 gdb_assert (wait_status != NULL);
5024 strcpy (rs->buf, wait_status);
5025 rs->cached_wait_status = 1;
5029 gdb_assert (wait_status == NULL);
5032 /* Implementation of the to_post_attach method. */
5035 extended_remote_post_attach (struct target_ops *ops, int pid)
5037 /* In certain cases GDB might not have had the chance to start
5038 symbol lookup up until now. This could happen if the debugged
5039 binary is not using shared libraries, the vsyscall page is not
5040 present (on Linux) and the binary itself hadn't changed since the
5041 debugging process was started. */
5042 if (symfile_objfile != NULL)
5043 remote_check_symbols();
5047 /* Check for the availability of vCont. This function should also check
5051 remote_vcont_probe (struct remote_state *rs)
5055 strcpy (rs->buf, "vCont?");
5057 getpkt (&rs->buf, &rs->buf_size, 0);
5060 /* Make sure that the features we assume are supported. */
5061 if (startswith (buf, "vCont"))
5064 int support_s, support_S, support_c, support_C;
5070 rs->supports_vCont.t = 0;
5071 rs->supports_vCont.r = 0;
5072 while (p && *p == ';')
5075 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5077 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5079 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5081 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5083 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5084 rs->supports_vCont.t = 1;
5085 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5086 rs->supports_vCont.r = 1;
5088 p = strchr (p, ';');
5091 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
5092 BUF will make packet_ok disable the packet. */
5093 if (!support_s || !support_S || !support_c || !support_C)
5097 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5100 /* Helper function for building "vCont" resumptions. Write a
5101 resumption to P. ENDP points to one-passed-the-end of the buffer
5102 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5103 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5104 resumed thread should be single-stepped and/or signalled. If PTID
5105 equals minus_one_ptid, then all threads are resumed; if PTID
5106 represents a process, then all threads of the process are resumed;
5107 the thread to be stepped and/or signalled is given in the global
5111 append_resumption (char *p, char *endp,
5112 ptid_t ptid, int step, enum gdb_signal siggnal)
5114 struct remote_state *rs = get_remote_state ();
5116 if (step && siggnal != GDB_SIGNAL_0)
5117 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5119 /* GDB is willing to range step. */
5120 && use_range_stepping
5121 /* Target supports range stepping. */
5122 && rs->supports_vCont.r
5123 /* We don't currently support range stepping multiple
5124 threads with a wildcard (though the protocol allows it,
5125 so stubs shouldn't make an active effort to forbid
5127 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5129 struct thread_info *tp;
5131 if (ptid_equal (ptid, minus_one_ptid))
5133 /* If we don't know about the target thread's tid, then
5134 we're resuming magic_null_ptid (see caller). */
5135 tp = find_thread_ptid (magic_null_ptid);
5138 tp = find_thread_ptid (ptid);
5139 gdb_assert (tp != NULL);
5141 if (tp->control.may_range_step)
5143 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5145 p += xsnprintf (p, endp - p, ";r%s,%s",
5146 phex_nz (tp->control.step_range_start,
5148 phex_nz (tp->control.step_range_end,
5152 p += xsnprintf (p, endp - p, ";s");
5155 p += xsnprintf (p, endp - p, ";s");
5156 else if (siggnal != GDB_SIGNAL_0)
5157 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5159 p += xsnprintf (p, endp - p, ";c");
5161 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5165 /* All (-1) threads of process. */
5166 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5168 p += xsnprintf (p, endp - p, ":");
5169 p = write_ptid (p, endp, nptid);
5171 else if (!ptid_equal (ptid, minus_one_ptid))
5173 p += xsnprintf (p, endp - p, ":");
5174 p = write_ptid (p, endp, ptid);
5180 /* Append a vCont continue-with-signal action for threads that have a
5181 non-zero stop signal. */
5184 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5186 struct thread_info *thread;
5188 ALL_NON_EXITED_THREADS (thread)
5189 if (ptid_match (thread->ptid, ptid)
5190 && !ptid_equal (inferior_ptid, thread->ptid)
5191 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5193 p = append_resumption (p, endp, thread->ptid,
5194 0, thread->suspend.stop_signal);
5195 thread->suspend.stop_signal = GDB_SIGNAL_0;
5201 /* Resume the remote inferior by using a "vCont" packet. The thread
5202 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5203 resumed thread should be single-stepped and/or signalled. If PTID
5204 equals minus_one_ptid, then all threads are resumed; the thread to
5205 be stepped and/or signalled is given in the global INFERIOR_PTID.
5206 This function returns non-zero iff it resumes the inferior.
5208 This function issues a strict subset of all possible vCont commands at the
5212 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5214 struct remote_state *rs = get_remote_state ();
5218 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5219 remote_vcont_probe (rs);
5221 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5225 endp = rs->buf + get_remote_packet_size ();
5227 /* If we could generate a wider range of packets, we'd have to worry
5228 about overflowing BUF. Should there be a generic
5229 "multi-part-packet" packet? */
5231 p += xsnprintf (p, endp - p, "vCont");
5233 if (ptid_equal (ptid, magic_null_ptid))
5235 /* MAGIC_NULL_PTID means that we don't have any active threads,
5236 so we don't have any TID numbers the inferior will
5237 understand. Make sure to only send forms that do not specify
5239 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5241 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5243 /* Resume all threads (of all processes, or of a single
5244 process), with preference for INFERIOR_PTID. This assumes
5245 inferior_ptid belongs to the set of all threads we are about
5247 if (step || siggnal != GDB_SIGNAL_0)
5249 /* Step inferior_ptid, with or without signal. */
5250 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5253 /* Also pass down any pending signaled resumption for other
5254 threads not the current. */
5255 p = append_pending_thread_resumptions (p, endp, ptid);
5257 /* And continue others without a signal. */
5258 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5262 /* Scheduler locking; resume only PTID. */
5263 append_resumption (p, endp, ptid, step, siggnal);
5266 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5271 /* In non-stop, the stub replies to vCont with "OK". The stop
5272 reply will be reported asynchronously by means of a `%Stop'
5274 getpkt (&rs->buf, &rs->buf_size, 0);
5275 if (strcmp (rs->buf, "OK") != 0)
5276 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5282 /* Tell the remote machine to resume. */
5285 remote_resume (struct target_ops *ops,
5286 ptid_t ptid, int step, enum gdb_signal siggnal)
5288 struct remote_state *rs = get_remote_state ();
5291 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5292 (explained in remote-notif.c:handle_notification) so
5293 remote_notif_process is not called. We need find a place where
5294 it is safe to start a 'vNotif' sequence. It is good to do it
5295 before resuming inferior, because inferior was stopped and no RSP
5296 traffic at that moment. */
5298 remote_notif_process (rs->notif_state, ¬if_client_stop);
5300 rs->last_sent_signal = siggnal;
5301 rs->last_sent_step = step;
5303 /* The vCont packet doesn't need to specify threads via Hc. */
5304 /* No reverse support (yet) for vCont. */
5305 if (execution_direction != EXEC_REVERSE)
5306 if (remote_vcont_resume (ptid, step, siggnal))
5309 /* All other supported resume packets do use Hc, so set the continue
5311 if (ptid_equal (ptid, minus_one_ptid))
5312 set_continue_thread (any_thread_ptid);
5314 set_continue_thread (ptid);
5317 if (execution_direction == EXEC_REVERSE)
5319 /* We don't pass signals to the target in reverse exec mode. */
5320 if (info_verbose && siggnal != GDB_SIGNAL_0)
5321 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5324 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5325 error (_("Remote reverse-step not supported."));
5326 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5327 error (_("Remote reverse-continue not supported."));
5329 strcpy (buf, step ? "bs" : "bc");
5331 else if (siggnal != GDB_SIGNAL_0)
5333 buf[0] = step ? 'S' : 'C';
5334 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5335 buf[2] = tohex (((int) siggnal) & 0xf);
5339 strcpy (buf, step ? "s" : "c");
5344 /* We are about to start executing the inferior, let's register it
5345 with the event loop. NOTE: this is the one place where all the
5346 execution commands end up. We could alternatively do this in each
5347 of the execution commands in infcmd.c. */
5348 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5349 into infcmd.c in order to allow inferior function calls to work
5350 NOT asynchronously. */
5351 if (target_can_async_p ())
5354 /* We've just told the target to resume. The remote server will
5355 wait for the inferior to stop, and then send a stop reply. In
5356 the mean time, we can't start another command/query ourselves
5357 because the stub wouldn't be ready to process it. This applies
5358 only to the base all-stop protocol, however. In non-stop (which
5359 only supports vCont), the stub replies with an "OK", and is
5360 immediate able to process further serial input. */
5362 rs->waiting_for_stop_reply = 1;
5366 /* Set up the signal handler for SIGINT, while the target is
5367 executing, ovewriting the 'regular' SIGINT signal handler. */
5369 async_initialize_sigint_signal_handler (void)
5371 signal (SIGINT, async_handle_remote_sigint);
5374 /* Signal handler for SIGINT, while the target is executing. */
5376 async_handle_remote_sigint (int sig)
5378 signal (sig, async_handle_remote_sigint_twice);
5379 /* Note we need to go through gdb_call_async_signal_handler in order
5380 to wake up the event loop on Windows. */
5381 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5384 /* Signal handler for SIGINT, installed after SIGINT has already been
5385 sent once. It will take effect the second time that the user sends
5388 async_handle_remote_sigint_twice (int sig)
5390 signal (sig, async_handle_remote_sigint);
5391 /* See note in async_handle_remote_sigint. */
5392 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5395 /* Implementation of to_check_pending_interrupt. */
5398 remote_check_pending_interrupt (struct target_ops *self)
5400 struct async_signal_handler *token = async_sigint_remote_twice_token;
5402 if (async_signal_handler_is_marked (token))
5404 clear_async_signal_handler (token);
5405 call_async_signal_handler (token);
5409 /* Perform the real interruption of the target execution, in response
5412 async_remote_interrupt (gdb_client_data arg)
5415 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5417 target_stop (inferior_ptid);
5420 /* Perform interrupt, if the first attempt did not succeed. Just give
5421 up on the target alltogether. */
5423 async_remote_interrupt_twice (gdb_client_data arg)
5426 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5431 /* Reinstall the usual SIGINT handlers, after the target has
5434 async_cleanup_sigint_signal_handler (void *dummy)
5436 signal (SIGINT, handle_sigint);
5439 /* Send ^C to target to halt it. Target will respond, and send us a
5441 static void (*ofunc) (int);
5443 /* The command line interface's interrupt routine. This function is installed
5444 as a signal handler for SIGINT. The first time a user requests an
5445 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5446 response from the target (it didn't stop when the user requested it),
5447 we ask the user if he'd like to detach from the target. */
5450 sync_remote_interrupt (int signo)
5452 /* If this doesn't work, try more severe steps. */
5453 signal (signo, sync_remote_interrupt_twice);
5455 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5458 /* The user typed ^C twice. */
5461 sync_remote_interrupt_twice (int signo)
5463 signal (signo, ofunc);
5464 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5465 signal (signo, sync_remote_interrupt);
5468 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5469 thread, all threads of a remote process, or all threads of all
5473 remote_stop_ns (ptid_t ptid)
5475 struct remote_state *rs = get_remote_state ();
5477 char *endp = rs->buf + get_remote_packet_size ();
5479 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5480 remote_vcont_probe (rs);
5482 if (!rs->supports_vCont.t)
5483 error (_("Remote server does not support stopping threads"));
5485 if (ptid_equal (ptid, minus_one_ptid)
5486 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5487 p += xsnprintf (p, endp - p, "vCont;t");
5492 p += xsnprintf (p, endp - p, "vCont;t:");
5494 if (ptid_is_pid (ptid))
5495 /* All (-1) threads of process. */
5496 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5499 /* Small optimization: if we already have a stop reply for
5500 this thread, no use in telling the stub we want this
5502 if (peek_stop_reply (ptid))
5508 write_ptid (p, endp, nptid);
5511 /* In non-stop, we get an immediate OK reply. The stop reply will
5512 come in asynchronously by notification. */
5514 getpkt (&rs->buf, &rs->buf_size, 0);
5515 if (strcmp (rs->buf, "OK") != 0)
5516 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5519 /* All-stop version of target_interrupt. Sends a break or a ^C to
5520 interrupt the remote target. It is undefined which thread of which
5521 process reports the interrupt. */
5524 remote_interrupt_as (ptid_t ptid)
5526 struct remote_state *rs = get_remote_state ();
5528 rs->ctrlc_pending_p = 1;
5530 /* If the inferior is stopped already, but the core didn't know
5531 about it yet, just ignore the request. The cached wait status
5532 will be collected in remote_wait. */
5533 if (rs->cached_wait_status)
5536 /* Send interrupt_sequence to remote target. */
5537 send_interrupt_sequence ();
5540 /* Implement the to_stop function for the remote targets. */
5543 remote_stop (struct target_ops *self, ptid_t ptid)
5546 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5549 remote_stop_ns (ptid);
5552 /* We don't currently have a way to transparently pause the
5553 remote target in all-stop mode. Interrupt it instead. */
5554 remote_interrupt_as (ptid);
5558 /* Implement the to_interrupt function for the remote targets. */
5561 remote_interrupt (struct target_ops *self, ptid_t ptid)
5564 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5568 /* We don't currently have a way to ^C the remote target in
5569 non-stop mode. Stop it (with no signal) instead. */
5570 remote_stop_ns (ptid);
5573 remote_interrupt_as (ptid);
5576 /* Ask the user what to do when an interrupt is received. */
5579 interrupt_query (void)
5581 struct remote_state *rs = get_remote_state ();
5582 struct cleanup *old_chain;
5584 old_chain = make_cleanup_restore_target_terminal ();
5585 target_terminal_ours ();
5587 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5589 if (query (_("The target is not responding to interrupt requests.\n"
5590 "Stop debugging it? ")))
5592 remote_unpush_target ();
5593 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5598 if (query (_("Interrupted while waiting for the program.\n"
5599 "Give up waiting? ")))
5603 do_cleanups (old_chain);
5606 /* Enable/disable target terminal ownership. Most targets can use
5607 terminal groups to control terminal ownership. Remote targets are
5608 different in that explicit transfer of ownership to/from GDB/target
5612 remote_terminal_inferior (struct target_ops *self)
5614 if (!target_async_permitted)
5615 /* Nothing to do. */
5618 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5619 idempotent. The event-loop GDB talking to an asynchronous target
5620 with a synchronous command calls this function from both
5621 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5622 transfer the terminal to the target when it shouldn't this guard
5624 if (!remote_async_terminal_ours_p)
5626 delete_file_handler (input_fd);
5627 remote_async_terminal_ours_p = 0;
5628 async_initialize_sigint_signal_handler ();
5629 /* NOTE: At this point we could also register our selves as the
5630 recipient of all input. Any characters typed could then be
5631 passed on down to the target. */
5635 remote_terminal_ours (struct target_ops *self)
5637 if (!target_async_permitted)
5638 /* Nothing to do. */
5641 /* See FIXME in remote_terminal_inferior. */
5642 if (remote_async_terminal_ours_p)
5644 async_cleanup_sigint_signal_handler (NULL);
5645 add_file_handler (input_fd, stdin_event_handler, 0);
5646 remote_async_terminal_ours_p = 1;
5650 remote_console_output (char *msg)
5654 for (p = msg; p[0] && p[1]; p += 2)
5657 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5661 fputs_unfiltered (tb, gdb_stdtarg);
5663 gdb_flush (gdb_stdtarg);
5666 typedef struct cached_reg
5669 gdb_byte data[MAX_REGISTER_SIZE];
5672 DEF_VEC_O(cached_reg_t);
5674 typedef struct stop_reply
5676 struct notif_event base;
5678 /* The identifier of the thread about this event */
5681 /* The remote state this event is associated with. When the remote
5682 connection, represented by a remote_state object, is closed,
5683 all the associated stop_reply events should be released. */
5684 struct remote_state *rs;
5686 struct target_waitstatus ws;
5688 /* Expedited registers. This makes remote debugging a bit more
5689 efficient for those targets that provide critical registers as
5690 part of their normal status mechanism (as another roundtrip to
5691 fetch them is avoided). */
5692 VEC(cached_reg_t) *regcache;
5694 enum target_stop_reason stop_reason;
5696 CORE_ADDR watch_data_address;
5701 DECLARE_QUEUE_P (stop_reply_p);
5702 DEFINE_QUEUE_P (stop_reply_p);
5703 /* The list of already fetched and acknowledged stop events. This
5704 queue is used for notification Stop, and other notifications
5705 don't need queue for their events, because the notification events
5706 of Stop can't be consumed immediately, so that events should be
5707 queued first, and be consumed by remote_wait_{ns,as} one per
5708 time. Other notifications can consume their events immediately,
5709 so queue is not needed for them. */
5710 static QUEUE (stop_reply_p) *stop_reply_queue;
5713 stop_reply_xfree (struct stop_reply *r)
5715 notif_event_xfree ((struct notif_event *) r);
5718 /* Return the length of the stop reply queue. */
5721 stop_reply_queue_length (void)
5723 return QUEUE_length (stop_reply_p, stop_reply_queue);
5727 remote_notif_stop_parse (struct notif_client *self, char *buf,
5728 struct notif_event *event)
5730 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5734 remote_notif_stop_ack (struct notif_client *self, char *buf,
5735 struct notif_event *event)
5737 struct stop_reply *stop_reply = (struct stop_reply *) event;
5740 putpkt ((char *) self->ack_command);
5742 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5743 /* We got an unknown stop reply. */
5744 error (_("Unknown stop reply"));
5746 push_stop_reply (stop_reply);
5750 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5752 /* We can't get pending events in remote_notif_process for
5753 notification stop, and we have to do this in remote_wait_ns
5754 instead. If we fetch all queued events from stub, remote stub
5755 may exit and we have no chance to process them back in
5757 mark_async_event_handler (remote_async_inferior_event_token);
5762 stop_reply_dtr (struct notif_event *event)
5764 struct stop_reply *r = (struct stop_reply *) event;
5766 VEC_free (cached_reg_t, r->regcache);
5769 static struct notif_event *
5770 remote_notif_stop_alloc_reply (void)
5772 /* We cast to a pointer to the "base class". */
5773 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5775 r->dtr = stop_reply_dtr;
5780 /* A client of notification Stop. */
5782 struct notif_client notif_client_stop =
5786 remote_notif_stop_parse,
5787 remote_notif_stop_ack,
5788 remote_notif_stop_can_get_pending_events,
5789 remote_notif_stop_alloc_reply,
5793 /* A parameter to pass data in and out. */
5795 struct queue_iter_param
5798 struct stop_reply *output;
5801 /* Determine if THREAD is a pending fork parent thread. ARG contains
5802 the pid of the process that owns the threads we want to check, or
5803 -1 if we want to check all threads. */
5806 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5809 if (ws->kind == TARGET_WAITKIND_FORKED
5810 || ws->kind == TARGET_WAITKIND_VFORKED)
5812 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5819 /* Check whether EVENT is a fork event, and if it is, remove the
5820 fork child from the context list passed in DATA. */
5823 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5824 QUEUE_ITER (stop_reply_p) *iter,
5828 struct queue_iter_param *param = data;
5829 struct threads_listing_context *context = param->input;
5831 if (event->ws.kind == TARGET_WAITKIND_FORKED
5832 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5834 threads_listing_context_remove (&event->ws, context);
5840 /* If CONTEXT contains any fork child threads that have not been
5841 reported yet, remove them from the CONTEXT list. If such a
5842 thread exists it is because we are stopped at a fork catchpoint
5843 and have not yet called follow_fork, which will set up the
5844 host-side data structures for the new process. */
5847 remove_new_fork_children (struct threads_listing_context *context)
5849 struct thread_info * thread;
5851 struct notif_client *notif = ¬if_client_stop;
5852 struct queue_iter_param param;
5854 /* For any threads stopped at a fork event, remove the corresponding
5855 fork child threads from the CONTEXT list. */
5856 ALL_NON_EXITED_THREADS (thread)
5858 struct target_waitstatus *ws = &thread->pending_follow;
5860 if (is_pending_fork_parent (ws, pid, thread->ptid))
5862 threads_listing_context_remove (ws, context);
5866 /* Check for any pending fork events (not reported or processed yet)
5867 in process PID and remove those fork child threads from the
5868 CONTEXT list as well. */
5869 remote_notif_get_pending_events (notif);
5870 param.input = context;
5871 param.output = NULL;
5872 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5873 remove_child_of_pending_fork, ¶m);
5876 /* Remove stop replies in the queue if its pid is equal to the given
5880 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5881 QUEUE_ITER (stop_reply_p) *iter,
5885 struct queue_iter_param *param = data;
5886 struct inferior *inf = param->input;
5888 if (ptid_get_pid (event->ptid) == inf->pid)
5890 stop_reply_xfree (event);
5891 QUEUE_remove_elem (stop_reply_p, q, iter);
5897 /* Discard all pending stop replies of inferior INF. */
5900 discard_pending_stop_replies (struct inferior *inf)
5903 struct queue_iter_param param;
5904 struct stop_reply *reply;
5905 struct remote_state *rs = get_remote_state ();
5906 struct remote_notif_state *rns = rs->notif_state;
5908 /* This function can be notified when an inferior exists. When the
5909 target is not remote, the notification state is NULL. */
5910 if (rs->remote_desc == NULL)
5913 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5915 /* Discard the in-flight notification. */
5916 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5918 stop_reply_xfree (reply);
5919 rns->pending_event[notif_client_stop.id] = NULL;
5923 param.output = NULL;
5924 /* Discard the stop replies we have already pulled with
5926 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5927 remove_stop_reply_for_inferior, ¶m);
5930 /* If its remote state is equal to the given remote state,
5931 remove EVENT from the stop reply queue. */
5934 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5935 QUEUE_ITER (stop_reply_p) *iter,
5939 struct queue_iter_param *param = data;
5940 struct remote_state *rs = param->input;
5942 if (event->rs == rs)
5944 stop_reply_xfree (event);
5945 QUEUE_remove_elem (stop_reply_p, q, iter);
5951 /* Discard the stop replies for RS in stop_reply_queue. */
5954 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5956 struct queue_iter_param param;
5959 param.output = NULL;
5960 /* Discard the stop replies we have already pulled with
5962 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5963 remove_stop_reply_of_remote_state, ¶m);
5966 /* A parameter to pass data in and out. */
5969 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5970 QUEUE_ITER (stop_reply_p) *iter,
5974 struct queue_iter_param *param = data;
5975 ptid_t *ptid = param->input;
5977 if (ptid_match (event->ptid, *ptid))
5979 param->output = event;
5980 QUEUE_remove_elem (stop_reply_p, q, iter);
5987 /* Remove the first reply in 'stop_reply_queue' which matches
5990 static struct stop_reply *
5991 remote_notif_remove_queued_reply (ptid_t ptid)
5993 struct queue_iter_param param;
5995 param.input = &ptid;
5996 param.output = NULL;
5998 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5999 remote_notif_remove_once_on_match, ¶m);
6001 fprintf_unfiltered (gdb_stdlog,
6002 "notif: discard queued event: 'Stop' in %s\n",
6003 target_pid_to_str (ptid));
6005 return param.output;
6008 /* Look for a queued stop reply belonging to PTID. If one is found,
6009 remove it from the queue, and return it. Returns NULL if none is
6010 found. If there are still queued events left to process, tell the
6011 event loop to get back to target_wait soon. */
6013 static struct stop_reply *
6014 queued_stop_reply (ptid_t ptid)
6016 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6018 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6019 /* There's still at least an event left. */
6020 mark_async_event_handler (remote_async_inferior_event_token);
6025 /* Push a fully parsed stop reply in the stop reply queue. Since we
6026 know that we now have at least one queued event left to pass to the
6027 core side, tell the event loop to get back to target_wait soon. */
6030 push_stop_reply (struct stop_reply *new_event)
6032 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6035 fprintf_unfiltered (gdb_stdlog,
6036 "notif: push 'Stop' %s to queue %d\n",
6037 target_pid_to_str (new_event->ptid),
6038 QUEUE_length (stop_reply_p,
6041 mark_async_event_handler (remote_async_inferior_event_token);
6045 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6046 QUEUE_ITER (stop_reply_p) *iter,
6047 struct stop_reply *event,
6050 ptid_t *ptid = data;
6052 return !(ptid_equal (*ptid, event->ptid)
6053 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6056 /* Returns true if we have a stop reply for PTID. */
6059 peek_stop_reply (ptid_t ptid)
6061 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6062 stop_reply_match_ptid_and_ws, &ptid);
6065 /* Skip PACKET until the next semi-colon (or end of string). */
6068 skip_to_semicolon (char *p)
6070 while (*p != '\0' && *p != ';')
6075 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6076 starting with P and ending with PEND matches PREFIX. */
6079 strprefix (const char *p, const char *pend, const char *prefix)
6081 for ( ; p < pend; p++, prefix++)
6084 return *prefix == '\0';
6087 /* Parse the stop reply in BUF. Either the function succeeds, and the
6088 result is stored in EVENT, or throws an error. */
6091 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6093 struct remote_arch_state *rsa = get_remote_arch_state ();
6098 event->ptid = null_ptid;
6099 event->rs = get_remote_state ();
6100 event->ws.kind = TARGET_WAITKIND_IGNORE;
6101 event->ws.value.integer = 0;
6102 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6103 event->regcache = NULL;
6108 case 'T': /* Status with PC, SP, FP, ... */
6109 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6110 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6112 n... = register number
6113 r... = register contents
6116 p = &buf[3]; /* after Txx */
6122 p1 = strchr (p, ':');
6124 error (_("Malformed packet(a) (missing colon): %s\n\
6128 error (_("Malformed packet(a) (missing register number): %s\n\
6132 /* Some "registers" are actually extended stop information.
6133 Note if you're adding a new entry here: GDB 7.9 and
6134 earlier assume that all register "numbers" that start
6135 with an hex digit are real register numbers. Make sure
6136 the server only sends such a packet if it knows the
6137 client understands it. */
6139 if (strprefix (p, p1, "thread"))
6140 event->ptid = read_ptid (++p1, &p);
6141 else if (strprefix (p, p1, "watch")
6142 || strprefix (p, p1, "rwatch")
6143 || strprefix (p, p1, "awatch"))
6145 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6146 p = unpack_varlen_hex (++p1, &addr);
6147 event->watch_data_address = (CORE_ADDR) addr;
6149 else if (strprefix (p, p1, "swbreak"))
6151 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6153 /* Make sure the stub doesn't forget to indicate support
6155 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6156 error (_("Unexpected swbreak stop reason"));
6158 /* The value part is documented as "must be empty",
6159 though we ignore it, in case we ever decide to make
6160 use of it in a backward compatible way. */
6161 p = skip_to_semicolon (p1 + 1);
6163 else if (strprefix (p, p1, "hwbreak"))
6165 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6167 /* Make sure the stub doesn't forget to indicate support
6169 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6170 error (_("Unexpected hwbreak stop reason"));
6173 p = skip_to_semicolon (p1 + 1);
6175 else if (strprefix (p, p1, "library"))
6177 event->ws.kind = TARGET_WAITKIND_LOADED;
6178 p = skip_to_semicolon (p1 + 1);
6180 else if (strprefix (p, p1, "replaylog"))
6182 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6183 /* p1 will indicate "begin" or "end", but it makes
6184 no difference for now, so ignore it. */
6185 p = skip_to_semicolon (p1 + 1);
6187 else if (strprefix (p, p1, "core"))
6191 p = unpack_varlen_hex (++p1, &c);
6194 else if (strprefix (p, p1, "fork"))
6196 event->ws.value.related_pid = read_ptid (++p1, &p);
6197 event->ws.kind = TARGET_WAITKIND_FORKED;
6199 else if (strprefix (p, p1, "vfork"))
6201 event->ws.value.related_pid = read_ptid (++p1, &p);
6202 event->ws.kind = TARGET_WAITKIND_VFORKED;
6204 else if (strprefix (p, p1, "vforkdone"))
6206 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6207 p = skip_to_semicolon (p1 + 1);
6209 else if (strncmp (p, "exec", p1 - p) == 0)
6212 char pathname[PATH_MAX];
6215 /* Determine the length of the execd pathname. */
6216 p = unpack_varlen_hex (++p1, &ignored);
6217 pathlen = (p - p1) / 2;
6219 /* Save the pathname for event reporting and for
6220 the next run command. */
6221 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6222 pathname[pathlen] = '\0';
6224 /* This is freed during event handling. */
6225 event->ws.value.execd_pathname = xstrdup (pathname);
6226 event->ws.kind = TARGET_WAITKIND_EXECD;
6228 /* Skip the registers included in this packet, since
6229 they may be for an architecture different from the
6230 one used by the original program. */
6240 p = skip_to_semicolon (p1 + 1);
6245 /* Maybe a real ``P'' register number. */
6246 p_temp = unpack_varlen_hex (p, &pnum);
6247 /* If the first invalid character is the colon, we got a
6248 register number. Otherwise, it's an unknown stop
6252 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6253 cached_reg_t cached_reg;
6256 error (_("Remote sent bad register number %s: %s\n\
6258 hex_string (pnum), p, buf);
6260 cached_reg.num = reg->regnum;
6263 fieldsize = hex2bin (p, cached_reg.data,
6264 register_size (target_gdbarch (),
6267 if (fieldsize < register_size (target_gdbarch (),
6269 warning (_("Remote reply is too short: %s"), buf);
6271 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6275 /* Not a number. Silently skip unknown optional
6277 p = skip_to_semicolon (p1 + 1);
6282 error (_("Remote register badly formatted: %s\nhere: %s"),
6287 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6291 case 'S': /* Old style status, just signal only. */
6295 event->ws.kind = TARGET_WAITKIND_STOPPED;
6296 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6297 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6298 event->ws.value.sig = (enum gdb_signal) sig;
6300 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6303 case 'W': /* Target exited. */
6310 /* GDB used to accept only 2 hex chars here. Stubs should
6311 only send more if they detect GDB supports multi-process
6313 p = unpack_varlen_hex (&buf[1], &value);
6317 /* The remote process exited. */
6318 event->ws.kind = TARGET_WAITKIND_EXITED;
6319 event->ws.value.integer = value;
6323 /* The remote process exited with a signal. */
6324 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6325 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6326 event->ws.value.sig = (enum gdb_signal) value;
6328 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6331 /* If no process is specified, assume inferior_ptid. */
6332 pid = ptid_get_pid (inferior_ptid);
6341 else if (startswith (p, "process:"))
6345 p += sizeof ("process:") - 1;
6346 unpack_varlen_hex (p, &upid);
6350 error (_("unknown stop reply packet: %s"), buf);
6353 error (_("unknown stop reply packet: %s"), buf);
6354 event->ptid = pid_to_ptid (pid);
6359 if (non_stop && ptid_equal (event->ptid, null_ptid))
6360 error (_("No process or thread specified in stop reply: %s"), buf);
6363 /* When the stub wants to tell GDB about a new notification reply, it
6364 sends a notification (%Stop, for example). Those can come it at
6365 any time, hence, we have to make sure that any pending
6366 putpkt/getpkt sequence we're making is finished, before querying
6367 the stub for more events with the corresponding ack command
6368 (vStopped, for example). E.g., if we started a vStopped sequence
6369 immediately upon receiving the notification, something like this
6377 1.6) <-- (registers reply to step #1.3)
6379 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6382 To solve this, whenever we parse a %Stop notification successfully,
6383 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6384 doing whatever we were doing:
6390 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6391 2.5) <-- (registers reply to step #2.3)
6393 Eventualy after step #2.5, we return to the event loop, which
6394 notices there's an event on the
6395 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6396 associated callback --- the function below. At this point, we're
6397 always safe to start a vStopped sequence. :
6400 2.7) <-- T05 thread:2
6406 remote_notif_get_pending_events (struct notif_client *nc)
6408 struct remote_state *rs = get_remote_state ();
6410 if (rs->notif_state->pending_event[nc->id] != NULL)
6413 fprintf_unfiltered (gdb_stdlog,
6414 "notif: process: '%s' ack pending event\n",
6418 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6419 rs->notif_state->pending_event[nc->id] = NULL;
6423 getpkt (&rs->buf, &rs->buf_size, 0);
6424 if (strcmp (rs->buf, "OK") == 0)
6427 remote_notif_ack (nc, rs->buf);
6433 fprintf_unfiltered (gdb_stdlog,
6434 "notif: process: '%s' no pending reply\n",
6439 /* Called when it is decided that STOP_REPLY holds the info of the
6440 event that is to be returned to the core. This function always
6441 destroys STOP_REPLY. */
6444 process_stop_reply (struct stop_reply *stop_reply,
6445 struct target_waitstatus *status)
6449 *status = stop_reply->ws;
6450 ptid = stop_reply->ptid;
6452 /* If no thread/process was reported by the stub, assume the current
6454 if (ptid_equal (ptid, null_ptid))
6455 ptid = inferior_ptid;
6457 if (status->kind != TARGET_WAITKIND_EXITED
6458 && status->kind != TARGET_WAITKIND_SIGNALLED)
6460 struct remote_state *rs = get_remote_state ();
6462 /* Expedited registers. */
6463 if (stop_reply->regcache)
6465 struct regcache *regcache
6466 = get_thread_arch_regcache (ptid, target_gdbarch ());
6471 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6473 regcache_raw_supply (regcache, reg->num, reg->data);
6474 VEC_free (cached_reg_t, stop_reply->regcache);
6477 rs->stop_reason = stop_reply->stop_reason;
6478 rs->remote_watch_data_address = stop_reply->watch_data_address;
6480 remote_notice_new_inferior (ptid, 0);
6481 demand_private_info (ptid)->core = stop_reply->core;
6484 stop_reply_xfree (stop_reply);
6488 /* The non-stop mode version of target_wait. */
6491 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6493 struct remote_state *rs = get_remote_state ();
6494 struct stop_reply *stop_reply;
6498 /* If in non-stop mode, get out of getpkt even if a
6499 notification is received. */
6501 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6502 0 /* forever */, &is_notif);
6505 if (ret != -1 && !is_notif)
6508 case 'E': /* Error of some sort. */
6509 /* We're out of sync with the target now. Did it continue
6510 or not? We can't tell which thread it was in non-stop,
6511 so just ignore this. */
6512 warning (_("Remote failure reply: %s"), rs->buf);
6514 case 'O': /* Console output. */
6515 remote_console_output (rs->buf + 1);
6518 warning (_("Invalid remote reply: %s"), rs->buf);
6522 /* Acknowledge a pending stop reply that may have arrived in the
6524 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6525 remote_notif_get_pending_events (¬if_client_stop);
6527 /* If indeed we noticed a stop reply, we're done. */
6528 stop_reply = queued_stop_reply (ptid);
6529 if (stop_reply != NULL)
6530 return process_stop_reply (stop_reply, status);
6532 /* Still no event. If we're just polling for an event, then
6533 return to the event loop. */
6534 if (options & TARGET_WNOHANG)
6536 status->kind = TARGET_WAITKIND_IGNORE;
6537 return minus_one_ptid;
6540 /* Otherwise do a blocking wait. */
6541 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6542 1 /* forever */, &is_notif);
6546 /* Wait until the remote machine stops, then return, storing status in
6547 STATUS just as `wait' would. */
6550 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6552 struct remote_state *rs = get_remote_state ();
6553 ptid_t event_ptid = null_ptid;
6555 struct stop_reply *stop_reply;
6559 status->kind = TARGET_WAITKIND_IGNORE;
6560 status->value.integer = 0;
6562 stop_reply = queued_stop_reply (ptid);
6563 if (stop_reply != NULL)
6564 return process_stop_reply (stop_reply, status);
6566 if (rs->cached_wait_status)
6567 /* Use the cached wait status, but only once. */
6568 rs->cached_wait_status = 0;
6573 int forever = ((options & TARGET_WNOHANG) == 0
6574 && wait_forever_enabled_p);
6576 if (!rs->waiting_for_stop_reply)
6578 status->kind = TARGET_WAITKIND_NO_RESUMED;
6579 return minus_one_ptid;
6582 if (!target_is_async_p ())
6584 ofunc = signal (SIGINT, sync_remote_interrupt);
6585 /* If the user hit C-c before this packet, or between packets,
6586 pretend that it was hit right here. */
6587 if (check_quit_flag ())
6590 sync_remote_interrupt (SIGINT);
6594 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6595 _never_ wait for ever -> test on target_is_async_p().
6596 However, before we do that we need to ensure that the caller
6597 knows how to take the target into/out of async mode. */
6598 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6599 forever, &is_notif);
6601 if (!target_is_async_p ())
6602 signal (SIGINT, ofunc);
6604 /* GDB gets a notification. Return to core as this event is
6606 if (ret != -1 && is_notif)
6607 return minus_one_ptid;
6609 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6610 return minus_one_ptid;
6615 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6617 /* We got something. */
6618 rs->waiting_for_stop_reply = 0;
6620 /* Assume that the target has acknowledged Ctrl-C unless we receive
6621 an 'F' or 'O' packet. */
6622 if (buf[0] != 'F' && buf[0] != 'O')
6623 rs->ctrlc_pending_p = 0;
6627 case 'E': /* Error of some sort. */
6628 /* We're out of sync with the target now. Did it continue or
6629 not? Not is more likely, so report a stop. */
6630 warning (_("Remote failure reply: %s"), buf);
6631 status->kind = TARGET_WAITKIND_STOPPED;
6632 status->value.sig = GDB_SIGNAL_0;
6634 case 'F': /* File-I/O request. */
6635 remote_fileio_request (buf, rs->ctrlc_pending_p);
6636 rs->ctrlc_pending_p = 0;
6638 case 'T': case 'S': case 'X': case 'W':
6640 struct stop_reply *stop_reply
6641 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6644 event_ptid = process_stop_reply (stop_reply, status);
6647 case 'O': /* Console output. */
6648 remote_console_output (buf + 1);
6650 /* The target didn't really stop; keep waiting. */
6651 rs->waiting_for_stop_reply = 1;
6655 if (rs->last_sent_signal != GDB_SIGNAL_0)
6657 /* Zero length reply means that we tried 'S' or 'C' and the
6658 remote system doesn't support it. */
6659 target_terminal_ours_for_output ();
6661 ("Can't send signals to this remote system. %s not sent.\n",
6662 gdb_signal_to_name (rs->last_sent_signal));
6663 rs->last_sent_signal = GDB_SIGNAL_0;
6664 target_terminal_inferior ();
6666 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6667 putpkt ((char *) buf);
6669 /* We just told the target to resume, so a stop reply is in
6671 rs->waiting_for_stop_reply = 1;
6674 /* else fallthrough */
6676 warning (_("Invalid remote reply: %s"), buf);
6678 rs->waiting_for_stop_reply = 1;
6682 if (status->kind == TARGET_WAITKIND_IGNORE)
6684 /* Nothing interesting happened. If we're doing a non-blocking
6685 poll, we're done. Otherwise, go back to waiting. */
6686 if (options & TARGET_WNOHANG)
6687 return minus_one_ptid;
6691 else if (status->kind != TARGET_WAITKIND_EXITED
6692 && status->kind != TARGET_WAITKIND_SIGNALLED)
6694 if (!ptid_equal (event_ptid, null_ptid))
6695 record_currthread (rs, event_ptid);
6697 event_ptid = inferior_ptid;
6700 /* A process exit. Invalidate our notion of current thread. */
6701 record_currthread (rs, minus_one_ptid);
6706 /* Wait until the remote machine stops, then return, storing status in
6707 STATUS just as `wait' would. */
6710 remote_wait (struct target_ops *ops,
6711 ptid_t ptid, struct target_waitstatus *status, int options)
6716 event_ptid = remote_wait_ns (ptid, status, options);
6718 event_ptid = remote_wait_as (ptid, status, options);
6720 if (target_is_async_p ())
6722 /* If there are are events left in the queue tell the event loop
6724 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6725 mark_async_event_handler (remote_async_inferior_event_token);
6731 /* Fetch a single register using a 'p' packet. */
6734 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6736 struct remote_state *rs = get_remote_state ();
6738 char regp[MAX_REGISTER_SIZE];
6741 if (packet_support (PACKET_p) == PACKET_DISABLE)
6744 if (reg->pnum == -1)
6749 p += hexnumstr (p, reg->pnum);
6752 getpkt (&rs->buf, &rs->buf_size, 0);
6756 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6760 case PACKET_UNKNOWN:
6763 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6764 gdbarch_register_name (get_regcache_arch (regcache),
6769 /* If this register is unfetchable, tell the regcache. */
6772 regcache_raw_supply (regcache, reg->regnum, NULL);
6776 /* Otherwise, parse and supply the value. */
6782 error (_("fetch_register_using_p: early buf termination"));
6784 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6787 regcache_raw_supply (regcache, reg->regnum, regp);
6791 /* Fetch the registers included in the target's 'g' packet. */
6794 send_g_packet (void)
6796 struct remote_state *rs = get_remote_state ();
6799 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6800 remote_send (&rs->buf, &rs->buf_size);
6802 /* We can get out of synch in various cases. If the first character
6803 in the buffer is not a hex character, assume that has happened
6804 and try to fetch another packet to read. */
6805 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6806 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6807 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6808 && rs->buf[0] != 'x') /* New: unavailable register value. */
6811 fprintf_unfiltered (gdb_stdlog,
6812 "Bad register packet; fetching a new packet\n");
6813 getpkt (&rs->buf, &rs->buf_size, 0);
6816 buf_len = strlen (rs->buf);
6818 /* Sanity check the received packet. */
6819 if (buf_len % 2 != 0)
6820 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6826 process_g_packet (struct regcache *regcache)
6828 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6829 struct remote_state *rs = get_remote_state ();
6830 struct remote_arch_state *rsa = get_remote_arch_state ();
6835 buf_len = strlen (rs->buf);
6837 /* Further sanity checks, with knowledge of the architecture. */
6838 if (buf_len > 2 * rsa->sizeof_g_packet)
6839 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6841 /* Save the size of the packet sent to us by the target. It is used
6842 as a heuristic when determining the max size of packets that the
6843 target can safely receive. */
6844 if (rsa->actual_register_packet_size == 0)
6845 rsa->actual_register_packet_size = buf_len;
6847 /* If this is smaller than we guessed the 'g' packet would be,
6848 update our records. A 'g' reply that doesn't include a register's
6849 value implies either that the register is not available, or that
6850 the 'p' packet must be used. */
6851 if (buf_len < 2 * rsa->sizeof_g_packet)
6853 rsa->sizeof_g_packet = buf_len / 2;
6855 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6857 if (rsa->regs[i].pnum == -1)
6860 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6861 rsa->regs[i].in_g_packet = 0;
6863 rsa->regs[i].in_g_packet = 1;
6867 regs = alloca (rsa->sizeof_g_packet);
6869 /* Unimplemented registers read as all bits zero. */
6870 memset (regs, 0, rsa->sizeof_g_packet);
6872 /* Reply describes registers byte by byte, each byte encoded as two
6873 hex characters. Suck them all up, then supply them to the
6874 register cacheing/storage mechanism. */
6877 for (i = 0; i < rsa->sizeof_g_packet; i++)
6879 if (p[0] == 0 || p[1] == 0)
6880 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6881 internal_error (__FILE__, __LINE__,
6882 _("unexpected end of 'g' packet reply"));
6884 if (p[0] == 'x' && p[1] == 'x')
6885 regs[i] = 0; /* 'x' */
6887 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6891 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6893 struct packet_reg *r = &rsa->regs[i];
6897 if (r->offset * 2 >= strlen (rs->buf))
6898 /* This shouldn't happen - we adjusted in_g_packet above. */
6899 internal_error (__FILE__, __LINE__,
6900 _("unexpected end of 'g' packet reply"));
6901 else if (rs->buf[r->offset * 2] == 'x')
6903 gdb_assert (r->offset * 2 < strlen (rs->buf));
6904 /* The register isn't available, mark it as such (at
6905 the same time setting the value to zero). */
6906 regcache_raw_supply (regcache, r->regnum, NULL);
6909 regcache_raw_supply (regcache, r->regnum,
6916 fetch_registers_using_g (struct regcache *regcache)
6919 process_g_packet (regcache);
6922 /* Make the remote selected traceframe match GDB's selected
6926 set_remote_traceframe (void)
6929 struct remote_state *rs = get_remote_state ();
6931 if (rs->remote_traceframe_number == get_traceframe_number ())
6934 /* Avoid recursion, remote_trace_find calls us again. */
6935 rs->remote_traceframe_number = get_traceframe_number ();
6937 newnum = target_trace_find (tfind_number,
6938 get_traceframe_number (), 0, 0, NULL);
6940 /* Should not happen. If it does, all bets are off. */
6941 if (newnum != get_traceframe_number ())
6942 warning (_("could not set remote traceframe"));
6946 remote_fetch_registers (struct target_ops *ops,
6947 struct regcache *regcache, int regnum)
6949 struct remote_arch_state *rsa = get_remote_arch_state ();
6952 set_remote_traceframe ();
6953 set_general_thread (inferior_ptid);
6957 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6959 gdb_assert (reg != NULL);
6961 /* If this register might be in the 'g' packet, try that first -
6962 we are likely to read more than one register. If this is the
6963 first 'g' packet, we might be overly optimistic about its
6964 contents, so fall back to 'p'. */
6965 if (reg->in_g_packet)
6967 fetch_registers_using_g (regcache);
6968 if (reg->in_g_packet)
6972 if (fetch_register_using_p (regcache, reg))
6975 /* This register is not available. */
6976 regcache_raw_supply (regcache, reg->regnum, NULL);
6981 fetch_registers_using_g (regcache);
6983 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6984 if (!rsa->regs[i].in_g_packet)
6985 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6987 /* This register is not available. */
6988 regcache_raw_supply (regcache, i, NULL);
6992 /* Prepare to store registers. Since we may send them all (using a
6993 'G' request), we have to read out the ones we don't want to change
6997 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6999 struct remote_arch_state *rsa = get_remote_arch_state ();
7001 gdb_byte buf[MAX_REGISTER_SIZE];
7003 /* Make sure the entire registers array is valid. */
7004 switch (packet_support (PACKET_P))
7006 case PACKET_DISABLE:
7007 case PACKET_SUPPORT_UNKNOWN:
7008 /* Make sure all the necessary registers are cached. */
7009 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7010 if (rsa->regs[i].in_g_packet)
7011 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7018 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7019 packet was not recognized. */
7022 store_register_using_P (const struct regcache *regcache,
7023 struct packet_reg *reg)
7025 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7026 struct remote_state *rs = get_remote_state ();
7027 /* Try storing a single register. */
7028 char *buf = rs->buf;
7029 gdb_byte regp[MAX_REGISTER_SIZE];
7032 if (packet_support (PACKET_P) == PACKET_DISABLE)
7035 if (reg->pnum == -1)
7038 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7039 p = buf + strlen (buf);
7040 regcache_raw_collect (regcache, reg->regnum, regp);
7041 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7043 getpkt (&rs->buf, &rs->buf_size, 0);
7045 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7050 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7051 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7052 case PACKET_UNKNOWN:
7055 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7059 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7060 contents of the register cache buffer. FIXME: ignores errors. */
7063 store_registers_using_G (const struct regcache *regcache)
7065 struct remote_state *rs = get_remote_state ();
7066 struct remote_arch_state *rsa = get_remote_arch_state ();
7070 /* Extract all the registers in the regcache copying them into a
7075 regs = alloca (rsa->sizeof_g_packet);
7076 memset (regs, 0, rsa->sizeof_g_packet);
7077 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7079 struct packet_reg *r = &rsa->regs[i];
7082 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7086 /* Command describes registers byte by byte,
7087 each byte encoded as two hex characters. */
7090 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7092 bin2hex (regs, p, rsa->sizeof_g_packet);
7094 getpkt (&rs->buf, &rs->buf_size, 0);
7095 if (packet_check_result (rs->buf) == PACKET_ERROR)
7096 error (_("Could not write registers; remote failure reply '%s'"),
7100 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7101 of the register cache buffer. FIXME: ignores errors. */
7104 remote_store_registers (struct target_ops *ops,
7105 struct regcache *regcache, int regnum)
7107 struct remote_arch_state *rsa = get_remote_arch_state ();
7110 set_remote_traceframe ();
7111 set_general_thread (inferior_ptid);
7115 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7117 gdb_assert (reg != NULL);
7119 /* Always prefer to store registers using the 'P' packet if
7120 possible; we often change only a small number of registers.
7121 Sometimes we change a larger number; we'd need help from a
7122 higher layer to know to use 'G'. */
7123 if (store_register_using_P (regcache, reg))
7126 /* For now, don't complain if we have no way to write the
7127 register. GDB loses track of unavailable registers too
7128 easily. Some day, this may be an error. We don't have
7129 any way to read the register, either... */
7130 if (!reg->in_g_packet)
7133 store_registers_using_G (regcache);
7137 store_registers_using_G (regcache);
7139 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7140 if (!rsa->regs[i].in_g_packet)
7141 if (!store_register_using_P (regcache, &rsa->regs[i]))
7142 /* See above for why we do not issue an error here. */
7147 /* Return the number of hex digits in num. */
7150 hexnumlen (ULONGEST num)
7154 for (i = 0; num != 0; i++)
7160 /* Set BUF to the minimum number of hex digits representing NUM. */
7163 hexnumstr (char *buf, ULONGEST num)
7165 int len = hexnumlen (num);
7167 return hexnumnstr (buf, num, len);
7171 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7174 hexnumnstr (char *buf, ULONGEST num, int width)
7180 for (i = width - 1; i >= 0; i--)
7182 buf[i] = "0123456789abcdef"[(num & 0xf)];
7189 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7192 remote_address_masked (CORE_ADDR addr)
7194 unsigned int address_size = remote_address_size;
7196 /* If "remoteaddresssize" was not set, default to target address size. */
7198 address_size = gdbarch_addr_bit (target_gdbarch ());
7200 if (address_size > 0
7201 && address_size < (sizeof (ULONGEST) * 8))
7203 /* Only create a mask when that mask can safely be constructed
7204 in a ULONGEST variable. */
7207 mask = (mask << address_size) - 1;
7213 /* Determine whether the remote target supports binary downloading.
7214 This is accomplished by sending a no-op memory write of zero length
7215 to the target at the specified address. It does not suffice to send
7216 the whole packet, since many stubs strip the eighth bit and
7217 subsequently compute a wrong checksum, which causes real havoc with
7220 NOTE: This can still lose if the serial line is not eight-bit
7221 clean. In cases like this, the user should clear "remote
7225 check_binary_download (CORE_ADDR addr)
7227 struct remote_state *rs = get_remote_state ();
7229 switch (packet_support (PACKET_X))
7231 case PACKET_DISABLE:
7235 case PACKET_SUPPORT_UNKNOWN:
7241 p += hexnumstr (p, (ULONGEST) addr);
7243 p += hexnumstr (p, (ULONGEST) 0);
7247 putpkt_binary (rs->buf, (int) (p - rs->buf));
7248 getpkt (&rs->buf, &rs->buf_size, 0);
7250 if (rs->buf[0] == '\0')
7253 fprintf_unfiltered (gdb_stdlog,
7254 "binary downloading NOT "
7255 "supported by target\n");
7256 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7261 fprintf_unfiltered (gdb_stdlog,
7262 "binary downloading supported by target\n");
7263 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7270 /* Helper function to resize the payload in order to try to get a good
7271 alignment. We try to write an amount of data such that the next write will
7272 start on an address aligned on REMOTE_ALIGN_WRITES. */
7275 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7277 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7280 /* Write memory data directly to the remote machine.
7281 This does not inform the data cache; the data cache uses this.
7282 HEADER is the starting part of the packet.
7283 MEMADDR is the address in the remote memory space.
7284 MYADDR is the address of the buffer in our space.
7285 LEN_UNITS is the number of addressable units to write.
7286 UNIT_SIZE is the length in bytes of an addressable unit.
7287 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7288 should send data as binary ('X'), or hex-encoded ('M').
7290 The function creates packet of the form
7291 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7293 where encoding of <DATA> is terminated by PACKET_FORMAT.
7295 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7298 Return the transferred status, error or OK (an
7299 'enum target_xfer_status' value). Save the number of addressable units
7300 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7302 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7303 exchange between gdb and the stub could look like (?? in place of the
7309 -> $M1000,3:eeeeffffeeee#??
7313 <- eeeeffffeeeedddd */
7315 static enum target_xfer_status
7316 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7317 const gdb_byte *myaddr, ULONGEST len_units,
7318 int unit_size, ULONGEST *xfered_len_units,
7319 char packet_format, int use_length)
7321 struct remote_state *rs = get_remote_state ();
7327 int payload_capacity_bytes;
7328 int payload_length_bytes;
7330 if (packet_format != 'X' && packet_format != 'M')
7331 internal_error (__FILE__, __LINE__,
7332 _("remote_write_bytes_aux: bad packet format"));
7335 return TARGET_XFER_EOF;
7337 payload_capacity_bytes = get_memory_write_packet_size ();
7339 /* The packet buffer will be large enough for the payload;
7340 get_memory_packet_size ensures this. */
7343 /* Compute the size of the actual payload by subtracting out the
7344 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7346 payload_capacity_bytes -= strlen ("$,:#NN");
7348 /* The comma won't be used. */
7349 payload_capacity_bytes += 1;
7350 payload_capacity_bytes -= strlen (header);
7351 payload_capacity_bytes -= hexnumlen (memaddr);
7353 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7355 strcat (rs->buf, header);
7356 p = rs->buf + strlen (header);
7358 /* Compute a best guess of the number of bytes actually transfered. */
7359 if (packet_format == 'X')
7361 /* Best guess at number of bytes that will fit. */
7362 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7364 payload_capacity_bytes -= hexnumlen (todo_units);
7365 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7369 /* Number of bytes that will fit. */
7370 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7372 payload_capacity_bytes -= hexnumlen (todo_units);
7373 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7376 if (todo_units <= 0)
7377 internal_error (__FILE__, __LINE__,
7378 _("minimum packet size too small to write data"));
7380 /* If we already need another packet, then try to align the end
7381 of this packet to a useful boundary. */
7382 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7383 todo_units = align_for_efficient_write (todo_units, memaddr);
7385 /* Append "<memaddr>". */
7386 memaddr = remote_address_masked (memaddr);
7387 p += hexnumstr (p, (ULONGEST) memaddr);
7394 /* Append the length and retain its location and size. It may need to be
7395 adjusted once the packet body has been created. */
7397 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7405 /* Append the packet body. */
7406 if (packet_format == 'X')
7408 /* Binary mode. Send target system values byte by byte, in
7409 increasing byte addresses. Only escape certain critical
7411 payload_length_bytes =
7412 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7413 &units_written, payload_capacity_bytes);
7415 /* If not all TODO units fit, then we'll need another packet. Make
7416 a second try to keep the end of the packet aligned. Don't do
7417 this if the packet is tiny. */
7418 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7422 new_todo_units = align_for_efficient_write (units_written, memaddr);
7424 if (new_todo_units != units_written)
7425 payload_length_bytes =
7426 remote_escape_output (myaddr, new_todo_units, unit_size,
7427 (gdb_byte *) p, &units_written,
7428 payload_capacity_bytes);
7431 p += payload_length_bytes;
7432 if (use_length && units_written < todo_units)
7434 /* Escape chars have filled up the buffer prematurely,
7435 and we have actually sent fewer units than planned.
7436 Fix-up the length field of the packet. Use the same
7437 number of characters as before. */
7438 plen += hexnumnstr (plen, (ULONGEST) units_written,
7440 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7445 /* Normal mode: Send target system values byte by byte, in
7446 increasing byte addresses. Each byte is encoded as a two hex
7448 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7449 units_written = todo_units;
7452 putpkt_binary (rs->buf, (int) (p - rs->buf));
7453 getpkt (&rs->buf, &rs->buf_size, 0);
7455 if (rs->buf[0] == 'E')
7456 return TARGET_XFER_E_IO;
7458 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7459 send fewer units than we'd planned. */
7460 *xfered_len_units = (ULONGEST) units_written;
7461 return TARGET_XFER_OK;
7464 /* Write memory data directly to the remote machine.
7465 This does not inform the data cache; the data cache uses this.
7466 MEMADDR is the address in the remote memory space.
7467 MYADDR is the address of the buffer in our space.
7468 LEN is the number of bytes.
7470 Return the transferred status, error or OK (an
7471 'enum target_xfer_status' value). Save the number of bytes
7472 transferred in *XFERED_LEN. Only transfer a single packet. */
7474 static enum target_xfer_status
7475 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7476 int unit_size, ULONGEST *xfered_len)
7478 char *packet_format = 0;
7480 /* Check whether the target supports binary download. */
7481 check_binary_download (memaddr);
7483 switch (packet_support (PACKET_X))
7486 packet_format = "X";
7488 case PACKET_DISABLE:
7489 packet_format = "M";
7491 case PACKET_SUPPORT_UNKNOWN:
7492 internal_error (__FILE__, __LINE__,
7493 _("remote_write_bytes: bad internal state"));
7495 internal_error (__FILE__, __LINE__, _("bad switch"));
7498 return remote_write_bytes_aux (packet_format,
7499 memaddr, myaddr, len, unit_size, xfered_len,
7500 packet_format[0], 1);
7503 /* Read memory data directly from the remote machine.
7504 This does not use the data cache; the data cache uses this.
7505 MEMADDR is the address in the remote memory space.
7506 MYADDR is the address of the buffer in our space.
7507 LEN_UNITS is the number of addressable memory units to read..
7508 UNIT_SIZE is the length in bytes of an addressable unit.
7510 Return the transferred status, error or OK (an
7511 'enum target_xfer_status' value). Save the number of bytes
7512 transferred in *XFERED_LEN_UNITS.
7514 See the comment of remote_write_bytes_aux for an example of
7515 memory read/write exchange between gdb and the stub. */
7517 static enum target_xfer_status
7518 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7519 int unit_size, ULONGEST *xfered_len_units)
7521 struct remote_state *rs = get_remote_state ();
7522 int buf_size_bytes; /* Max size of packet output buffer. */
7527 buf_size_bytes = get_memory_read_packet_size ();
7528 /* The packet buffer will be large enough for the payload;
7529 get_memory_packet_size ensures this. */
7531 /* Number of units that will fit. */
7532 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7534 /* Construct "m"<memaddr>","<len>". */
7535 memaddr = remote_address_masked (memaddr);
7538 p += hexnumstr (p, (ULONGEST) memaddr);
7540 p += hexnumstr (p, (ULONGEST) todo_units);
7543 getpkt (&rs->buf, &rs->buf_size, 0);
7544 if (rs->buf[0] == 'E'
7545 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7546 && rs->buf[3] == '\0')
7547 return TARGET_XFER_E_IO;
7548 /* Reply describes memory byte by byte, each byte encoded as two hex
7551 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7552 /* Return what we have. Let higher layers handle partial reads. */
7553 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7554 return TARGET_XFER_OK;
7557 /* Using the set of read-only target sections of remote, read live
7560 For interface/parameters/return description see target.h,
7563 static enum target_xfer_status
7564 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7565 ULONGEST memaddr, ULONGEST len,
7566 int unit_size, ULONGEST *xfered_len)
7568 struct target_section *secp;
7569 struct target_section_table *table;
7571 secp = target_section_by_addr (ops, memaddr);
7573 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7574 secp->the_bfd_section)
7577 struct target_section *p;
7578 ULONGEST memend = memaddr + len;
7580 table = target_get_section_table (ops);
7582 for (p = table->sections; p < table->sections_end; p++)
7584 if (memaddr >= p->addr)
7586 if (memend <= p->endaddr)
7588 /* Entire transfer is within this section. */
7589 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7592 else if (memaddr >= p->endaddr)
7594 /* This section ends before the transfer starts. */
7599 /* This section overlaps the transfer. Just do half. */
7600 len = p->endaddr - memaddr;
7601 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7608 return TARGET_XFER_EOF;
7611 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7612 first if the requested memory is unavailable in traceframe.
7613 Otherwise, fall back to remote_read_bytes_1. */
7615 static enum target_xfer_status
7616 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7617 gdb_byte *myaddr, ULONGEST len, int unit_size,
7618 ULONGEST *xfered_len)
7621 return TARGET_XFER_EOF;
7623 if (get_traceframe_number () != -1)
7625 VEC(mem_range_s) *available;
7627 /* If we fail to get the set of available memory, then the
7628 target does not support querying traceframe info, and so we
7629 attempt reading from the traceframe anyway (assuming the
7630 target implements the old QTro packet then). */
7631 if (traceframe_available_memory (&available, memaddr, len))
7633 struct cleanup *old_chain;
7635 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7637 if (VEC_empty (mem_range_s, available)
7638 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7640 enum target_xfer_status res;
7642 /* Don't read into the traceframe's available
7644 if (!VEC_empty (mem_range_s, available))
7646 LONGEST oldlen = len;
7648 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7649 gdb_assert (len <= oldlen);
7652 do_cleanups (old_chain);
7654 /* This goes through the topmost target again. */
7655 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7656 len, unit_size, xfered_len);
7657 if (res == TARGET_XFER_OK)
7658 return TARGET_XFER_OK;
7661 /* No use trying further, we know some memory starting
7662 at MEMADDR isn't available. */
7664 return TARGET_XFER_UNAVAILABLE;
7668 /* Don't try to read more than how much is available, in
7669 case the target implements the deprecated QTro packet to
7670 cater for older GDBs (the target's knowledge of read-only
7671 sections may be outdated by now). */
7672 len = VEC_index (mem_range_s, available, 0)->length;
7674 do_cleanups (old_chain);
7678 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7683 /* Sends a packet with content determined by the printf format string
7684 FORMAT and the remaining arguments, then gets the reply. Returns
7685 whether the packet was a success, a failure, or unknown. */
7687 static enum packet_result remote_send_printf (const char *format, ...)
7688 ATTRIBUTE_PRINTF (1, 2);
7690 static enum packet_result
7691 remote_send_printf (const char *format, ...)
7693 struct remote_state *rs = get_remote_state ();
7694 int max_size = get_remote_packet_size ();
7697 va_start (ap, format);
7700 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7701 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7703 if (putpkt (rs->buf) < 0)
7704 error (_("Communication problem with target."));
7707 getpkt (&rs->buf, &rs->buf_size, 0);
7709 return packet_check_result (rs->buf);
7713 restore_remote_timeout (void *p)
7715 int value = *(int *)p;
7717 remote_timeout = value;
7720 /* Flash writing can take quite some time. We'll set
7721 effectively infinite timeout for flash operations.
7722 In future, we'll need to decide on a better approach. */
7723 static const int remote_flash_timeout = 1000;
7726 remote_flash_erase (struct target_ops *ops,
7727 ULONGEST address, LONGEST length)
7729 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7730 int saved_remote_timeout = remote_timeout;
7731 enum packet_result ret;
7732 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7733 &saved_remote_timeout);
7735 remote_timeout = remote_flash_timeout;
7737 ret = remote_send_printf ("vFlashErase:%s,%s",
7738 phex (address, addr_size),
7742 case PACKET_UNKNOWN:
7743 error (_("Remote target does not support flash erase"));
7745 error (_("Error erasing flash with vFlashErase packet"));
7750 do_cleanups (back_to);
7753 static enum target_xfer_status
7754 remote_flash_write (struct target_ops *ops, ULONGEST address,
7755 ULONGEST length, ULONGEST *xfered_len,
7756 const gdb_byte *data)
7758 int saved_remote_timeout = remote_timeout;
7759 enum target_xfer_status ret;
7760 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7761 &saved_remote_timeout);
7763 remote_timeout = remote_flash_timeout;
7764 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7766 do_cleanups (back_to);
7772 remote_flash_done (struct target_ops *ops)
7774 int saved_remote_timeout = remote_timeout;
7776 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7777 &saved_remote_timeout);
7779 remote_timeout = remote_flash_timeout;
7780 ret = remote_send_printf ("vFlashDone");
7781 do_cleanups (back_to);
7785 case PACKET_UNKNOWN:
7786 error (_("Remote target does not support vFlashDone"));
7788 error (_("Error finishing flash operation"));
7795 remote_files_info (struct target_ops *ignore)
7797 puts_filtered ("Debugging a target over a serial line.\n");
7800 /* Stuff for dealing with the packets which are part of this protocol.
7801 See comment at top of file for details. */
7803 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7804 error to higher layers. Called when a serial error is detected.
7805 The exception message is STRING, followed by a colon and a blank,
7806 the system error message for errno at function entry and final dot
7807 for output compatibility with throw_perror_with_name. */
7810 unpush_and_perror (const char *string)
7812 int saved_errno = errno;
7814 remote_unpush_target ();
7815 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7816 safe_strerror (saved_errno));
7819 /* Read a single character from the remote end. */
7822 readchar (int timeout)
7825 struct remote_state *rs = get_remote_state ();
7827 ch = serial_readchar (rs->remote_desc, timeout);
7832 switch ((enum serial_rc) ch)
7835 remote_unpush_target ();
7836 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7839 unpush_and_perror (_("Remote communication error. "
7840 "Target disconnected."));
7842 case SERIAL_TIMEOUT:
7848 /* Wrapper for serial_write that closes the target and throws if
7852 remote_serial_write (const char *str, int len)
7854 struct remote_state *rs = get_remote_state ();
7856 if (serial_write (rs->remote_desc, str, len))
7858 unpush_and_perror (_("Remote communication error. "
7859 "Target disconnected."));
7863 /* Send the command in *BUF to the remote machine, and read the reply
7864 into *BUF. Report an error if we get an error reply. Resize
7865 *BUF using xrealloc if necessary to hold the result, and update
7869 remote_send (char **buf,
7873 getpkt (buf, sizeof_buf, 0);
7875 if ((*buf)[0] == 'E')
7876 error (_("Remote failure reply: %s"), *buf);
7879 /* Return a pointer to an xmalloc'ed string representing an escaped
7880 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7881 etc. The caller is responsible for releasing the returned
7885 escape_buffer (const char *buf, int n)
7887 struct cleanup *old_chain;
7888 struct ui_file *stb;
7891 stb = mem_fileopen ();
7892 old_chain = make_cleanup_ui_file_delete (stb);
7894 fputstrn_unfiltered (buf, n, '\\', stb);
7895 str = ui_file_xstrdup (stb, NULL);
7896 do_cleanups (old_chain);
7900 /* Display a null-terminated packet on stdout, for debugging, using C
7904 print_packet (const char *buf)
7906 puts_filtered ("\"");
7907 fputstr_filtered (buf, '"', gdb_stdout);
7908 puts_filtered ("\"");
7912 putpkt (const char *buf)
7914 return putpkt_binary (buf, strlen (buf));
7917 /* Send a packet to the remote machine, with error checking. The data
7918 of the packet is in BUF. The string in BUF can be at most
7919 get_remote_packet_size () - 5 to account for the $, # and checksum,
7920 and for a possible /0 if we are debugging (remote_debug) and want
7921 to print the sent packet as a string. */
7924 putpkt_binary (const char *buf, int cnt)
7926 struct remote_state *rs = get_remote_state ();
7928 unsigned char csum = 0;
7929 char *buf2 = xmalloc (cnt + 6);
7930 struct cleanup *old_chain = make_cleanup (xfree, buf2);
7937 /* Catch cases like trying to read memory or listing threads while
7938 we're waiting for a stop reply. The remote server wouldn't be
7939 ready to handle this request, so we'd hang and timeout. We don't
7940 have to worry about this in synchronous mode, because in that
7941 case it's not possible to issue a command while the target is
7942 running. This is not a problem in non-stop mode, because in that
7943 case, the stub is always ready to process serial input. */
7944 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7946 error (_("Cannot execute this command while the target is running.\n"
7947 "Use the \"interrupt\" command to stop the target\n"
7948 "and then try again."));
7951 /* We're sending out a new packet. Make sure we don't look at a
7952 stale cached response. */
7953 rs->cached_wait_status = 0;
7955 /* Copy the packet into buffer BUF2, encapsulating it
7956 and giving it a checksum. */
7961 for (i = 0; i < cnt; i++)
7967 *p++ = tohex ((csum >> 4) & 0xf);
7968 *p++ = tohex (csum & 0xf);
7970 /* Send it over and over until we get a positive ack. */
7974 int started_error_output = 0;
7978 struct cleanup *old_chain;
7982 str = escape_buffer (buf2, p - buf2);
7983 old_chain = make_cleanup (xfree, str);
7984 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7985 gdb_flush (gdb_stdlog);
7986 do_cleanups (old_chain);
7988 remote_serial_write (buf2, p - buf2);
7990 /* If this is a no acks version of the remote protocol, send the
7991 packet and move on. */
7995 /* Read until either a timeout occurs (-2) or '+' is read.
7996 Handle any notification that arrives in the mean time. */
7999 ch = readchar (remote_timeout);
8007 case SERIAL_TIMEOUT:
8010 if (started_error_output)
8012 putchar_unfiltered ('\n');
8013 started_error_output = 0;
8022 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8023 do_cleanups (old_chain);
8027 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8029 case SERIAL_TIMEOUT:
8033 do_cleanups (old_chain);
8036 break; /* Retransmit buffer. */
8040 fprintf_unfiltered (gdb_stdlog,
8041 "Packet instead of Ack, ignoring it\n");
8042 /* It's probably an old response sent because an ACK
8043 was lost. Gobble up the packet and ack it so it
8044 doesn't get retransmitted when we resend this
8047 remote_serial_write ("+", 1);
8048 continue; /* Now, go look for +. */
8055 /* If we got a notification, handle it, and go back to looking
8057 /* We've found the start of a notification. Now
8058 collect the data. */
8059 val = read_frame (&rs->buf, &rs->buf_size);
8064 struct cleanup *old_chain;
8067 str = escape_buffer (rs->buf, val);
8068 old_chain = make_cleanup (xfree, str);
8069 fprintf_unfiltered (gdb_stdlog,
8070 " Notification received: %s\n",
8072 do_cleanups (old_chain);
8074 handle_notification (rs->notif_state, rs->buf);
8075 /* We're in sync now, rewait for the ack. */
8082 if (!started_error_output)
8084 started_error_output = 1;
8085 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8087 fputc_unfiltered (ch & 0177, gdb_stdlog);
8088 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8097 if (!started_error_output)
8099 started_error_output = 1;
8100 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8102 fputc_unfiltered (ch & 0177, gdb_stdlog);
8106 break; /* Here to retransmit. */
8110 /* This is wrong. If doing a long backtrace, the user should be
8111 able to get out next time we call QUIT, without anything as
8112 violent as interrupt_query. If we want to provide a way out of
8113 here without getting to the next QUIT, it should be based on
8114 hitting ^C twice as in remote_wait. */
8123 do_cleanups (old_chain);
8127 /* Come here after finding the start of a frame when we expected an
8128 ack. Do our best to discard the rest of this packet. */
8137 c = readchar (remote_timeout);
8140 case SERIAL_TIMEOUT:
8141 /* Nothing we can do. */
8144 /* Discard the two bytes of checksum and stop. */
8145 c = readchar (remote_timeout);
8147 c = readchar (remote_timeout);
8150 case '*': /* Run length encoding. */
8151 /* Discard the repeat count. */
8152 c = readchar (remote_timeout);
8157 /* A regular character. */
8163 /* Come here after finding the start of the frame. Collect the rest
8164 into *BUF, verifying the checksum, length, and handling run-length
8165 compression. NUL terminate the buffer. If there is not enough room,
8166 expand *BUF using xrealloc.
8168 Returns -1 on error, number of characters in buffer (ignoring the
8169 trailing NULL) on success. (could be extended to return one of the
8170 SERIAL status indications). */
8173 read_frame (char **buf_p,
8180 struct remote_state *rs = get_remote_state ();
8187 c = readchar (remote_timeout);
8190 case SERIAL_TIMEOUT:
8192 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8196 fputs_filtered ("Saw new packet start in middle of old one\n",
8198 return -1; /* Start a new packet, count retries. */
8201 unsigned char pktcsum;
8207 check_0 = readchar (remote_timeout);
8209 check_1 = readchar (remote_timeout);
8211 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8214 fputs_filtered ("Timeout in checksum, retrying\n",
8218 else if (check_0 < 0 || check_1 < 0)
8221 fputs_filtered ("Communication error in checksum\n",
8226 /* Don't recompute the checksum; with no ack packets we
8227 don't have any way to indicate a packet retransmission
8232 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8233 if (csum == pktcsum)
8238 struct cleanup *old_chain;
8241 str = escape_buffer (buf, bc);
8242 old_chain = make_cleanup (xfree, str);
8243 fprintf_unfiltered (gdb_stdlog,
8244 "Bad checksum, sentsum=0x%x, "
8245 "csum=0x%x, buf=%s\n",
8246 pktcsum, csum, str);
8247 do_cleanups (old_chain);
8249 /* Number of characters in buffer ignoring trailing
8253 case '*': /* Run length encoding. */
8258 c = readchar (remote_timeout);
8260 repeat = c - ' ' + 3; /* Compute repeat count. */
8262 /* The character before ``*'' is repeated. */
8264 if (repeat > 0 && repeat <= 255 && bc > 0)
8266 if (bc + repeat - 1 >= *sizeof_buf - 1)
8268 /* Make some more room in the buffer. */
8269 *sizeof_buf += repeat;
8270 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8274 memset (&buf[bc], buf[bc - 1], repeat);
8280 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8284 if (bc >= *sizeof_buf - 1)
8286 /* Make some more room in the buffer. */
8288 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8299 /* Read a packet from the remote machine, with error checking, and
8300 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8301 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8302 rather than timing out; this is used (in synchronous mode) to wait
8303 for a target that is is executing user code to stop. */
8304 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8305 don't have to change all the calls to getpkt to deal with the
8306 return value, because at the moment I don't know what the right
8307 thing to do it for those. */
8315 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8319 /* Read a packet from the remote machine, with error checking, and
8320 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8321 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8322 rather than timing out; this is used (in synchronous mode) to wait
8323 for a target that is is executing user code to stop. If FOREVER ==
8324 0, this function is allowed to time out gracefully and return an
8325 indication of this to the caller. Otherwise return the number of
8326 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8327 enough reason to return to the caller. *IS_NOTIF is an output
8328 boolean that indicates whether *BUF holds a notification or not
8329 (a regular packet). */
8332 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8333 int expecting_notif, int *is_notif)
8335 struct remote_state *rs = get_remote_state ();
8341 /* We're reading a new response. Make sure we don't look at a
8342 previously cached response. */
8343 rs->cached_wait_status = 0;
8345 strcpy (*buf, "timeout");
8348 timeout = watchdog > 0 ? watchdog : -1;
8349 else if (expecting_notif)
8350 timeout = 0; /* There should already be a char in the buffer. If
8353 timeout = remote_timeout;
8357 /* Process any number of notifications, and then return when
8361 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8363 for (tries = 1; tries <= MAX_TRIES; tries++)
8365 /* This can loop forever if the remote side sends us
8366 characters continuously, but if it pauses, we'll get
8367 SERIAL_TIMEOUT from readchar because of timeout. Then
8368 we'll count that as a retry.
8370 Note that even when forever is set, we will only wait
8371 forever prior to the start of a packet. After that, we
8372 expect characters to arrive at a brisk pace. They should
8373 show up within remote_timeout intervals. */
8375 c = readchar (timeout);
8376 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8378 if (c == SERIAL_TIMEOUT)
8380 if (expecting_notif)
8381 return -1; /* Don't complain, it's normal to not get
8382 anything in this case. */
8384 if (forever) /* Watchdog went off? Kill the target. */
8387 remote_unpush_target ();
8388 throw_error (TARGET_CLOSE_ERROR,
8389 _("Watchdog timeout has expired. "
8390 "Target detached."));
8393 fputs_filtered ("Timed out.\n", gdb_stdlog);
8397 /* We've found the start of a packet or notification.
8398 Now collect the data. */
8399 val = read_frame (buf, sizeof_buf);
8404 remote_serial_write ("-", 1);
8407 if (tries > MAX_TRIES)
8409 /* We have tried hard enough, and just can't receive the
8410 packet/notification. Give up. */
8411 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8413 /* Skip the ack char if we're in no-ack mode. */
8414 if (!rs->noack_mode)
8415 remote_serial_write ("+", 1);
8419 /* If we got an ordinary packet, return that to our caller. */
8424 struct cleanup *old_chain;
8427 str = escape_buffer (*buf, val);
8428 old_chain = make_cleanup (xfree, str);
8429 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8430 do_cleanups (old_chain);
8433 /* Skip the ack char if we're in no-ack mode. */
8434 if (!rs->noack_mode)
8435 remote_serial_write ("+", 1);
8436 if (is_notif != NULL)
8441 /* If we got a notification, handle it, and go back to looking
8445 gdb_assert (c == '%');
8449 struct cleanup *old_chain;
8452 str = escape_buffer (*buf, val);
8453 old_chain = make_cleanup (xfree, str);
8454 fprintf_unfiltered (gdb_stdlog,
8455 " Notification received: %s\n",
8457 do_cleanups (old_chain);
8459 if (is_notif != NULL)
8462 handle_notification (rs->notif_state, *buf);
8464 /* Notifications require no acknowledgement. */
8466 if (expecting_notif)
8473 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8475 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8479 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8482 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8486 /* Check whether EVENT is a fork event for the process specified
8487 by the pid passed in DATA, and if it is, kill the fork child. */
8490 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8491 QUEUE_ITER (stop_reply_p) *iter,
8495 struct queue_iter_param *param = data;
8496 int parent_pid = *(int *) param->input;
8498 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8500 struct remote_state *rs = get_remote_state ();
8501 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8504 res = remote_vkill (child_pid, rs);
8506 error (_("Can't kill fork child process %d"), child_pid);
8512 /* Kill any new fork children of process PID that haven't been
8513 processed by follow_fork. */
8516 kill_new_fork_children (int pid, struct remote_state *rs)
8518 struct thread_info *thread;
8519 struct notif_client *notif = ¬if_client_stop;
8520 struct queue_iter_param param;
8522 /* Kill the fork child threads of any threads in process PID
8523 that are stopped at a fork event. */
8524 ALL_NON_EXITED_THREADS (thread)
8526 struct target_waitstatus *ws = &thread->pending_follow;
8528 if (is_pending_fork_parent (ws, pid, thread->ptid))
8530 struct remote_state *rs = get_remote_state ();
8531 int child_pid = ptid_get_pid (ws->value.related_pid);
8534 res = remote_vkill (child_pid, rs);
8536 error (_("Can't kill fork child process %d"), child_pid);
8540 /* Check for any pending fork events (not reported or processed yet)
8541 in process PID and kill those fork child threads as well. */
8542 remote_notif_get_pending_events (notif);
8544 param.output = NULL;
8545 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8546 kill_child_of_pending_fork, ¶m);
8551 remote_kill (struct target_ops *ops)
8554 /* Catch errors so the user can quit from gdb even when we
8555 aren't on speaking terms with the remote system. */
8560 CATCH (ex, RETURN_MASK_ERROR)
8562 if (ex.error == TARGET_CLOSE_ERROR)
8564 /* If we got an (EOF) error that caused the target
8565 to go away, then we're done, that's what we wanted.
8566 "k" is susceptible to cause a premature EOF, given
8567 that the remote server isn't actually required to
8568 reply to "k", and it can happen that it doesn't
8569 even get to reply ACK to the "k". */
8573 /* Otherwise, something went wrong. We didn't actually kill
8574 the target. Just propagate the exception, and let the
8575 user or higher layers decide what to do. */
8576 throw_exception (ex);
8580 /* We've killed the remote end, we get to mourn it. Since this is
8581 target remote, single-process, mourning the inferior also
8582 unpushes remote_ops. */
8583 target_mourn_inferior ();
8587 remote_vkill (int pid, struct remote_state *rs)
8589 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8592 /* Tell the remote target to detach. */
8593 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8595 getpkt (&rs->buf, &rs->buf_size, 0);
8597 switch (packet_ok (rs->buf,
8598 &remote_protocol_packets[PACKET_vKill]))
8604 case PACKET_UNKNOWN:
8607 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8612 extended_remote_kill (struct target_ops *ops)
8615 int pid = ptid_get_pid (inferior_ptid);
8616 struct remote_state *rs = get_remote_state ();
8618 /* If we're stopped while forking and we haven't followed yet, kill the
8619 child task. We need to do this before killing the parent task
8620 because if this is a vfork then the parent will be sleeping. */
8621 kill_new_fork_children (pid, rs);
8623 res = remote_vkill (pid, rs);
8624 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8626 /* Don't try 'k' on a multi-process aware stub -- it has no way
8627 to specify the pid. */
8631 getpkt (&rs->buf, &rs->buf_size, 0);
8632 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8635 /* Don't wait for it to die. I'm not really sure it matters whether
8636 we do or not. For the existing stubs, kill is a noop. */
8642 error (_("Can't kill process"));
8644 target_mourn_inferior ();
8648 remote_mourn (struct target_ops *target)
8650 unpush_target (target);
8652 /* remote_close takes care of doing most of the clean up. */
8653 generic_mourn_inferior ();
8657 extended_remote_mourn (struct target_ops *target)
8659 struct remote_state *rs = get_remote_state ();
8661 /* In case we got here due to an error, but we're going to stay
8663 rs->waiting_for_stop_reply = 0;
8665 /* If the current general thread belonged to the process we just
8666 detached from or has exited, the remote side current general
8667 thread becomes undefined. Considering a case like this:
8669 - We just got here due to a detach.
8670 - The process that we're detaching from happens to immediately
8671 report a global breakpoint being hit in non-stop mode, in the
8672 same thread we had selected before.
8673 - GDB attaches to this process again.
8674 - This event happens to be the next event we handle.
8676 GDB would consider that the current general thread didn't need to
8677 be set on the stub side (with Hg), since for all it knew,
8678 GENERAL_THREAD hadn't changed.
8680 Notice that although in all-stop mode, the remote server always
8681 sets the current thread to the thread reporting the stop event,
8682 that doesn't happen in non-stop mode; in non-stop, the stub *must
8683 not* change the current thread when reporting a breakpoint hit,
8684 due to the decoupling of event reporting and event handling.
8686 To keep things simple, we always invalidate our notion of the
8688 record_currthread (rs, minus_one_ptid);
8690 /* Unlike "target remote", we do not want to unpush the target; then
8691 the next time the user says "run", we won't be connected. */
8693 /* Call common code to mark the inferior as not running. */
8694 generic_mourn_inferior ();
8696 if (!have_inferiors ())
8698 if (!remote_multi_process_p (rs))
8700 /* Check whether the target is running now - some remote stubs
8701 automatically restart after kill. */
8703 getpkt (&rs->buf, &rs->buf_size, 0);
8705 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8707 /* Assume that the target has been restarted. Set
8708 inferior_ptid so that bits of core GDB realizes
8709 there's something here, e.g., so that the user can
8710 say "kill" again. */
8711 inferior_ptid = magic_null_ptid;
8718 extended_remote_supports_disable_randomization (struct target_ops *self)
8720 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8724 extended_remote_disable_randomization (int val)
8726 struct remote_state *rs = get_remote_state ();
8729 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8732 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8734 error (_("Target does not support QDisableRandomization."));
8735 if (strcmp (reply, "OK") != 0)
8736 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8740 extended_remote_run (char *args)
8742 struct remote_state *rs = get_remote_state ();
8744 const char *remote_exec_file = get_remote_exec_file ();
8746 /* If the user has disabled vRun support, or we have detected that
8747 support is not available, do not try it. */
8748 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8751 strcpy (rs->buf, "vRun;");
8752 len = strlen (rs->buf);
8754 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8755 error (_("Remote file name too long for run packet"));
8756 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8757 strlen (remote_exec_file));
8759 gdb_assert (args != NULL);
8762 struct cleanup *back_to;
8766 argv = gdb_buildargv (args);
8767 back_to = make_cleanup_freeargv (argv);
8768 for (i = 0; argv[i] != NULL; i++)
8770 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8771 error (_("Argument list too long for run packet"));
8772 rs->buf[len++] = ';';
8773 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8776 do_cleanups (back_to);
8779 rs->buf[len++] = '\0';
8782 getpkt (&rs->buf, &rs->buf_size, 0);
8784 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8787 /* We have a wait response. All is well. */
8789 case PACKET_UNKNOWN:
8792 if (remote_exec_file[0] == '\0')
8793 error (_("Running the default executable on the remote target failed; "
8794 "try \"set remote exec-file\"?"));
8796 error (_("Running \"%s\" on the remote target failed"),
8799 gdb_assert_not_reached (_("bad switch"));
8803 /* In the extended protocol we want to be able to do things like
8804 "run" and have them basically work as expected. So we need
8805 a special create_inferior function. We support changing the
8806 executable file and the command line arguments, but not the
8810 extended_remote_create_inferior (struct target_ops *ops,
8811 char *exec_file, char *args,
8812 char **env, int from_tty)
8816 struct remote_state *rs = get_remote_state ();
8817 const char *remote_exec_file = get_remote_exec_file ();
8819 /* If running asynchronously, register the target file descriptor
8820 with the event loop. */
8821 if (target_can_async_p ())
8824 /* Disable address space randomization if requested (and supported). */
8825 if (extended_remote_supports_disable_randomization (ops))
8826 extended_remote_disable_randomization (disable_randomization);
8828 /* Now restart the remote server. */
8829 run_worked = extended_remote_run (args) != -1;
8832 /* vRun was not supported. Fail if we need it to do what the
8834 if (remote_exec_file[0])
8835 error (_("Remote target does not support \"set remote exec-file\""));
8837 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8839 /* Fall back to "R". */
8840 extended_remote_restart ();
8843 if (!have_inferiors ())
8845 /* Clean up from the last time we ran, before we mark the target
8846 running again. This will mark breakpoints uninserted, and
8847 get_offsets may insert breakpoints. */
8848 init_thread_list ();
8849 init_wait_for_inferior ();
8852 /* vRun's success return is a stop reply. */
8853 stop_reply = run_worked ? rs->buf : NULL;
8854 add_current_inferior_and_thread (stop_reply);
8856 /* Get updated offsets, if the stub uses qOffsets. */
8861 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8862 the list of conditions (in agent expression bytecode format), if any, the
8863 target needs to evaluate. The output is placed into the packet buffer
8864 started from BUF and ended at BUF_END. */
8867 remote_add_target_side_condition (struct gdbarch *gdbarch,
8868 struct bp_target_info *bp_tgt, char *buf,
8871 struct agent_expr *aexpr = NULL;
8874 char *buf_start = buf;
8876 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8879 buf += strlen (buf);
8880 xsnprintf (buf, buf_end - buf, "%s", ";");
8883 /* Send conditions to the target and free the vector. */
8885 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8888 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8889 buf += strlen (buf);
8890 for (i = 0; i < aexpr->len; ++i)
8891 buf = pack_hex_byte (buf, aexpr->buf[i]);
8898 remote_add_target_side_commands (struct gdbarch *gdbarch,
8899 struct bp_target_info *bp_tgt, char *buf)
8901 struct agent_expr *aexpr = NULL;
8904 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8907 buf += strlen (buf);
8909 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8910 buf += strlen (buf);
8912 /* Concatenate all the agent expressions that are commands into the
8915 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8918 sprintf (buf, "X%x,", aexpr->len);
8919 buf += strlen (buf);
8920 for (i = 0; i < aexpr->len; ++i)
8921 buf = pack_hex_byte (buf, aexpr->buf[i]);
8926 /* Insert a breakpoint. On targets that have software breakpoint
8927 support, we ask the remote target to do the work; on targets
8928 which don't, we insert a traditional memory breakpoint. */
8931 remote_insert_breakpoint (struct target_ops *ops,
8932 struct gdbarch *gdbarch,
8933 struct bp_target_info *bp_tgt)
8935 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8936 If it succeeds, then set the support to PACKET_ENABLE. If it
8937 fails, and the user has explicitly requested the Z support then
8938 report an error, otherwise, mark it disabled and go on. */
8940 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8942 CORE_ADDR addr = bp_tgt->reqstd_address;
8943 struct remote_state *rs;
8946 struct condition_list *cond = NULL;
8948 /* Make sure the remote is pointing at the right process, if
8950 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8951 set_general_process ();
8953 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8955 rs = get_remote_state ();
8957 endbuf = rs->buf + get_remote_packet_size ();
8962 addr = (ULONGEST) remote_address_masked (addr);
8963 p += hexnumstr (p, addr);
8964 xsnprintf (p, endbuf - p, ",%d", bpsize);
8966 if (remote_supports_cond_breakpoints (ops))
8967 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8969 if (remote_can_run_breakpoint_commands (ops))
8970 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8973 getpkt (&rs->buf, &rs->buf_size, 0);
8975 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8980 bp_tgt->placed_address = addr;
8981 bp_tgt->placed_size = bpsize;
8983 case PACKET_UNKNOWN:
8988 /* If this breakpoint has target-side commands but this stub doesn't
8989 support Z0 packets, throw error. */
8990 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8991 throw_error (NOT_SUPPORTED_ERROR, _("\
8992 Target doesn't support breakpoints that have target side commands."));
8994 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8998 remote_remove_breakpoint (struct target_ops *ops,
8999 struct gdbarch *gdbarch,
9000 struct bp_target_info *bp_tgt)
9002 CORE_ADDR addr = bp_tgt->placed_address;
9003 struct remote_state *rs = get_remote_state ();
9005 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9008 char *endbuf = rs->buf + get_remote_packet_size ();
9010 /* Make sure the remote is pointing at the right process, if
9012 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9013 set_general_process ();
9019 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9020 p += hexnumstr (p, addr);
9021 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9024 getpkt (&rs->buf, &rs->buf_size, 0);
9026 return (rs->buf[0] == 'E');
9029 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9032 static enum Z_packet_type
9033 watchpoint_to_Z_packet (int type)
9038 return Z_PACKET_WRITE_WP;
9041 return Z_PACKET_READ_WP;
9044 return Z_PACKET_ACCESS_WP;
9047 internal_error (__FILE__, __LINE__,
9048 _("hw_bp_to_z: bad watchpoint type %d"), type);
9053 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9054 enum target_hw_bp_type type, struct expression *cond)
9056 struct remote_state *rs = get_remote_state ();
9057 char *endbuf = rs->buf + get_remote_packet_size ();
9059 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9061 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9064 /* Make sure the remote is pointing at the right process, if
9066 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9067 set_general_process ();
9069 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9070 p = strchr (rs->buf, '\0');
9071 addr = remote_address_masked (addr);
9072 p += hexnumstr (p, (ULONGEST) addr);
9073 xsnprintf (p, endbuf - p, ",%x", len);
9076 getpkt (&rs->buf, &rs->buf_size, 0);
9078 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9082 case PACKET_UNKNOWN:
9087 internal_error (__FILE__, __LINE__,
9088 _("remote_insert_watchpoint: reached end of function"));
9092 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9093 CORE_ADDR start, int length)
9095 CORE_ADDR diff = remote_address_masked (addr - start);
9097 return diff < length;
9102 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9103 enum target_hw_bp_type type, struct expression *cond)
9105 struct remote_state *rs = get_remote_state ();
9106 char *endbuf = rs->buf + get_remote_packet_size ();
9108 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9110 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9113 /* Make sure the remote is pointing at the right process, if
9115 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9116 set_general_process ();
9118 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9119 p = strchr (rs->buf, '\0');
9120 addr = remote_address_masked (addr);
9121 p += hexnumstr (p, (ULONGEST) addr);
9122 xsnprintf (p, endbuf - p, ",%x", len);
9124 getpkt (&rs->buf, &rs->buf_size, 0);
9126 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9129 case PACKET_UNKNOWN:
9134 internal_error (__FILE__, __LINE__,
9135 _("remote_remove_watchpoint: reached end of function"));
9139 int remote_hw_watchpoint_limit = -1;
9140 int remote_hw_watchpoint_length_limit = -1;
9141 int remote_hw_breakpoint_limit = -1;
9144 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9145 CORE_ADDR addr, int len)
9147 if (remote_hw_watchpoint_length_limit == 0)
9149 else if (remote_hw_watchpoint_length_limit < 0)
9151 else if (len <= remote_hw_watchpoint_length_limit)
9158 remote_check_watch_resources (struct target_ops *self,
9159 enum bptype type, int cnt, int ot)
9161 if (type == bp_hardware_breakpoint)
9163 if (remote_hw_breakpoint_limit == 0)
9165 else if (remote_hw_breakpoint_limit < 0)
9167 else if (cnt <= remote_hw_breakpoint_limit)
9172 if (remote_hw_watchpoint_limit == 0)
9174 else if (remote_hw_watchpoint_limit < 0)
9178 else if (cnt <= remote_hw_watchpoint_limit)
9184 /* The to_stopped_by_sw_breakpoint method of target remote. */
9187 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9189 struct remote_state *rs = get_remote_state ();
9191 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9194 /* The to_supports_stopped_by_sw_breakpoint method of target
9198 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9200 struct remote_state *rs = get_remote_state ();
9202 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9205 /* The to_stopped_by_hw_breakpoint method of target remote. */
9208 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9210 struct remote_state *rs = get_remote_state ();
9212 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9215 /* The to_supports_stopped_by_hw_breakpoint method of target
9219 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9221 struct remote_state *rs = get_remote_state ();
9223 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9227 remote_stopped_by_watchpoint (struct target_ops *ops)
9229 struct remote_state *rs = get_remote_state ();
9231 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
9235 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9237 struct remote_state *rs = get_remote_state ();
9240 if (remote_stopped_by_watchpoint (target))
9242 *addr_p = rs->remote_watch_data_address;
9251 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9252 struct bp_target_info *bp_tgt)
9254 CORE_ADDR addr = bp_tgt->reqstd_address;
9255 struct remote_state *rs;
9260 /* The length field should be set to the size of a breakpoint
9261 instruction, even though we aren't inserting one ourselves. */
9263 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9265 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9268 /* Make sure the remote is pointing at the right process, if
9270 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9271 set_general_process ();
9273 rs = get_remote_state ();
9275 endbuf = rs->buf + get_remote_packet_size ();
9281 addr = remote_address_masked (addr);
9282 p += hexnumstr (p, (ULONGEST) addr);
9283 xsnprintf (p, endbuf - p, ",%x", bpsize);
9285 if (remote_supports_cond_breakpoints (self))
9286 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9288 if (remote_can_run_breakpoint_commands (self))
9289 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9292 getpkt (&rs->buf, &rs->buf_size, 0);
9294 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9297 if (rs->buf[1] == '.')
9299 message = strchr (rs->buf + 2, '.');
9301 error (_("Remote failure reply: %s"), message + 1);
9304 case PACKET_UNKNOWN:
9307 bp_tgt->placed_address = addr;
9308 bp_tgt->placed_size = bpsize;
9311 internal_error (__FILE__, __LINE__,
9312 _("remote_insert_hw_breakpoint: reached end of function"));
9317 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9318 struct bp_target_info *bp_tgt)
9321 struct remote_state *rs = get_remote_state ();
9323 char *endbuf = rs->buf + get_remote_packet_size ();
9325 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9328 /* Make sure the remote is pointing at the right process, if
9330 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9331 set_general_process ();
9337 addr = remote_address_masked (bp_tgt->placed_address);
9338 p += hexnumstr (p, (ULONGEST) addr);
9339 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9342 getpkt (&rs->buf, &rs->buf_size, 0);
9344 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9347 case PACKET_UNKNOWN:
9352 internal_error (__FILE__, __LINE__,
9353 _("remote_remove_hw_breakpoint: reached end of function"));
9356 /* Verify memory using the "qCRC:" request. */
9359 remote_verify_memory (struct target_ops *ops,
9360 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9362 struct remote_state *rs = get_remote_state ();
9363 unsigned long host_crc, target_crc;
9366 /* It doesn't make sense to use qCRC if the remote target is
9367 connected but not running. */
9368 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9370 enum packet_result result;
9372 /* Make sure the remote is pointing at the right process. */
9373 set_general_process ();
9375 /* FIXME: assumes lma can fit into long. */
9376 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9377 (long) lma, (long) size);
9380 /* Be clever; compute the host_crc before waiting for target
9382 host_crc = xcrc32 (data, size, 0xffffffff);
9384 getpkt (&rs->buf, &rs->buf_size, 0);
9386 result = packet_ok (rs->buf,
9387 &remote_protocol_packets[PACKET_qCRC]);
9388 if (result == PACKET_ERROR)
9390 else if (result == PACKET_OK)
9392 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9393 target_crc = target_crc * 16 + fromhex (*tmp);
9395 return (host_crc == target_crc);
9399 return simple_verify_memory (ops, data, lma, size);
9402 /* compare-sections command
9404 With no arguments, compares each loadable section in the exec bfd
9405 with the same memory range on the target, and reports mismatches.
9406 Useful for verifying the image on the target against the exec file. */
9409 compare_sections_command (char *args, int from_tty)
9412 struct cleanup *old_chain;
9414 const char *sectname;
9423 error (_("command cannot be used without an exec file"));
9425 /* Make sure the remote is pointing at the right process. */
9426 set_general_process ();
9428 if (args != NULL && strcmp (args, "-r") == 0)
9434 for (s = exec_bfd->sections; s; s = s->next)
9436 if (!(s->flags & SEC_LOAD))
9437 continue; /* Skip non-loadable section. */
9439 if (read_only && (s->flags & SEC_READONLY) == 0)
9440 continue; /* Skip writeable sections */
9442 size = bfd_get_section_size (s);
9444 continue; /* Skip zero-length section. */
9446 sectname = bfd_get_section_name (exec_bfd, s);
9447 if (args && strcmp (args, sectname) != 0)
9448 continue; /* Not the section selected by user. */
9450 matched = 1; /* Do this section. */
9453 sectdata = xmalloc (size);
9454 old_chain = make_cleanup (xfree, sectdata);
9455 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9457 res = target_verify_memory (sectdata, lma, size);
9460 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9461 paddress (target_gdbarch (), lma),
9462 paddress (target_gdbarch (), lma + size));
9464 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9465 paddress (target_gdbarch (), lma),
9466 paddress (target_gdbarch (), lma + size));
9468 printf_filtered ("matched.\n");
9471 printf_filtered ("MIS-MATCHED!\n");
9475 do_cleanups (old_chain);
9478 warning (_("One or more sections of the target image does not match\n\
9479 the loaded file\n"));
9480 if (args && !matched)
9481 printf_filtered (_("No loaded section named '%s'.\n"), args);
9484 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9485 into remote target. The number of bytes written to the remote
9486 target is returned, or -1 for error. */
9488 static enum target_xfer_status
9489 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9490 const char *annex, const gdb_byte *writebuf,
9491 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9492 struct packet_config *packet)
9496 struct remote_state *rs = get_remote_state ();
9497 int max_size = get_memory_write_packet_size ();
9499 if (packet->support == PACKET_DISABLE)
9500 return TARGET_XFER_E_IO;
9502 /* Insert header. */
9503 i = snprintf (rs->buf, max_size,
9504 "qXfer:%s:write:%s:%s:",
9505 object_name, annex ? annex : "",
9506 phex_nz (offset, sizeof offset));
9507 max_size -= (i + 1);
9509 /* Escape as much data as fits into rs->buf. */
9510 buf_len = remote_escape_output
9511 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9513 if (putpkt_binary (rs->buf, i + buf_len) < 0
9514 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9515 || packet_ok (rs->buf, packet) != PACKET_OK)
9516 return TARGET_XFER_E_IO;
9518 unpack_varlen_hex (rs->buf, &n);
9521 return TARGET_XFER_OK;
9524 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9525 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9526 number of bytes read is returned, or 0 for EOF, or -1 for error.
9527 The number of bytes read may be less than LEN without indicating an
9528 EOF. PACKET is checked and updated to indicate whether the remote
9529 target supports this object. */
9531 static enum target_xfer_status
9532 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9534 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9535 ULONGEST *xfered_len,
9536 struct packet_config *packet)
9538 struct remote_state *rs = get_remote_state ();
9539 LONGEST i, n, packet_len;
9541 if (packet->support == PACKET_DISABLE)
9542 return TARGET_XFER_E_IO;
9544 /* Check whether we've cached an end-of-object packet that matches
9546 if (rs->finished_object)
9548 if (strcmp (object_name, rs->finished_object) == 0
9549 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9550 && offset == rs->finished_offset)
9551 return TARGET_XFER_EOF;
9554 /* Otherwise, we're now reading something different. Discard
9556 xfree (rs->finished_object);
9557 xfree (rs->finished_annex);
9558 rs->finished_object = NULL;
9559 rs->finished_annex = NULL;
9562 /* Request only enough to fit in a single packet. The actual data
9563 may not, since we don't know how much of it will need to be escaped;
9564 the target is free to respond with slightly less data. We subtract
9565 five to account for the response type and the protocol frame. */
9566 n = min (get_remote_packet_size () - 5, len);
9567 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9568 object_name, annex ? annex : "",
9569 phex_nz (offset, sizeof offset),
9570 phex_nz (n, sizeof n));
9571 i = putpkt (rs->buf);
9573 return TARGET_XFER_E_IO;
9576 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9577 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9578 return TARGET_XFER_E_IO;
9580 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9581 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9583 /* 'm' means there is (or at least might be) more data after this
9584 batch. That does not make sense unless there's at least one byte
9585 of data in this reply. */
9586 if (rs->buf[0] == 'm' && packet_len == 1)
9587 error (_("Remote qXfer reply contained no data."));
9589 /* Got some data. */
9590 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9591 packet_len - 1, readbuf, n);
9593 /* 'l' is an EOF marker, possibly including a final block of data,
9594 or possibly empty. If we have the final block of a non-empty
9595 object, record this fact to bypass a subsequent partial read. */
9596 if (rs->buf[0] == 'l' && offset + i > 0)
9598 rs->finished_object = xstrdup (object_name);
9599 rs->finished_annex = xstrdup (annex ? annex : "");
9600 rs->finished_offset = offset + i;
9604 return TARGET_XFER_EOF;
9608 return TARGET_XFER_OK;
9612 static enum target_xfer_status
9613 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9614 const char *annex, gdb_byte *readbuf,
9615 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9616 ULONGEST *xfered_len)
9618 struct remote_state *rs;
9622 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9624 set_remote_traceframe ();
9625 set_general_thread (inferior_ptid);
9627 rs = get_remote_state ();
9629 /* Handle memory using the standard memory routines. */
9630 if (object == TARGET_OBJECT_MEMORY)
9632 /* If the remote target is connected but not running, we should
9633 pass this request down to a lower stratum (e.g. the executable
9635 if (!target_has_execution)
9636 return TARGET_XFER_EOF;
9638 if (writebuf != NULL)
9639 return remote_write_bytes (offset, writebuf, len, unit_size,
9642 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9646 /* Handle SPU memory using qxfer packets. */
9647 if (object == TARGET_OBJECT_SPU)
9650 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9651 xfered_len, &remote_protocol_packets
9652 [PACKET_qXfer_spu_read]);
9654 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9655 xfered_len, &remote_protocol_packets
9656 [PACKET_qXfer_spu_write]);
9659 /* Handle extra signal info using qxfer packets. */
9660 if (object == TARGET_OBJECT_SIGNAL_INFO)
9663 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9664 xfered_len, &remote_protocol_packets
9665 [PACKET_qXfer_siginfo_read]);
9667 return remote_write_qxfer (ops, "siginfo", annex,
9668 writebuf, offset, len, xfered_len,
9669 &remote_protocol_packets
9670 [PACKET_qXfer_siginfo_write]);
9673 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9676 return remote_read_qxfer (ops, "statictrace", annex,
9677 readbuf, offset, len, xfered_len,
9678 &remote_protocol_packets
9679 [PACKET_qXfer_statictrace_read]);
9681 return TARGET_XFER_E_IO;
9684 /* Only handle flash writes. */
9685 if (writebuf != NULL)
9691 case TARGET_OBJECT_FLASH:
9692 return remote_flash_write (ops, offset, len, xfered_len,
9696 return TARGET_XFER_E_IO;
9700 /* Map pre-existing objects onto letters. DO NOT do this for new
9701 objects!!! Instead specify new query packets. */
9704 case TARGET_OBJECT_AVR:
9708 case TARGET_OBJECT_AUXV:
9709 gdb_assert (annex == NULL);
9710 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9712 &remote_protocol_packets[PACKET_qXfer_auxv]);
9714 case TARGET_OBJECT_AVAILABLE_FEATURES:
9715 return remote_read_qxfer
9716 (ops, "features", annex, readbuf, offset, len, xfered_len,
9717 &remote_protocol_packets[PACKET_qXfer_features]);
9719 case TARGET_OBJECT_LIBRARIES:
9720 return remote_read_qxfer
9721 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9722 &remote_protocol_packets[PACKET_qXfer_libraries]);
9724 case TARGET_OBJECT_LIBRARIES_SVR4:
9725 return remote_read_qxfer
9726 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9727 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9729 case TARGET_OBJECT_MEMORY_MAP:
9730 gdb_assert (annex == NULL);
9731 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9733 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9735 case TARGET_OBJECT_OSDATA:
9736 /* Should only get here if we're connected. */
9737 gdb_assert (rs->remote_desc);
9738 return remote_read_qxfer
9739 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9740 &remote_protocol_packets[PACKET_qXfer_osdata]);
9742 case TARGET_OBJECT_THREADS:
9743 gdb_assert (annex == NULL);
9744 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9746 &remote_protocol_packets[PACKET_qXfer_threads]);
9748 case TARGET_OBJECT_TRACEFRAME_INFO:
9749 gdb_assert (annex == NULL);
9750 return remote_read_qxfer
9751 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9752 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9754 case TARGET_OBJECT_FDPIC:
9755 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9757 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9759 case TARGET_OBJECT_OPENVMS_UIB:
9760 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9762 &remote_protocol_packets[PACKET_qXfer_uib]);
9764 case TARGET_OBJECT_BTRACE:
9765 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9767 &remote_protocol_packets[PACKET_qXfer_btrace]);
9769 case TARGET_OBJECT_BTRACE_CONF:
9770 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9772 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9774 case TARGET_OBJECT_EXEC_FILE:
9775 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9777 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9780 return TARGET_XFER_E_IO;
9783 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9784 large enough let the caller deal with it. */
9785 if (len < get_remote_packet_size ())
9786 return TARGET_XFER_E_IO;
9787 len = get_remote_packet_size ();
9789 /* Except for querying the minimum buffer size, target must be open. */
9790 if (!rs->remote_desc)
9791 error (_("remote query is only available after target open"));
9793 gdb_assert (annex != NULL);
9794 gdb_assert (readbuf != NULL);
9800 /* We used one buffer char for the remote protocol q command and
9801 another for the query type. As the remote protocol encapsulation
9802 uses 4 chars plus one extra in case we are debugging
9803 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9806 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9808 /* Bad caller may have sent forbidden characters. */
9809 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9814 gdb_assert (annex[i] == '\0');
9816 i = putpkt (rs->buf);
9818 return TARGET_XFER_E_IO;
9820 getpkt (&rs->buf, &rs->buf_size, 0);
9821 strcpy ((char *) readbuf, rs->buf);
9823 *xfered_len = strlen ((char *) readbuf);
9824 return TARGET_XFER_OK;
9828 remote_search_memory (struct target_ops* ops,
9829 CORE_ADDR start_addr, ULONGEST search_space_len,
9830 const gdb_byte *pattern, ULONGEST pattern_len,
9831 CORE_ADDR *found_addrp)
9833 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9834 struct remote_state *rs = get_remote_state ();
9835 int max_size = get_memory_write_packet_size ();
9836 struct packet_config *packet =
9837 &remote_protocol_packets[PACKET_qSearch_memory];
9838 /* Number of packet bytes used to encode the pattern;
9839 this could be more than PATTERN_LEN due to escape characters. */
9840 int escaped_pattern_len;
9841 /* Amount of pattern that was encodable in the packet. */
9842 int used_pattern_len;
9845 ULONGEST found_addr;
9847 /* Don't go to the target if we don't have to.
9848 This is done before checking packet->support to avoid the possibility that
9849 a success for this edge case means the facility works in general. */
9850 if (pattern_len > search_space_len)
9852 if (pattern_len == 0)
9854 *found_addrp = start_addr;
9858 /* If we already know the packet isn't supported, fall back to the simple
9859 way of searching memory. */
9861 if (packet_config_support (packet) == PACKET_DISABLE)
9863 /* Target doesn't provided special support, fall back and use the
9864 standard support (copy memory and do the search here). */
9865 return simple_search_memory (ops, start_addr, search_space_len,
9866 pattern, pattern_len, found_addrp);
9869 /* Make sure the remote is pointing at the right process. */
9870 set_general_process ();
9872 /* Insert header. */
9873 i = snprintf (rs->buf, max_size,
9874 "qSearch:memory:%s;%s;",
9875 phex_nz (start_addr, addr_size),
9876 phex_nz (search_space_len, sizeof (search_space_len)));
9877 max_size -= (i + 1);
9879 /* Escape as much data as fits into rs->buf. */
9880 escaped_pattern_len =
9881 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
9882 &used_pattern_len, max_size);
9884 /* Bail if the pattern is too large. */
9885 if (used_pattern_len != pattern_len)
9886 error (_("Pattern is too large to transmit to remote target."));
9888 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9889 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9890 || packet_ok (rs->buf, packet) != PACKET_OK)
9892 /* The request may not have worked because the command is not
9893 supported. If so, fall back to the simple way. */
9894 if (packet->support == PACKET_DISABLE)
9896 return simple_search_memory (ops, start_addr, search_space_len,
9897 pattern, pattern_len, found_addrp);
9902 if (rs->buf[0] == '0')
9904 else if (rs->buf[0] == '1')
9907 if (rs->buf[1] != ',')
9908 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9909 unpack_varlen_hex (rs->buf + 2, &found_addr);
9910 *found_addrp = found_addr;
9913 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9919 remote_rcmd (struct target_ops *self, const char *command,
9920 struct ui_file *outbuf)
9922 struct remote_state *rs = get_remote_state ();
9925 if (!rs->remote_desc)
9926 error (_("remote rcmd is only available after target open"));
9928 /* Send a NULL command across as an empty command. */
9929 if (command == NULL)
9932 /* The query prefix. */
9933 strcpy (rs->buf, "qRcmd,");
9934 p = strchr (rs->buf, '\0');
9936 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9937 > get_remote_packet_size ())
9938 error (_("\"monitor\" command ``%s'' is too long."), command);
9940 /* Encode the actual command. */
9941 bin2hex ((const gdb_byte *) command, p, strlen (command));
9943 if (putpkt (rs->buf) < 0)
9944 error (_("Communication problem with target."));
9946 /* get/display the response */
9951 /* XXX - see also remote_get_noisy_reply(). */
9952 QUIT; /* Allow user to bail out with ^C. */
9954 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9956 /* Timeout. Continue to (try to) read responses.
9957 This is better than stopping with an error, assuming the stub
9958 is still executing the (long) monitor command.
9959 If needed, the user can interrupt gdb using C-c, obtaining
9960 an effect similar to stop on timeout. */
9965 error (_("Target does not support this command."));
9966 if (buf[0] == 'O' && buf[1] != 'K')
9968 remote_console_output (buf + 1); /* 'O' message from stub. */
9971 if (strcmp (buf, "OK") == 0)
9973 if (strlen (buf) == 3 && buf[0] == 'E'
9974 && isdigit (buf[1]) && isdigit (buf[2]))
9976 error (_("Protocol error with Rcmd"));
9978 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9980 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9982 fputc_unfiltered (c, outbuf);
9988 static VEC(mem_region_s) *
9989 remote_memory_map (struct target_ops *ops)
9991 VEC(mem_region_s) *result = NULL;
9992 char *text = target_read_stralloc (¤t_target,
9993 TARGET_OBJECT_MEMORY_MAP, NULL);
9997 struct cleanup *back_to = make_cleanup (xfree, text);
9999 result = parse_memory_map (text);
10000 do_cleanups (back_to);
10007 packet_command (char *args, int from_tty)
10009 struct remote_state *rs = get_remote_state ();
10011 if (!rs->remote_desc)
10012 error (_("command can only be used with remote target"));
10015 error (_("remote-packet command requires packet text as argument"));
10017 puts_filtered ("sending: ");
10018 print_packet (args);
10019 puts_filtered ("\n");
10022 getpkt (&rs->buf, &rs->buf_size, 0);
10023 puts_filtered ("received: ");
10024 print_packet (rs->buf);
10025 puts_filtered ("\n");
10029 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10031 static void display_thread_info (struct gdb_ext_thread_info *info);
10033 static void threadset_test_cmd (char *cmd, int tty);
10035 static void threadalive_test (char *cmd, int tty);
10037 static void threadlist_test_cmd (char *cmd, int tty);
10039 int get_and_display_threadinfo (threadref *ref);
10041 static void threadinfo_test_cmd (char *cmd, int tty);
10043 static int thread_display_step (threadref *ref, void *context);
10045 static void threadlist_update_test_cmd (char *cmd, int tty);
10047 static void init_remote_threadtests (void);
10049 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10052 threadset_test_cmd (char *cmd, int tty)
10054 int sample_thread = SAMPLE_THREAD;
10056 printf_filtered (_("Remote threadset test\n"));
10057 set_general_thread (sample_thread);
10062 threadalive_test (char *cmd, int tty)
10064 int sample_thread = SAMPLE_THREAD;
10065 int pid = ptid_get_pid (inferior_ptid);
10066 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10068 if (remote_thread_alive (ptid))
10069 printf_filtered ("PASS: Thread alive test\n");
10071 printf_filtered ("FAIL: Thread alive test\n");
10074 void output_threadid (char *title, threadref *ref);
10077 output_threadid (char *title, threadref *ref)
10081 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10083 printf_filtered ("%s %s\n", title, (&hexid[0]));
10087 threadlist_test_cmd (char *cmd, int tty)
10090 threadref nextthread;
10091 int done, result_count;
10092 threadref threadlist[3];
10094 printf_filtered ("Remote Threadlist test\n");
10095 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10096 &result_count, &threadlist[0]))
10097 printf_filtered ("FAIL: threadlist test\n");
10100 threadref *scan = threadlist;
10101 threadref *limit = scan + result_count;
10103 while (scan < limit)
10104 output_threadid (" thread ", scan++);
10109 display_thread_info (struct gdb_ext_thread_info *info)
10111 output_threadid ("Threadid: ", &info->threadid);
10112 printf_filtered ("Name: %s\n ", info->shortname);
10113 printf_filtered ("State: %s\n", info->display);
10114 printf_filtered ("other: %s\n\n", info->more_display);
10118 get_and_display_threadinfo (threadref *ref)
10122 struct gdb_ext_thread_info threadinfo;
10124 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10125 | TAG_MOREDISPLAY | TAG_DISPLAY;
10126 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10127 display_thread_info (&threadinfo);
10132 threadinfo_test_cmd (char *cmd, int tty)
10134 int athread = SAMPLE_THREAD;
10138 int_to_threadref (&thread, athread);
10139 printf_filtered ("Remote Threadinfo test\n");
10140 if (!get_and_display_threadinfo (&thread))
10141 printf_filtered ("FAIL cannot get thread info\n");
10145 thread_display_step (threadref *ref, void *context)
10147 /* output_threadid(" threadstep ",ref); *//* simple test */
10148 return get_and_display_threadinfo (ref);
10152 threadlist_update_test_cmd (char *cmd, int tty)
10154 printf_filtered ("Remote Threadlist update test\n");
10155 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10159 init_remote_threadtests (void)
10161 add_com ("tlist", class_obscure, threadlist_test_cmd,
10162 _("Fetch and print the remote list of "
10163 "thread identifiers, one pkt only"));
10164 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10165 _("Fetch and display info about one thread"));
10166 add_com ("tset", class_obscure, threadset_test_cmd,
10167 _("Test setting to a different thread"));
10168 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10169 _("Iterate through updating all remote thread info"));
10170 add_com ("talive", class_obscure, threadalive_test,
10171 _(" Remote thread alive test "));
10176 /* Convert a thread ID to a string. Returns the string in a static
10180 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10182 static char buf[64];
10183 struct remote_state *rs = get_remote_state ();
10185 if (ptid_equal (ptid, null_ptid))
10186 return normal_pid_to_str (ptid);
10187 else if (ptid_is_pid (ptid))
10189 /* Printing an inferior target id. */
10191 /* When multi-process extensions are off, there's no way in the
10192 remote protocol to know the remote process id, if there's any
10193 at all. There's one exception --- when we're connected with
10194 target extended-remote, and we manually attached to a process
10195 with "attach PID". We don't record anywhere a flag that
10196 allows us to distinguish that case from the case of
10197 connecting with extended-remote and the stub already being
10198 attached to a process, and reporting yes to qAttached, hence
10199 no smart special casing here. */
10200 if (!remote_multi_process_p (rs))
10202 xsnprintf (buf, sizeof buf, "Remote target");
10206 return normal_pid_to_str (ptid);
10210 if (ptid_equal (magic_null_ptid, ptid))
10211 xsnprintf (buf, sizeof buf, "Thread <main>");
10212 else if (rs->extended && remote_multi_process_p (rs))
10213 if (ptid_get_lwp (ptid) == 0)
10214 return normal_pid_to_str (ptid);
10216 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10217 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10219 xsnprintf (buf, sizeof buf, "Thread %ld",
10220 ptid_get_lwp (ptid));
10225 /* Get the address of the thread local variable in OBJFILE which is
10226 stored at OFFSET within the thread local storage for thread PTID. */
10229 remote_get_thread_local_address (struct target_ops *ops,
10230 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10232 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10234 struct remote_state *rs = get_remote_state ();
10236 char *endp = rs->buf + get_remote_packet_size ();
10237 enum packet_result result;
10239 strcpy (p, "qGetTLSAddr:");
10241 p = write_ptid (p, endp, ptid);
10243 p += hexnumstr (p, offset);
10245 p += hexnumstr (p, lm);
10249 getpkt (&rs->buf, &rs->buf_size, 0);
10250 result = packet_ok (rs->buf,
10251 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10252 if (result == PACKET_OK)
10256 unpack_varlen_hex (rs->buf, &result);
10259 else if (result == PACKET_UNKNOWN)
10260 throw_error (TLS_GENERIC_ERROR,
10261 _("Remote target doesn't support qGetTLSAddr packet"));
10263 throw_error (TLS_GENERIC_ERROR,
10264 _("Remote target failed to process qGetTLSAddr request"));
10267 throw_error (TLS_GENERIC_ERROR,
10268 _("TLS not supported or disabled on this target"));
10273 /* Provide thread local base, i.e. Thread Information Block address.
10274 Returns 1 if ptid is found and thread_local_base is non zero. */
10277 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10279 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10281 struct remote_state *rs = get_remote_state ();
10283 char *endp = rs->buf + get_remote_packet_size ();
10284 enum packet_result result;
10286 strcpy (p, "qGetTIBAddr:");
10288 p = write_ptid (p, endp, ptid);
10292 getpkt (&rs->buf, &rs->buf_size, 0);
10293 result = packet_ok (rs->buf,
10294 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10295 if (result == PACKET_OK)
10299 unpack_varlen_hex (rs->buf, &result);
10301 *addr = (CORE_ADDR) result;
10304 else if (result == PACKET_UNKNOWN)
10305 error (_("Remote target doesn't support qGetTIBAddr packet"));
10307 error (_("Remote target failed to process qGetTIBAddr request"));
10310 error (_("qGetTIBAddr not supported or disabled on this target"));
10315 /* Support for inferring a target description based on the current
10316 architecture and the size of a 'g' packet. While the 'g' packet
10317 can have any size (since optional registers can be left off the
10318 end), some sizes are easily recognizable given knowledge of the
10319 approximate architecture. */
10321 struct remote_g_packet_guess
10324 const struct target_desc *tdesc;
10326 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10327 DEF_VEC_O(remote_g_packet_guess_s);
10329 struct remote_g_packet_data
10331 VEC(remote_g_packet_guess_s) *guesses;
10334 static struct gdbarch_data *remote_g_packet_data_handle;
10337 remote_g_packet_data_init (struct obstack *obstack)
10339 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10343 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10344 const struct target_desc *tdesc)
10346 struct remote_g_packet_data *data
10347 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10348 struct remote_g_packet_guess new_guess, *guess;
10351 gdb_assert (tdesc != NULL);
10354 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10356 if (guess->bytes == bytes)
10357 internal_error (__FILE__, __LINE__,
10358 _("Duplicate g packet description added for size %d"),
10361 new_guess.bytes = bytes;
10362 new_guess.tdesc = tdesc;
10363 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10366 /* Return 1 if remote_read_description would do anything on this target
10367 and architecture, 0 otherwise. */
10370 remote_read_description_p (struct target_ops *target)
10372 struct remote_g_packet_data *data
10373 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10375 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10381 static const struct target_desc *
10382 remote_read_description (struct target_ops *target)
10384 struct remote_g_packet_data *data
10385 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10387 /* Do not try this during initial connection, when we do not know
10388 whether there is a running but stopped thread. */
10389 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10390 return target->beneath->to_read_description (target->beneath);
10392 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10394 struct remote_g_packet_guess *guess;
10396 int bytes = send_g_packet ();
10399 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10401 if (guess->bytes == bytes)
10402 return guess->tdesc;
10404 /* We discard the g packet. A minor optimization would be to
10405 hold on to it, and fill the register cache once we have selected
10406 an architecture, but it's too tricky to do safely. */
10409 return target->beneath->to_read_description (target->beneath);
10412 /* Remote file transfer support. This is host-initiated I/O, not
10413 target-initiated; for target-initiated, see remote-fileio.c. */
10415 /* If *LEFT is at least the length of STRING, copy STRING to
10416 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10417 decrease *LEFT. Otherwise raise an error. */
10420 remote_buffer_add_string (char **buffer, int *left, char *string)
10422 int len = strlen (string);
10425 error (_("Packet too long for target."));
10427 memcpy (*buffer, string, len);
10431 /* NUL-terminate the buffer as a convenience, if there is
10437 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10438 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10439 decrease *LEFT. Otherwise raise an error. */
10442 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10445 if (2 * len > *left)
10446 error (_("Packet too long for target."));
10448 bin2hex (bytes, *buffer, len);
10449 *buffer += 2 * len;
10452 /* NUL-terminate the buffer as a convenience, if there is
10458 /* If *LEFT is large enough, convert VALUE to hex and add it to
10459 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10460 decrease *LEFT. Otherwise raise an error. */
10463 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10465 int len = hexnumlen (value);
10468 error (_("Packet too long for target."));
10470 hexnumstr (*buffer, value);
10474 /* NUL-terminate the buffer as a convenience, if there is
10480 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10481 value, *REMOTE_ERRNO to the remote error number or zero if none
10482 was included, and *ATTACHMENT to point to the start of the annex
10483 if any. The length of the packet isn't needed here; there may
10484 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10486 Return 0 if the packet could be parsed, -1 if it could not. If
10487 -1 is returned, the other variables may not be initialized. */
10490 remote_hostio_parse_result (char *buffer, int *retcode,
10491 int *remote_errno, char **attachment)
10496 *attachment = NULL;
10498 if (buffer[0] != 'F')
10502 *retcode = strtol (&buffer[1], &p, 16);
10503 if (errno != 0 || p == &buffer[1])
10506 /* Check for ",errno". */
10510 *remote_errno = strtol (p + 1, &p2, 16);
10511 if (errno != 0 || p + 1 == p2)
10516 /* Check for ";attachment". If there is no attachment, the
10517 packet should end here. */
10520 *attachment = p + 1;
10523 else if (*p == '\0')
10529 /* Send a prepared I/O packet to the target and read its response.
10530 The prepared packet is in the global RS->BUF before this function
10531 is called, and the answer is there when we return.
10533 COMMAND_BYTES is the length of the request to send, which may include
10534 binary data. WHICH_PACKET is the packet configuration to check
10535 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10536 is set to the error number and -1 is returned. Otherwise the value
10537 returned by the function is returned.
10539 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10540 attachment is expected; an error will be reported if there's a
10541 mismatch. If one is found, *ATTACHMENT will be set to point into
10542 the packet buffer and *ATTACHMENT_LEN will be set to the
10543 attachment's length. */
10546 remote_hostio_send_command (int command_bytes, int which_packet,
10547 int *remote_errno, char **attachment,
10548 int *attachment_len)
10550 struct remote_state *rs = get_remote_state ();
10551 int ret, bytes_read;
10552 char *attachment_tmp;
10554 if (!rs->remote_desc
10555 || packet_support (which_packet) == PACKET_DISABLE)
10557 *remote_errno = FILEIO_ENOSYS;
10561 putpkt_binary (rs->buf, command_bytes);
10562 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10564 /* If it timed out, something is wrong. Don't try to parse the
10566 if (bytes_read < 0)
10568 *remote_errno = FILEIO_EINVAL;
10572 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10575 *remote_errno = FILEIO_EINVAL;
10577 case PACKET_UNKNOWN:
10578 *remote_errno = FILEIO_ENOSYS;
10584 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10587 *remote_errno = FILEIO_EINVAL;
10591 /* Make sure we saw an attachment if and only if we expected one. */
10592 if ((attachment_tmp == NULL && attachment != NULL)
10593 || (attachment_tmp != NULL && attachment == NULL))
10595 *remote_errno = FILEIO_EINVAL;
10599 /* If an attachment was found, it must point into the packet buffer;
10600 work out how many bytes there were. */
10601 if (attachment_tmp != NULL)
10603 *attachment = attachment_tmp;
10604 *attachment_len = bytes_read - (*attachment - rs->buf);
10610 /* Invalidate the readahead cache. */
10613 readahead_cache_invalidate (void)
10615 struct remote_state *rs = get_remote_state ();
10617 rs->readahead_cache.fd = -1;
10620 /* Invalidate the readahead cache if it is holding data for FD. */
10623 readahead_cache_invalidate_fd (int fd)
10625 struct remote_state *rs = get_remote_state ();
10627 if (rs->readahead_cache.fd == fd)
10628 rs->readahead_cache.fd = -1;
10631 /* Set the filesystem remote_hostio functions that take FILENAME
10632 arguments will use. Return 0 on success, or -1 if an error
10633 occurs (and set *REMOTE_ERRNO). */
10636 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10638 struct remote_state *rs = get_remote_state ();
10639 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10641 int left = get_remote_packet_size () - 1;
10645 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10648 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10651 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10653 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10654 remote_buffer_add_string (&p, &left, arg);
10656 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10657 remote_errno, NULL, NULL);
10659 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10663 rs->fs_pid = required_pid;
10668 /* Implementation of to_fileio_open. */
10671 remote_hostio_open (struct target_ops *self,
10672 struct inferior *inf, const char *filename,
10673 int flags, int mode, int warn_if_slow,
10676 struct remote_state *rs = get_remote_state ();
10678 int left = get_remote_packet_size () - 1;
10682 static int warning_issued = 0;
10684 printf_unfiltered (_("Reading %s from remote target...\n"),
10687 if (!warning_issued)
10689 warning (_("File transfers from remote targets can be slow."
10690 " Use \"set sysroot\" to access files locally"
10692 warning_issued = 1;
10696 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10699 remote_buffer_add_string (&p, &left, "vFile:open:");
10701 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10702 strlen (filename));
10703 remote_buffer_add_string (&p, &left, ",");
10705 remote_buffer_add_int (&p, &left, flags);
10706 remote_buffer_add_string (&p, &left, ",");
10708 remote_buffer_add_int (&p, &left, mode);
10710 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10711 remote_errno, NULL, NULL);
10714 /* Implementation of to_fileio_pwrite. */
10717 remote_hostio_pwrite (struct target_ops *self,
10718 int fd, const gdb_byte *write_buf, int len,
10719 ULONGEST offset, int *remote_errno)
10721 struct remote_state *rs = get_remote_state ();
10723 int left = get_remote_packet_size ();
10726 readahead_cache_invalidate_fd (fd);
10728 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10730 remote_buffer_add_int (&p, &left, fd);
10731 remote_buffer_add_string (&p, &left, ",");
10733 remote_buffer_add_int (&p, &left, offset);
10734 remote_buffer_add_string (&p, &left, ",");
10736 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10737 get_remote_packet_size () - (p - rs->buf));
10739 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10740 remote_errno, NULL, NULL);
10743 /* Helper for the implementation of to_fileio_pread. Read the file
10744 from the remote side with vFile:pread. */
10747 remote_hostio_pread_vFile (struct target_ops *self,
10748 int fd, gdb_byte *read_buf, int len,
10749 ULONGEST offset, int *remote_errno)
10751 struct remote_state *rs = get_remote_state ();
10754 int left = get_remote_packet_size ();
10755 int ret, attachment_len;
10758 remote_buffer_add_string (&p, &left, "vFile:pread:");
10760 remote_buffer_add_int (&p, &left, fd);
10761 remote_buffer_add_string (&p, &left, ",");
10763 remote_buffer_add_int (&p, &left, len);
10764 remote_buffer_add_string (&p, &left, ",");
10766 remote_buffer_add_int (&p, &left, offset);
10768 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10769 remote_errno, &attachment,
10775 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10777 if (read_len != ret)
10778 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10783 /* Serve pread from the readahead cache. Returns number of bytes
10784 read, or 0 if the request can't be served from the cache. */
10787 remote_hostio_pread_from_cache (struct remote_state *rs,
10788 int fd, gdb_byte *read_buf, size_t len,
10791 struct readahead_cache *cache = &rs->readahead_cache;
10793 if (cache->fd == fd
10794 && cache->offset <= offset
10795 && offset < cache->offset + cache->bufsize)
10797 ULONGEST max = cache->offset + cache->bufsize;
10799 if (offset + len > max)
10800 len = max - offset;
10802 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10809 /* Implementation of to_fileio_pread. */
10812 remote_hostio_pread (struct target_ops *self,
10813 int fd, gdb_byte *read_buf, int len,
10814 ULONGEST offset, int *remote_errno)
10817 struct remote_state *rs = get_remote_state ();
10818 struct readahead_cache *cache = &rs->readahead_cache;
10820 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10823 cache->hit_count++;
10826 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10827 pulongest (cache->hit_count));
10831 cache->miss_count++;
10833 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10834 pulongest (cache->miss_count));
10837 cache->offset = offset;
10838 cache->bufsize = get_remote_packet_size ();
10839 cache->buf = xrealloc (cache->buf, cache->bufsize);
10841 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10842 cache->offset, remote_errno);
10845 readahead_cache_invalidate_fd (fd);
10849 cache->bufsize = ret;
10850 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10853 /* Implementation of to_fileio_close. */
10856 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
10858 struct remote_state *rs = get_remote_state ();
10860 int left = get_remote_packet_size () - 1;
10862 readahead_cache_invalidate_fd (fd);
10864 remote_buffer_add_string (&p, &left, "vFile:close:");
10866 remote_buffer_add_int (&p, &left, fd);
10868 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10869 remote_errno, NULL, NULL);
10872 /* Implementation of to_fileio_unlink. */
10875 remote_hostio_unlink (struct target_ops *self,
10876 struct inferior *inf, const char *filename,
10879 struct remote_state *rs = get_remote_state ();
10881 int left = get_remote_packet_size () - 1;
10883 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10886 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10888 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10889 strlen (filename));
10891 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10892 remote_errno, NULL, NULL);
10895 /* Implementation of to_fileio_readlink. */
10898 remote_hostio_readlink (struct target_ops *self,
10899 struct inferior *inf, const char *filename,
10902 struct remote_state *rs = get_remote_state ();
10905 int left = get_remote_packet_size ();
10906 int len, attachment_len;
10910 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10913 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10915 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10916 strlen (filename));
10918 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10919 remote_errno, &attachment,
10925 ret = xmalloc (len + 1);
10927 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10928 (gdb_byte *) ret, len);
10929 if (read_len != len)
10930 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10936 /* Implementation of to_fileio_fstat. */
10939 remote_hostio_fstat (struct target_ops *self,
10940 int fd, struct stat *st,
10943 struct remote_state *rs = get_remote_state ();
10945 int left = get_remote_packet_size ();
10946 int attachment_len, ret;
10948 struct fio_stat fst;
10951 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10953 remote_buffer_add_int (&p, &left, fd);
10955 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10956 remote_errno, &attachment,
10960 if (*remote_errno != FILEIO_ENOSYS)
10963 /* Strictly we should return -1, ENOSYS here, but when
10964 "set sysroot remote:" was implemented in August 2008
10965 BFD's need for a stat function was sidestepped with
10966 this hack. This was not remedied until March 2015
10967 so we retain the previous behavior to avoid breaking
10970 Note that the memset is a March 2015 addition; older
10971 GDBs set st_size *and nothing else* so the structure
10972 would have garbage in all other fields. This might
10973 break something but retaining the previous behavior
10974 here would be just too wrong. */
10976 memset (st, 0, sizeof (struct stat));
10977 st->st_size = INT_MAX;
10981 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10982 (gdb_byte *) &fst, sizeof (fst));
10984 if (read_len != ret)
10985 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10987 if (read_len != sizeof (fst))
10988 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10989 read_len, (int) sizeof (fst));
10991 remote_fileio_to_host_stat (&fst, st);
10996 /* Implementation of to_filesystem_is_local. */
10999 remote_filesystem_is_local (struct target_ops *self)
11001 /* Valgrind GDB presents itself as a remote target but works
11002 on the local filesystem: it does not implement remote get
11003 and users are not expected to set a sysroot. To handle
11004 this case we treat the remote filesystem as local if the
11005 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11006 does not support vFile:open. */
11007 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11009 enum packet_support ps = packet_support (PACKET_vFile_open);
11011 if (ps == PACKET_SUPPORT_UNKNOWN)
11013 int fd, remote_errno;
11015 /* Try opening a file to probe support. The supplied
11016 filename is irrelevant, we only care about whether
11017 the stub recognizes the packet or not. */
11018 fd = remote_hostio_open (self, NULL, "just probing",
11019 FILEIO_O_RDONLY, 0700, 0,
11023 remote_hostio_close (self, fd, &remote_errno);
11025 ps = packet_support (PACKET_vFile_open);
11028 if (ps == PACKET_DISABLE)
11030 static int warning_issued = 0;
11032 if (!warning_issued)
11034 warning (_("remote target does not support file"
11035 " transfer, attempting to access files"
11036 " from local filesystem."));
11037 warning_issued = 1;
11048 remote_fileio_errno_to_host (int errnum)
11054 case FILEIO_ENOENT:
11062 case FILEIO_EACCES:
11064 case FILEIO_EFAULT:
11068 case FILEIO_EEXIST:
11070 case FILEIO_ENODEV:
11072 case FILEIO_ENOTDIR:
11074 case FILEIO_EISDIR:
11076 case FILEIO_EINVAL:
11078 case FILEIO_ENFILE:
11080 case FILEIO_EMFILE:
11084 case FILEIO_ENOSPC:
11086 case FILEIO_ESPIPE:
11090 case FILEIO_ENOSYS:
11092 case FILEIO_ENAMETOOLONG:
11093 return ENAMETOOLONG;
11099 remote_hostio_error (int errnum)
11101 int host_error = remote_fileio_errno_to_host (errnum);
11103 if (host_error == -1)
11104 error (_("Unknown remote I/O error %d"), errnum);
11106 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11110 remote_hostio_close_cleanup (void *opaque)
11112 int fd = *(int *) opaque;
11115 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11119 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11121 struct cleanup *back_to, *close_cleanup;
11122 int retcode, fd, remote_errno, bytes, io_size;
11125 int bytes_in_buffer;
11128 struct remote_state *rs = get_remote_state ();
11130 if (!rs->remote_desc)
11131 error (_("command can only be used with remote target"));
11133 file = gdb_fopen_cloexec (local_file, "rb");
11135 perror_with_name (local_file);
11136 back_to = make_cleanup_fclose (file);
11138 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11139 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11141 0700, 0, &remote_errno);
11143 remote_hostio_error (remote_errno);
11145 /* Send up to this many bytes at once. They won't all fit in the
11146 remote packet limit, so we'll transfer slightly fewer. */
11147 io_size = get_remote_packet_size ();
11148 buffer = xmalloc (io_size);
11149 make_cleanup (xfree, buffer);
11151 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11153 bytes_in_buffer = 0;
11156 while (bytes_in_buffer || !saw_eof)
11160 bytes = fread (buffer + bytes_in_buffer, 1,
11161 io_size - bytes_in_buffer,
11166 error (_("Error reading %s."), local_file);
11169 /* EOF. Unless there is something still in the
11170 buffer from the last iteration, we are done. */
11172 if (bytes_in_buffer == 0)
11180 bytes += bytes_in_buffer;
11181 bytes_in_buffer = 0;
11183 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11185 offset, &remote_errno);
11188 remote_hostio_error (remote_errno);
11189 else if (retcode == 0)
11190 error (_("Remote write of %d bytes returned 0!"), bytes);
11191 else if (retcode < bytes)
11193 /* Short write. Save the rest of the read data for the next
11195 bytes_in_buffer = bytes - retcode;
11196 memmove (buffer, buffer + retcode, bytes_in_buffer);
11202 discard_cleanups (close_cleanup);
11203 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11204 remote_hostio_error (remote_errno);
11207 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11208 do_cleanups (back_to);
11212 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11214 struct cleanup *back_to, *close_cleanup;
11215 int fd, remote_errno, bytes, io_size;
11219 struct remote_state *rs = get_remote_state ();
11221 if (!rs->remote_desc)
11222 error (_("command can only be used with remote target"));
11224 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11225 remote_file, FILEIO_O_RDONLY, 0, 0,
11228 remote_hostio_error (remote_errno);
11230 file = gdb_fopen_cloexec (local_file, "wb");
11232 perror_with_name (local_file);
11233 back_to = make_cleanup_fclose (file);
11235 /* Send up to this many bytes at once. They won't all fit in the
11236 remote packet limit, so we'll transfer slightly fewer. */
11237 io_size = get_remote_packet_size ();
11238 buffer = xmalloc (io_size);
11239 make_cleanup (xfree, buffer);
11241 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11246 bytes = remote_hostio_pread (find_target_at (process_stratum),
11247 fd, buffer, io_size, offset, &remote_errno);
11249 /* Success, but no bytes, means end-of-file. */
11252 remote_hostio_error (remote_errno);
11256 bytes = fwrite (buffer, 1, bytes, file);
11258 perror_with_name (local_file);
11261 discard_cleanups (close_cleanup);
11262 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11263 remote_hostio_error (remote_errno);
11266 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11267 do_cleanups (back_to);
11271 remote_file_delete (const char *remote_file, int from_tty)
11273 int retcode, remote_errno;
11274 struct remote_state *rs = get_remote_state ();
11276 if (!rs->remote_desc)
11277 error (_("command can only be used with remote target"));
11279 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11280 NULL, remote_file, &remote_errno);
11282 remote_hostio_error (remote_errno);
11285 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11289 remote_put_command (char *args, int from_tty)
11291 struct cleanup *back_to;
11295 error_no_arg (_("file to put"));
11297 argv = gdb_buildargv (args);
11298 back_to = make_cleanup_freeargv (argv);
11299 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11300 error (_("Invalid parameters to remote put"));
11302 remote_file_put (argv[0], argv[1], from_tty);
11304 do_cleanups (back_to);
11308 remote_get_command (char *args, int from_tty)
11310 struct cleanup *back_to;
11314 error_no_arg (_("file to get"));
11316 argv = gdb_buildargv (args);
11317 back_to = make_cleanup_freeargv (argv);
11318 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11319 error (_("Invalid parameters to remote get"));
11321 remote_file_get (argv[0], argv[1], from_tty);
11323 do_cleanups (back_to);
11327 remote_delete_command (char *args, int from_tty)
11329 struct cleanup *back_to;
11333 error_no_arg (_("file to delete"));
11335 argv = gdb_buildargv (args);
11336 back_to = make_cleanup_freeargv (argv);
11337 if (argv[0] == NULL || argv[1] != NULL)
11338 error (_("Invalid parameters to remote delete"));
11340 remote_file_delete (argv[0], from_tty);
11342 do_cleanups (back_to);
11346 remote_command (char *args, int from_tty)
11348 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11352 remote_can_execute_reverse (struct target_ops *self)
11354 if (packet_support (PACKET_bs) == PACKET_ENABLE
11355 || packet_support (PACKET_bc) == PACKET_ENABLE)
11362 remote_supports_non_stop (struct target_ops *self)
11368 remote_supports_disable_randomization (struct target_ops *self)
11370 /* Only supported in extended mode. */
11375 remote_supports_multi_process (struct target_ops *self)
11377 struct remote_state *rs = get_remote_state ();
11379 /* Only extended-remote handles being attached to multiple
11380 processes, even though plain remote can use the multi-process
11381 thread id extensions, so that GDB knows the target process's
11383 return rs->extended && remote_multi_process_p (rs);
11387 remote_supports_cond_tracepoints (void)
11389 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11393 remote_supports_cond_breakpoints (struct target_ops *self)
11395 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11399 remote_supports_fast_tracepoints (void)
11401 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11405 remote_supports_static_tracepoints (void)
11407 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11411 remote_supports_install_in_trace (void)
11413 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11417 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11419 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11424 remote_supports_string_tracing (struct target_ops *self)
11426 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11430 remote_can_run_breakpoint_commands (struct target_ops *self)
11432 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11436 remote_trace_init (struct target_ops *self)
11439 remote_get_noisy_reply (&target_buf, &target_buf_size);
11440 if (strcmp (target_buf, "OK") != 0)
11441 error (_("Target does not support this command."));
11444 static void free_actions_list (char **actions_list);
11445 static void free_actions_list_cleanup_wrapper (void *);
11447 free_actions_list_cleanup_wrapper (void *al)
11449 free_actions_list (al);
11453 free_actions_list (char **actions_list)
11457 if (actions_list == 0)
11460 for (ndx = 0; actions_list[ndx]; ndx++)
11461 xfree (actions_list[ndx]);
11463 xfree (actions_list);
11466 /* Recursive routine to walk through command list including loops, and
11467 download packets for each command. */
11470 remote_download_command_source (int num, ULONGEST addr,
11471 struct command_line *cmds)
11473 struct remote_state *rs = get_remote_state ();
11474 struct command_line *cmd;
11476 for (cmd = cmds; cmd; cmd = cmd->next)
11478 QUIT; /* Allow user to bail out with ^C. */
11479 strcpy (rs->buf, "QTDPsrc:");
11480 encode_source_string (num, addr, "cmd", cmd->line,
11481 rs->buf + strlen (rs->buf),
11482 rs->buf_size - strlen (rs->buf));
11484 remote_get_noisy_reply (&target_buf, &target_buf_size);
11485 if (strcmp (target_buf, "OK"))
11486 warning (_("Target does not support source download."));
11488 if (cmd->control_type == while_control
11489 || cmd->control_type == while_stepping_control)
11491 remote_download_command_source (num, addr, *cmd->body_list);
11493 QUIT; /* Allow user to bail out with ^C. */
11494 strcpy (rs->buf, "QTDPsrc:");
11495 encode_source_string (num, addr, "cmd", "end",
11496 rs->buf + strlen (rs->buf),
11497 rs->buf_size - strlen (rs->buf));
11499 remote_get_noisy_reply (&target_buf, &target_buf_size);
11500 if (strcmp (target_buf, "OK"))
11501 warning (_("Target does not support source download."));
11507 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11509 #define BUF_SIZE 2048
11513 char buf[BUF_SIZE];
11514 char **tdp_actions;
11515 char **stepping_actions;
11517 struct cleanup *old_chain = NULL;
11518 struct agent_expr *aexpr;
11519 struct cleanup *aexpr_chain = NULL;
11521 struct breakpoint *b = loc->owner;
11522 struct tracepoint *t = (struct tracepoint *) b;
11524 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11525 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11527 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11530 tpaddr = loc->address;
11531 sprintf_vma (addrbuf, tpaddr);
11532 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11533 addrbuf, /* address */
11534 (b->enable_state == bp_enabled ? 'E' : 'D'),
11535 t->step_count, t->pass_count);
11536 /* Fast tracepoints are mostly handled by the target, but we can
11537 tell the target how big of an instruction block should be moved
11539 if (b->type == bp_fast_tracepoint)
11541 /* Only test for support at download time; we may not know
11542 target capabilities at definition time. */
11543 if (remote_supports_fast_tracepoints ())
11545 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11547 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11548 gdb_insn_length (loc->gdbarch, tpaddr));
11550 /* If it passed validation at definition but fails now,
11551 something is very wrong. */
11552 internal_error (__FILE__, __LINE__,
11553 _("Fast tracepoint not "
11554 "valid during download"));
11557 /* Fast tracepoints are functionally identical to regular
11558 tracepoints, so don't take lack of support as a reason to
11559 give up on the trace run. */
11560 warning (_("Target does not support fast tracepoints, "
11561 "downloading %d as regular tracepoint"), b->number);
11563 else if (b->type == bp_static_tracepoint)
11565 /* Only test for support at download time; we may not know
11566 target capabilities at definition time. */
11567 if (remote_supports_static_tracepoints ())
11569 struct static_tracepoint_marker marker;
11571 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11572 strcat (buf, ":S");
11574 error (_("Static tracepoint not valid during download"));
11577 /* Fast tracepoints are functionally identical to regular
11578 tracepoints, so don't take lack of support as a reason
11579 to give up on the trace run. */
11580 error (_("Target does not support static tracepoints"));
11582 /* If the tracepoint has a conditional, make it into an agent
11583 expression and append to the definition. */
11586 /* Only test support at download time, we may not know target
11587 capabilities at definition time. */
11588 if (remote_supports_cond_tracepoints ())
11590 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11591 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11592 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11594 pkt = buf + strlen (buf);
11595 for (ndx = 0; ndx < aexpr->len; ++ndx)
11596 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11598 do_cleanups (aexpr_chain);
11601 warning (_("Target does not support conditional tracepoints, "
11602 "ignoring tp %d cond"), b->number);
11605 if (b->commands || *default_collect)
11608 remote_get_noisy_reply (&target_buf, &target_buf_size);
11609 if (strcmp (target_buf, "OK"))
11610 error (_("Target does not support tracepoints."));
11612 /* do_single_steps (t); */
11615 for (ndx = 0; tdp_actions[ndx]; ndx++)
11617 QUIT; /* Allow user to bail out with ^C. */
11618 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11619 b->number, addrbuf, /* address */
11621 ((tdp_actions[ndx + 1] || stepping_actions)
11624 remote_get_noisy_reply (&target_buf,
11626 if (strcmp (target_buf, "OK"))
11627 error (_("Error on target while setting tracepoints."));
11630 if (stepping_actions)
11632 for (ndx = 0; stepping_actions[ndx]; ndx++)
11634 QUIT; /* Allow user to bail out with ^C. */
11635 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11636 b->number, addrbuf, /* address */
11637 ((ndx == 0) ? "S" : ""),
11638 stepping_actions[ndx],
11639 (stepping_actions[ndx + 1] ? "-" : ""));
11641 remote_get_noisy_reply (&target_buf,
11643 if (strcmp (target_buf, "OK"))
11644 error (_("Error on target while setting tracepoints."));
11648 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11650 if (b->location != NULL)
11652 strcpy (buf, "QTDPsrc:");
11653 encode_source_string (b->number, loc->address, "at",
11654 event_location_to_string (b->location),
11655 buf + strlen (buf), 2048 - strlen (buf));
11657 remote_get_noisy_reply (&target_buf, &target_buf_size);
11658 if (strcmp (target_buf, "OK"))
11659 warning (_("Target does not support source download."));
11661 if (b->cond_string)
11663 strcpy (buf, "QTDPsrc:");
11664 encode_source_string (b->number, loc->address,
11665 "cond", b->cond_string, buf + strlen (buf),
11666 2048 - strlen (buf));
11668 remote_get_noisy_reply (&target_buf, &target_buf_size);
11669 if (strcmp (target_buf, "OK"))
11670 warning (_("Target does not support source download."));
11672 remote_download_command_source (b->number, loc->address,
11673 breakpoint_commands (b));
11676 do_cleanups (old_chain);
11680 remote_can_download_tracepoint (struct target_ops *self)
11682 struct remote_state *rs = get_remote_state ();
11683 struct trace_status *ts;
11686 /* Don't try to install tracepoints until we've relocated our
11687 symbols, and fetched and merged the target's tracepoint list with
11689 if (rs->starting_up)
11692 ts = current_trace_status ();
11693 status = remote_get_trace_status (self, ts);
11695 if (status == -1 || !ts->running_known || !ts->running)
11698 /* If we are in a tracing experiment, but remote stub doesn't support
11699 installing tracepoint in trace, we have to return. */
11700 if (!remote_supports_install_in_trace ())
11708 remote_download_trace_state_variable (struct target_ops *self,
11709 struct trace_state_variable *tsv)
11711 struct remote_state *rs = get_remote_state ();
11714 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11715 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11717 p = rs->buf + strlen (rs->buf);
11718 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11719 error (_("Trace state variable name too long for tsv definition packet"));
11720 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11723 remote_get_noisy_reply (&target_buf, &target_buf_size);
11724 if (*target_buf == '\0')
11725 error (_("Target does not support this command."));
11726 if (strcmp (target_buf, "OK") != 0)
11727 error (_("Error on target while downloading trace state variable."));
11731 remote_enable_tracepoint (struct target_ops *self,
11732 struct bp_location *location)
11734 struct remote_state *rs = get_remote_state ();
11737 sprintf_vma (addr_buf, location->address);
11738 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11739 location->owner->number, addr_buf);
11741 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11742 if (*rs->buf == '\0')
11743 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11744 if (strcmp (rs->buf, "OK") != 0)
11745 error (_("Error on target while enabling tracepoint."));
11749 remote_disable_tracepoint (struct target_ops *self,
11750 struct bp_location *location)
11752 struct remote_state *rs = get_remote_state ();
11755 sprintf_vma (addr_buf, location->address);
11756 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11757 location->owner->number, addr_buf);
11759 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11760 if (*rs->buf == '\0')
11761 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11762 if (strcmp (rs->buf, "OK") != 0)
11763 error (_("Error on target while disabling tracepoint."));
11767 remote_trace_set_readonly_regions (struct target_ops *self)
11771 bfd_size_type size;
11777 return; /* No information to give. */
11779 strcpy (target_buf, "QTro");
11780 offset = strlen (target_buf);
11781 for (s = exec_bfd->sections; s; s = s->next)
11783 char tmp1[40], tmp2[40];
11786 if ((s->flags & SEC_LOAD) == 0 ||
11787 /* (s->flags & SEC_CODE) == 0 || */
11788 (s->flags & SEC_READONLY) == 0)
11792 vma = bfd_get_section_vma (abfd, s);
11793 size = bfd_get_section_size (s);
11794 sprintf_vma (tmp1, vma);
11795 sprintf_vma (tmp2, vma + size);
11796 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11797 if (offset + sec_length + 1 > target_buf_size)
11799 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
11801 Too many sections for read-only sections definition packet."));
11804 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11806 offset += sec_length;
11810 putpkt (target_buf);
11811 getpkt (&target_buf, &target_buf_size, 0);
11816 remote_trace_start (struct target_ops *self)
11818 putpkt ("QTStart");
11819 remote_get_noisy_reply (&target_buf, &target_buf_size);
11820 if (*target_buf == '\0')
11821 error (_("Target does not support this command."));
11822 if (strcmp (target_buf, "OK") != 0)
11823 error (_("Bogus reply from target: %s"), target_buf);
11827 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11829 /* Initialize it just to avoid a GCC false warning. */
11831 /* FIXME we need to get register block size some other way. */
11832 extern int trace_regblock_size;
11833 enum packet_result result;
11835 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11838 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11840 putpkt ("qTStatus");
11844 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11846 CATCH (ex, RETURN_MASK_ERROR)
11848 if (ex.error != TARGET_CLOSE_ERROR)
11850 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11853 throw_exception (ex);
11857 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11859 /* If the remote target doesn't do tracing, flag it. */
11860 if (result == PACKET_UNKNOWN)
11863 /* We're working with a live target. */
11864 ts->filename = NULL;
11867 error (_("Bogus trace status reply from target: %s"), target_buf);
11869 /* Function 'parse_trace_status' sets default value of each field of
11870 'ts' at first, so we don't have to do it here. */
11871 parse_trace_status (p, ts);
11873 return ts->running;
11877 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
11878 struct uploaded_tp *utp)
11880 struct remote_state *rs = get_remote_state ();
11882 struct bp_location *loc;
11883 struct tracepoint *tp = (struct tracepoint *) bp;
11884 size_t size = get_remote_packet_size ();
11888 tp->base.hit_count = 0;
11889 tp->traceframe_usage = 0;
11890 for (loc = tp->base.loc; loc; loc = loc->next)
11892 /* If the tracepoint was never downloaded, don't go asking for
11894 if (tp->number_on_target == 0)
11896 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11897 phex_nz (loc->address, 0));
11899 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11900 if (reply && *reply)
11903 parse_tracepoint_status (reply + 1, bp, utp);
11909 utp->hit_count = 0;
11910 utp->traceframe_usage = 0;
11911 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11912 phex_nz (utp->addr, 0));
11914 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11915 if (reply && *reply)
11918 parse_tracepoint_status (reply + 1, bp, utp);
11924 remote_trace_stop (struct target_ops *self)
11927 remote_get_noisy_reply (&target_buf, &target_buf_size);
11928 if (*target_buf == '\0')
11929 error (_("Target does not support this command."));
11930 if (strcmp (target_buf, "OK") != 0)
11931 error (_("Bogus reply from target: %s"), target_buf);
11935 remote_trace_find (struct target_ops *self,
11936 enum trace_find_type type, int num,
11937 CORE_ADDR addr1, CORE_ADDR addr2,
11940 struct remote_state *rs = get_remote_state ();
11941 char *endbuf = rs->buf + get_remote_packet_size ();
11943 int target_frameno = -1, target_tracept = -1;
11945 /* Lookups other than by absolute frame number depend on the current
11946 trace selected, so make sure it is correct on the remote end
11948 if (type != tfind_number)
11949 set_remote_traceframe ();
11952 strcpy (p, "QTFrame:");
11953 p = strchr (p, '\0');
11957 xsnprintf (p, endbuf - p, "%x", num);
11960 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11963 xsnprintf (p, endbuf - p, "tdp:%x", num);
11966 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11967 phex_nz (addr2, 0));
11969 case tfind_outside:
11970 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11971 phex_nz (addr2, 0));
11974 error (_("Unknown trace find type %d"), type);
11978 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11979 if (*reply == '\0')
11980 error (_("Target does not support this command."));
11982 while (reply && *reply)
11987 target_frameno = (int) strtol (p, &reply, 16);
11989 error (_("Unable to parse trace frame number"));
11990 /* Don't update our remote traceframe number cache on failure
11991 to select a remote traceframe. */
11992 if (target_frameno == -1)
11997 target_tracept = (int) strtol (p, &reply, 16);
11999 error (_("Unable to parse tracepoint number"));
12001 case 'O': /* "OK"? */
12002 if (reply[1] == 'K' && reply[2] == '\0')
12005 error (_("Bogus reply from target: %s"), reply);
12008 error (_("Bogus reply from target: %s"), reply);
12011 *tpp = target_tracept;
12013 rs->remote_traceframe_number = target_frameno;
12014 return target_frameno;
12018 remote_get_trace_state_variable_value (struct target_ops *self,
12019 int tsvnum, LONGEST *val)
12021 struct remote_state *rs = get_remote_state ();
12025 set_remote_traceframe ();
12027 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12029 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12030 if (reply && *reply)
12034 unpack_varlen_hex (reply + 1, &uval);
12035 *val = (LONGEST) uval;
12043 remote_save_trace_data (struct target_ops *self, const char *filename)
12045 struct remote_state *rs = get_remote_state ();
12049 strcpy (p, "QTSave:");
12051 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12052 error (_("Remote file name too long for trace save packet"));
12053 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12056 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12057 if (*reply == '\0')
12058 error (_("Target does not support this command."));
12059 if (strcmp (reply, "OK") != 0)
12060 error (_("Bogus reply from target: %s"), reply);
12064 /* This is basically a memory transfer, but needs to be its own packet
12065 because we don't know how the target actually organizes its trace
12066 memory, plus we want to be able to ask for as much as possible, but
12067 not be unhappy if we don't get as much as we ask for. */
12070 remote_get_raw_trace_data (struct target_ops *self,
12071 gdb_byte *buf, ULONGEST offset, LONGEST len)
12073 struct remote_state *rs = get_remote_state ();
12079 strcpy (p, "qTBuffer:");
12081 p += hexnumstr (p, offset);
12083 p += hexnumstr (p, len);
12087 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12088 if (reply && *reply)
12090 /* 'l' by itself means we're at the end of the buffer and
12091 there is nothing more to get. */
12095 /* Convert the reply into binary. Limit the number of bytes to
12096 convert according to our passed-in buffer size, rather than
12097 what was returned in the packet; if the target is
12098 unexpectedly generous and gives us a bigger reply than we
12099 asked for, we don't want to crash. */
12100 rslt = hex2bin (target_buf, buf, len);
12104 /* Something went wrong, flag as an error. */
12109 remote_set_disconnected_tracing (struct target_ops *self, int val)
12111 struct remote_state *rs = get_remote_state ();
12113 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12117 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12119 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12120 if (*reply == '\0')
12121 error (_("Target does not support this command."));
12122 if (strcmp (reply, "OK") != 0)
12123 error (_("Bogus reply from target: %s"), reply);
12126 warning (_("Target does not support disconnected tracing."));
12130 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12132 struct thread_info *info = find_thread_ptid (ptid);
12134 if (info && info->priv)
12135 return info->priv->core;
12140 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12142 struct remote_state *rs = get_remote_state ();
12145 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12147 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12148 if (*reply == '\0')
12149 error (_("Target does not support this command."));
12150 if (strcmp (reply, "OK") != 0)
12151 error (_("Bogus reply from target: %s"), reply);
12154 static struct traceframe_info *
12155 remote_traceframe_info (struct target_ops *self)
12159 text = target_read_stralloc (¤t_target,
12160 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12163 struct traceframe_info *info;
12164 struct cleanup *back_to = make_cleanup (xfree, text);
12166 info = parse_traceframe_info (text);
12167 do_cleanups (back_to);
12174 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12175 instruction on which a fast tracepoint may be placed. Returns -1
12176 if the packet is not supported, and 0 if the minimum instruction
12177 length is unknown. */
12180 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12182 struct remote_state *rs = get_remote_state ();
12185 /* If we're not debugging a process yet, the IPA can't be
12187 if (!target_has_execution)
12190 /* Make sure the remote is pointing at the right process. */
12191 set_general_process ();
12193 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12195 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12196 if (*reply == '\0')
12200 ULONGEST min_insn_len;
12202 unpack_varlen_hex (reply, &min_insn_len);
12204 return (int) min_insn_len;
12209 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12211 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12213 struct remote_state *rs = get_remote_state ();
12214 char *buf = rs->buf;
12215 char *endbuf = rs->buf + get_remote_packet_size ();
12216 enum packet_result result;
12218 gdb_assert (val >= 0 || val == -1);
12219 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12220 /* Send -1 as literal "-1" to avoid host size dependency. */
12224 buf += hexnumstr (buf, (ULONGEST) -val);
12227 buf += hexnumstr (buf, (ULONGEST) val);
12230 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12231 result = packet_ok (rs->buf,
12232 &remote_protocol_packets[PACKET_QTBuffer_size]);
12234 if (result != PACKET_OK)
12235 warning (_("Bogus reply from target: %s"), rs->buf);
12240 remote_set_trace_notes (struct target_ops *self,
12241 const char *user, const char *notes,
12242 const char *stop_notes)
12244 struct remote_state *rs = get_remote_state ();
12246 char *buf = rs->buf;
12247 char *endbuf = rs->buf + get_remote_packet_size ();
12250 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12253 buf += xsnprintf (buf, endbuf - buf, "user:");
12254 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12260 buf += xsnprintf (buf, endbuf - buf, "notes:");
12261 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12267 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12268 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12272 /* Ensure the buffer is terminated. */
12276 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12277 if (*reply == '\0')
12280 if (strcmp (reply, "OK") != 0)
12281 error (_("Bogus reply from target: %s"), reply);
12287 remote_use_agent (struct target_ops *self, int use)
12289 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12291 struct remote_state *rs = get_remote_state ();
12293 /* If the stub supports QAgent. */
12294 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12296 getpkt (&rs->buf, &rs->buf_size, 0);
12298 if (strcmp (rs->buf, "OK") == 0)
12309 remote_can_use_agent (struct target_ops *self)
12311 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12314 struct btrace_target_info
12316 /* The ptid of the traced thread. */
12319 /* The obtained branch trace configuration. */
12320 struct btrace_config conf;
12323 /* Reset our idea of our target's btrace configuration. */
12326 remote_btrace_reset (void)
12328 struct remote_state *rs = get_remote_state ();
12330 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12333 /* Check whether the target supports branch tracing. */
12336 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12338 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12340 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12345 case BTRACE_FORMAT_NONE:
12348 case BTRACE_FORMAT_BTS:
12349 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12351 case BTRACE_FORMAT_PT:
12352 /* The trace is decoded on the host. Even if our target supports it,
12353 we still need to have libipt to decode the trace. */
12354 #if defined (HAVE_LIBIPT)
12355 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12356 #else /* !defined (HAVE_LIBIPT) */
12358 #endif /* !defined (HAVE_LIBIPT) */
12361 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12364 /* Synchronize the configuration with the target. */
12367 btrace_sync_conf (const struct btrace_config *conf)
12369 struct packet_config *packet;
12370 struct remote_state *rs;
12371 char *buf, *pos, *endbuf;
12373 rs = get_remote_state ();
12375 endbuf = buf + get_remote_packet_size ();
12377 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12378 if (packet_config_support (packet) == PACKET_ENABLE
12379 && conf->bts.size != rs->btrace_config.bts.size)
12382 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12386 getpkt (&buf, &rs->buf_size, 0);
12388 if (packet_ok (buf, packet) == PACKET_ERROR)
12390 if (buf[0] == 'E' && buf[1] == '.')
12391 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12393 error (_("Failed to configure the BTS buffer size."));
12396 rs->btrace_config.bts.size = conf->bts.size;
12399 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12400 if (packet_config_support (packet) == PACKET_ENABLE
12401 && conf->pt.size != rs->btrace_config.pt.size)
12404 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12408 getpkt (&buf, &rs->buf_size, 0);
12410 if (packet_ok (buf, packet) == PACKET_ERROR)
12412 if (buf[0] == 'E' && buf[1] == '.')
12413 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12415 error (_("Failed to configure the trace buffer size."));
12418 rs->btrace_config.pt.size = conf->pt.size;
12422 /* Read the current thread's btrace configuration from the target and
12423 store it into CONF. */
12426 btrace_read_config (struct btrace_config *conf)
12430 xml = target_read_stralloc (¤t_target,
12431 TARGET_OBJECT_BTRACE_CONF, "");
12434 struct cleanup *cleanup;
12436 cleanup = make_cleanup (xfree, xml);
12437 parse_xml_btrace_conf (conf, xml);
12438 do_cleanups (cleanup);
12442 /* Enable branch tracing. */
12444 static struct btrace_target_info *
12445 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12446 const struct btrace_config *conf)
12448 struct btrace_target_info *tinfo = NULL;
12449 struct packet_config *packet = NULL;
12450 struct remote_state *rs = get_remote_state ();
12451 char *buf = rs->buf;
12452 char *endbuf = rs->buf + get_remote_packet_size ();
12454 switch (conf->format)
12456 case BTRACE_FORMAT_BTS:
12457 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12460 case BTRACE_FORMAT_PT:
12461 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12465 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12466 error (_("Target does not support branch tracing."));
12468 btrace_sync_conf (conf);
12470 set_general_thread (ptid);
12472 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12474 getpkt (&rs->buf, &rs->buf_size, 0);
12476 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12478 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12479 error (_("Could not enable branch tracing for %s: %s"),
12480 target_pid_to_str (ptid), rs->buf + 2);
12482 error (_("Could not enable branch tracing for %s."),
12483 target_pid_to_str (ptid));
12486 tinfo = XCNEW (struct btrace_target_info);
12487 tinfo->ptid = ptid;
12489 /* If we fail to read the configuration, we lose some information, but the
12490 tracing itself is not impacted. */
12493 btrace_read_config (&tinfo->conf);
12495 CATCH (err, RETURN_MASK_ERROR)
12497 if (err.message != NULL)
12498 warning ("%s", err.message);
12505 /* Disable branch tracing. */
12508 remote_disable_btrace (struct target_ops *self,
12509 struct btrace_target_info *tinfo)
12511 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12512 struct remote_state *rs = get_remote_state ();
12513 char *buf = rs->buf;
12514 char *endbuf = rs->buf + get_remote_packet_size ();
12516 if (packet_config_support (packet) != PACKET_ENABLE)
12517 error (_("Target does not support branch tracing."));
12519 set_general_thread (tinfo->ptid);
12521 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12523 getpkt (&rs->buf, &rs->buf_size, 0);
12525 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12527 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12528 error (_("Could not disable branch tracing for %s: %s"),
12529 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12531 error (_("Could not disable branch tracing for %s."),
12532 target_pid_to_str (tinfo->ptid));
12538 /* Teardown branch tracing. */
12541 remote_teardown_btrace (struct target_ops *self,
12542 struct btrace_target_info *tinfo)
12544 /* We must not talk to the target during teardown. */
12548 /* Read the branch trace. */
12550 static enum btrace_error
12551 remote_read_btrace (struct target_ops *self,
12552 struct btrace_data *btrace,
12553 struct btrace_target_info *tinfo,
12554 enum btrace_read_type type)
12556 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12557 struct remote_state *rs = get_remote_state ();
12558 struct cleanup *cleanup;
12562 if (packet_config_support (packet) != PACKET_ENABLE)
12563 error (_("Target does not support branch tracing."));
12565 #if !defined(HAVE_LIBEXPAT)
12566 error (_("Cannot process branch tracing result. XML parsing not supported."));
12571 case BTRACE_READ_ALL:
12574 case BTRACE_READ_NEW:
12577 case BTRACE_READ_DELTA:
12581 internal_error (__FILE__, __LINE__,
12582 _("Bad branch tracing read type: %u."),
12583 (unsigned int) type);
12586 xml = target_read_stralloc (¤t_target,
12587 TARGET_OBJECT_BTRACE, annex);
12589 return BTRACE_ERR_UNKNOWN;
12591 cleanup = make_cleanup (xfree, xml);
12592 parse_xml_btrace (btrace, xml);
12593 do_cleanups (cleanup);
12595 return BTRACE_ERR_NONE;
12598 static const struct btrace_config *
12599 remote_btrace_conf (struct target_ops *self,
12600 const struct btrace_target_info *tinfo)
12602 return &tinfo->conf;
12606 remote_augmented_libraries_svr4_read (struct target_ops *self)
12608 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12612 /* Implementation of to_load. */
12615 remote_load (struct target_ops *self, const char *name, int from_tty)
12617 generic_load (name, from_tty);
12620 /* Accepts an integer PID; returns a string representing a file that
12621 can be opened on the remote side to get the symbols for the child
12622 process. Returns NULL if the operation is not supported. */
12625 remote_pid_to_exec_file (struct target_ops *self, int pid)
12627 static char *filename = NULL;
12628 struct inferior *inf;
12629 char *annex = NULL;
12631 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12634 if (filename != NULL)
12637 inf = find_inferior_pid (pid);
12639 internal_error (__FILE__, __LINE__,
12640 _("not currently attached to process %d"), pid);
12642 if (!inf->fake_pid_p)
12644 const int annex_size = 9;
12646 annex = alloca (annex_size);
12647 xsnprintf (annex, annex_size, "%x", pid);
12650 filename = target_read_stralloc (¤t_target,
12651 TARGET_OBJECT_EXEC_FILE, annex);
12657 init_remote_ops (void)
12659 remote_ops.to_shortname = "remote";
12660 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12661 remote_ops.to_doc =
12662 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12663 Specify the serial device it is connected to\n\
12664 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12665 remote_ops.to_open = remote_open;
12666 remote_ops.to_close = remote_close;
12667 remote_ops.to_detach = remote_detach;
12668 remote_ops.to_disconnect = remote_disconnect;
12669 remote_ops.to_resume = remote_resume;
12670 remote_ops.to_wait = remote_wait;
12671 remote_ops.to_fetch_registers = remote_fetch_registers;
12672 remote_ops.to_store_registers = remote_store_registers;
12673 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12674 remote_ops.to_files_info = remote_files_info;
12675 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12676 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12677 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12678 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12679 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12680 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12681 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12682 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12683 remote_ops.to_watchpoint_addr_within_range =
12684 remote_watchpoint_addr_within_range;
12685 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12686 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12687 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12688 remote_ops.to_region_ok_for_hw_watchpoint
12689 = remote_region_ok_for_hw_watchpoint;
12690 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12691 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12692 remote_ops.to_kill = remote_kill;
12693 remote_ops.to_load = remote_load;
12694 remote_ops.to_mourn_inferior = remote_mourn;
12695 remote_ops.to_pass_signals = remote_pass_signals;
12696 remote_ops.to_program_signals = remote_program_signals;
12697 remote_ops.to_thread_alive = remote_thread_alive;
12698 remote_ops.to_update_thread_list = remote_update_thread_list;
12699 remote_ops.to_pid_to_str = remote_pid_to_str;
12700 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12701 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12702 remote_ops.to_stop = remote_stop;
12703 remote_ops.to_interrupt = remote_interrupt;
12704 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12705 remote_ops.to_xfer_partial = remote_xfer_partial;
12706 remote_ops.to_rcmd = remote_rcmd;
12707 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12708 remote_ops.to_log_command = serial_log_command;
12709 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12710 remote_ops.to_stratum = process_stratum;
12711 remote_ops.to_has_all_memory = default_child_has_all_memory;
12712 remote_ops.to_has_memory = default_child_has_memory;
12713 remote_ops.to_has_stack = default_child_has_stack;
12714 remote_ops.to_has_registers = default_child_has_registers;
12715 remote_ops.to_has_execution = default_child_has_execution;
12716 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12717 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12718 remote_ops.to_magic = OPS_MAGIC;
12719 remote_ops.to_memory_map = remote_memory_map;
12720 remote_ops.to_flash_erase = remote_flash_erase;
12721 remote_ops.to_flash_done = remote_flash_done;
12722 remote_ops.to_read_description = remote_read_description;
12723 remote_ops.to_search_memory = remote_search_memory;
12724 remote_ops.to_can_async_p = remote_can_async_p;
12725 remote_ops.to_is_async_p = remote_is_async_p;
12726 remote_ops.to_async = remote_async;
12727 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12728 remote_ops.to_terminal_ours = remote_terminal_ours;
12729 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12730 remote_ops.to_supports_multi_process = remote_supports_multi_process;
12731 remote_ops.to_supports_disable_randomization
12732 = remote_supports_disable_randomization;
12733 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12734 remote_ops.to_fileio_open = remote_hostio_open;
12735 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12736 remote_ops.to_fileio_pread = remote_hostio_pread;
12737 remote_ops.to_fileio_fstat = remote_hostio_fstat;
12738 remote_ops.to_fileio_close = remote_hostio_close;
12739 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12740 remote_ops.to_fileio_readlink = remote_hostio_readlink;
12741 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12742 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12743 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12744 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12745 remote_ops.to_trace_init = remote_trace_init;
12746 remote_ops.to_download_tracepoint = remote_download_tracepoint;
12747 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12748 remote_ops.to_download_trace_state_variable
12749 = remote_download_trace_state_variable;
12750 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12751 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12752 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12753 remote_ops.to_trace_start = remote_trace_start;
12754 remote_ops.to_get_trace_status = remote_get_trace_status;
12755 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12756 remote_ops.to_trace_stop = remote_trace_stop;
12757 remote_ops.to_trace_find = remote_trace_find;
12758 remote_ops.to_get_trace_state_variable_value
12759 = remote_get_trace_state_variable_value;
12760 remote_ops.to_save_trace_data = remote_save_trace_data;
12761 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
12762 remote_ops.to_upload_trace_state_variables
12763 = remote_upload_trace_state_variables;
12764 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
12765 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
12766 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12767 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
12768 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
12769 remote_ops.to_set_trace_notes = remote_set_trace_notes;
12770 remote_ops.to_core_of_thread = remote_core_of_thread;
12771 remote_ops.to_verify_memory = remote_verify_memory;
12772 remote_ops.to_get_tib_address = remote_get_tib_address;
12773 remote_ops.to_set_permissions = remote_set_permissions;
12774 remote_ops.to_static_tracepoint_marker_at
12775 = remote_static_tracepoint_marker_at;
12776 remote_ops.to_static_tracepoint_markers_by_strid
12777 = remote_static_tracepoint_markers_by_strid;
12778 remote_ops.to_traceframe_info = remote_traceframe_info;
12779 remote_ops.to_use_agent = remote_use_agent;
12780 remote_ops.to_can_use_agent = remote_can_use_agent;
12781 remote_ops.to_supports_btrace = remote_supports_btrace;
12782 remote_ops.to_enable_btrace = remote_enable_btrace;
12783 remote_ops.to_disable_btrace = remote_disable_btrace;
12784 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12785 remote_ops.to_read_btrace = remote_read_btrace;
12786 remote_ops.to_btrace_conf = remote_btrace_conf;
12787 remote_ops.to_augmented_libraries_svr4_read =
12788 remote_augmented_libraries_svr4_read;
12791 /* Set up the extended remote vector by making a copy of the standard
12792 remote vector and adding to it. */
12795 init_extended_remote_ops (void)
12797 extended_remote_ops = remote_ops;
12799 extended_remote_ops.to_shortname = "extended-remote";
12800 extended_remote_ops.to_longname =
12801 "Extended remote serial target in gdb-specific protocol";
12802 extended_remote_ops.to_doc =
12803 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12804 Specify the serial device it is connected to (e.g. /dev/ttya).";
12805 extended_remote_ops.to_open = extended_remote_open;
12806 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12807 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
12808 extended_remote_ops.to_detach = extended_remote_detach;
12809 extended_remote_ops.to_attach = extended_remote_attach;
12810 extended_remote_ops.to_post_attach = extended_remote_post_attach;
12811 extended_remote_ops.to_kill = extended_remote_kill;
12812 extended_remote_ops.to_supports_disable_randomization
12813 = extended_remote_supports_disable_randomization;
12814 extended_remote_ops.to_follow_fork = remote_follow_fork;
12815 extended_remote_ops.to_follow_exec = remote_follow_exec;
12816 extended_remote_ops.to_insert_fork_catchpoint
12817 = remote_insert_fork_catchpoint;
12818 extended_remote_ops.to_remove_fork_catchpoint
12819 = remote_remove_fork_catchpoint;
12820 extended_remote_ops.to_insert_vfork_catchpoint
12821 = remote_insert_vfork_catchpoint;
12822 extended_remote_ops.to_remove_vfork_catchpoint
12823 = remote_remove_vfork_catchpoint;
12824 extended_remote_ops.to_insert_exec_catchpoint
12825 = remote_insert_exec_catchpoint;
12826 extended_remote_ops.to_remove_exec_catchpoint
12827 = remote_remove_exec_catchpoint;
12831 remote_can_async_p (struct target_ops *ops)
12833 struct remote_state *rs = get_remote_state ();
12835 if (!target_async_permitted)
12836 /* We only enable async when the user specifically asks for it. */
12839 /* We're async whenever the serial device is. */
12840 return serial_can_async_p (rs->remote_desc);
12844 remote_is_async_p (struct target_ops *ops)
12846 struct remote_state *rs = get_remote_state ();
12848 if (!target_async_permitted)
12849 /* We only enable async when the user specifically asks for it. */
12852 /* We're async whenever the serial device is. */
12853 return serial_is_async_p (rs->remote_desc);
12856 /* Pass the SERIAL event on and up to the client. One day this code
12857 will be able to delay notifying the client of an event until the
12858 point where an entire packet has been received. */
12860 static serial_event_ftype remote_async_serial_handler;
12863 remote_async_serial_handler (struct serial *scb, void *context)
12865 struct remote_state *rs = context;
12867 /* Don't propogate error information up to the client. Instead let
12868 the client find out about the error by querying the target. */
12869 inferior_event_handler (INF_REG_EVENT, NULL);
12873 remote_async_inferior_event_handler (gdb_client_data data)
12875 inferior_event_handler (INF_REG_EVENT, NULL);
12879 remote_async (struct target_ops *ops, int enable)
12881 struct remote_state *rs = get_remote_state ();
12885 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
12887 /* If there are pending events in the stop reply queue tell the
12888 event loop to process them. */
12889 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12890 mark_async_event_handler (remote_async_inferior_event_token);
12894 serial_async (rs->remote_desc, NULL, NULL);
12895 clear_async_event_handler (remote_async_inferior_event_token);
12900 set_remote_cmd (char *args, int from_tty)
12902 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
12906 show_remote_cmd (char *args, int from_tty)
12908 /* We can't just use cmd_show_list here, because we want to skip
12909 the redundant "show remote Z-packet" and the legacy aliases. */
12910 struct cleanup *showlist_chain;
12911 struct cmd_list_element *list = remote_show_cmdlist;
12912 struct ui_out *uiout = current_uiout;
12914 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12915 for (; list != NULL; list = list->next)
12916 if (strcmp (list->name, "Z-packet") == 0)
12918 else if (list->type == not_set_cmd)
12919 /* Alias commands are exactly like the original, except they
12920 don't have the normal type. */
12924 struct cleanup *option_chain
12925 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
12927 ui_out_field_string (uiout, "name", list->name);
12928 ui_out_text (uiout, ": ");
12929 if (list->type == show_cmd)
12930 do_show_command ((char *) NULL, from_tty, list);
12932 cmd_func (list, NULL, from_tty);
12933 /* Close the tuple. */
12934 do_cleanups (option_chain);
12937 /* Close the tuple. */
12938 do_cleanups (showlist_chain);
12942 /* Function to be called whenever a new objfile (shlib) is detected. */
12944 remote_new_objfile (struct objfile *objfile)
12946 struct remote_state *rs = get_remote_state ();
12948 if (rs->remote_desc != 0) /* Have a remote connection. */
12949 remote_check_symbols ();
12952 /* Pull all the tracepoints defined on the target and create local
12953 data structures representing them. We don't want to create real
12954 tracepoints yet, we don't want to mess up the user's existing
12958 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
12960 struct remote_state *rs = get_remote_state ();
12963 /* Ask for a first packet of tracepoint definition. */
12965 getpkt (&rs->buf, &rs->buf_size, 0);
12967 while (*p && *p != 'l')
12969 parse_tracepoint_definition (p, utpp);
12970 /* Ask for another packet of tracepoint definition. */
12972 getpkt (&rs->buf, &rs->buf_size, 0);
12979 remote_upload_trace_state_variables (struct target_ops *self,
12980 struct uploaded_tsv **utsvp)
12982 struct remote_state *rs = get_remote_state ();
12985 /* Ask for a first packet of variable definition. */
12987 getpkt (&rs->buf, &rs->buf_size, 0);
12989 while (*p && *p != 'l')
12991 parse_tsv_definition (p, utsvp);
12992 /* Ask for another packet of variable definition. */
12994 getpkt (&rs->buf, &rs->buf_size, 0);
13000 /* The "set/show range-stepping" show hook. */
13003 show_range_stepping (struct ui_file *file, int from_tty,
13004 struct cmd_list_element *c,
13007 fprintf_filtered (file,
13008 _("Debugger's willingness to use range stepping "
13009 "is %s.\n"), value);
13012 /* The "set/show range-stepping" set hook. */
13015 set_range_stepping (char *ignore_args, int from_tty,
13016 struct cmd_list_element *c)
13018 struct remote_state *rs = get_remote_state ();
13020 /* Whene enabling, check whether range stepping is actually
13021 supported by the target, and warn if not. */
13022 if (use_range_stepping)
13024 if (rs->remote_desc != NULL)
13026 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13027 remote_vcont_probe (rs);
13029 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13030 && rs->supports_vCont.r)
13034 warning (_("Range stepping is not supported by the current target"));
13039 _initialize_remote (void)
13041 struct remote_state *rs;
13042 struct cmd_list_element *cmd;
13043 const char *cmd_name;
13045 /* architecture specific data */
13046 remote_gdbarch_data_handle =
13047 gdbarch_data_register_post_init (init_remote_state);
13048 remote_g_packet_data_handle =
13049 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13052 = register_program_space_data_with_cleanup (NULL,
13053 remote_pspace_data_cleanup);
13055 /* Initialize the per-target state. At the moment there is only one
13056 of these, not one per target. Only one target is active at a
13058 remote_state = new_remote_state ();
13060 init_remote_ops ();
13061 add_target (&remote_ops);
13063 init_extended_remote_ops ();
13064 add_target (&extended_remote_ops);
13066 /* Hook into new objfile notification. */
13067 observer_attach_new_objfile (remote_new_objfile);
13068 /* We're no longer interested in notification events of an inferior
13070 observer_attach_inferior_exit (discard_pending_stop_replies);
13072 /* Set up signal handlers. */
13073 async_sigint_remote_token =
13074 create_async_signal_handler (async_remote_interrupt, NULL);
13075 async_sigint_remote_twice_token =
13076 create_async_signal_handler (async_remote_interrupt_twice, NULL);
13079 init_remote_threadtests ();
13082 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13083 /* set/show remote ... */
13085 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13086 Remote protocol specific variables\n\
13087 Configure various remote-protocol specific variables such as\n\
13088 the packets being used"),
13089 &remote_set_cmdlist, "set remote ",
13090 0 /* allow-unknown */, &setlist);
13091 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13092 Remote protocol specific variables\n\
13093 Configure various remote-protocol specific variables such as\n\
13094 the packets being used"),
13095 &remote_show_cmdlist, "show remote ",
13096 0 /* allow-unknown */, &showlist);
13098 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13099 Compare section data on target to the exec file.\n\
13100 Argument is a single section name (default: all loaded sections).\n\
13101 To compare only read-only loaded sections, specify the -r option."),
13104 add_cmd ("packet", class_maintenance, packet_command, _("\
13105 Send an arbitrary packet to a remote target.\n\
13106 maintenance packet TEXT\n\
13107 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13108 this command sends the string TEXT to the inferior, and displays the\n\
13109 response packet. GDB supplies the initial `$' character, and the\n\
13110 terminating `#' character and checksum."),
13113 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13114 Set whether to send break if interrupted."), _("\
13115 Show whether to send break if interrupted."), _("\
13116 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13117 set_remotebreak, show_remotebreak,
13118 &setlist, &showlist);
13119 cmd_name = "remotebreak";
13120 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13121 deprecate_cmd (cmd, "set remote interrupt-sequence");
13122 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13123 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13124 deprecate_cmd (cmd, "show remote interrupt-sequence");
13126 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13127 interrupt_sequence_modes, &interrupt_sequence_mode,
13129 Set interrupt sequence to remote target."), _("\
13130 Show interrupt sequence to remote target."), _("\
13131 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13132 NULL, show_interrupt_sequence,
13133 &remote_set_cmdlist,
13134 &remote_show_cmdlist);
13136 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13137 &interrupt_on_connect, _("\
13138 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13139 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13140 If set, interrupt sequence is sent to remote target."),
13142 &remote_set_cmdlist, &remote_show_cmdlist);
13144 /* Install commands for configuring memory read/write packets. */
13146 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13147 Set the maximum number of bytes per memory write packet (deprecated)."),
13149 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13150 Show the maximum number of bytes per memory write packet (deprecated)."),
13152 add_cmd ("memory-write-packet-size", no_class,
13153 set_memory_write_packet_size, _("\
13154 Set the maximum number of bytes per memory-write packet.\n\
13155 Specify the number of bytes in a packet or 0 (zero) for the\n\
13156 default packet size. The actual limit is further reduced\n\
13157 dependent on the target. Specify ``fixed'' to disable the\n\
13158 further restriction and ``limit'' to enable that restriction."),
13159 &remote_set_cmdlist);
13160 add_cmd ("memory-read-packet-size", no_class,
13161 set_memory_read_packet_size, _("\
13162 Set the maximum number of bytes per memory-read packet.\n\
13163 Specify the number of bytes in a packet or 0 (zero) for the\n\
13164 default packet size. The actual limit is further reduced\n\
13165 dependent on the target. Specify ``fixed'' to disable the\n\
13166 further restriction and ``limit'' to enable that restriction."),
13167 &remote_set_cmdlist);
13168 add_cmd ("memory-write-packet-size", no_class,
13169 show_memory_write_packet_size,
13170 _("Show the maximum number of bytes per memory-write packet."),
13171 &remote_show_cmdlist);
13172 add_cmd ("memory-read-packet-size", no_class,
13173 show_memory_read_packet_size,
13174 _("Show the maximum number of bytes per memory-read packet."),
13175 &remote_show_cmdlist);
13177 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13178 &remote_hw_watchpoint_limit, _("\
13179 Set the maximum number of target hardware watchpoints."), _("\
13180 Show the maximum number of target hardware watchpoints."), _("\
13181 Specify a negative limit for unlimited."),
13182 NULL, NULL, /* FIXME: i18n: The maximum
13183 number of target hardware
13184 watchpoints is %s. */
13185 &remote_set_cmdlist, &remote_show_cmdlist);
13186 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13187 &remote_hw_watchpoint_length_limit, _("\
13188 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13189 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13190 Specify a negative limit for unlimited."),
13191 NULL, NULL, /* FIXME: i18n: The maximum
13192 length (in bytes) of a target
13193 hardware watchpoint is %s. */
13194 &remote_set_cmdlist, &remote_show_cmdlist);
13195 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13196 &remote_hw_breakpoint_limit, _("\
13197 Set the maximum number of target hardware breakpoints."), _("\
13198 Show the maximum number of target hardware breakpoints."), _("\
13199 Specify a negative limit for unlimited."),
13200 NULL, NULL, /* FIXME: i18n: The maximum
13201 number of target hardware
13202 breakpoints is %s. */
13203 &remote_set_cmdlist, &remote_show_cmdlist);
13205 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13206 &remote_address_size, _("\
13207 Set the maximum size of the address (in bits) in a memory packet."), _("\
13208 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13210 NULL, /* FIXME: i18n: */
13211 &setlist, &showlist);
13213 init_all_packet_configs ();
13215 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13216 "X", "binary-download", 1);
13218 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13219 "vCont", "verbose-resume", 0);
13221 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13222 "QPassSignals", "pass-signals", 0);
13224 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13225 "QProgramSignals", "program-signals", 0);
13227 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13228 "qSymbol", "symbol-lookup", 0);
13230 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13231 "P", "set-register", 1);
13233 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13234 "p", "fetch-register", 1);
13236 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13237 "Z0", "software-breakpoint", 0);
13239 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13240 "Z1", "hardware-breakpoint", 0);
13242 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13243 "Z2", "write-watchpoint", 0);
13245 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13246 "Z3", "read-watchpoint", 0);
13248 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13249 "Z4", "access-watchpoint", 0);
13251 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13252 "qXfer:auxv:read", "read-aux-vector", 0);
13254 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13255 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13257 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13258 "qXfer:features:read", "target-features", 0);
13260 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13261 "qXfer:libraries:read", "library-info", 0);
13263 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13264 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13266 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13267 "qXfer:memory-map:read", "memory-map", 0);
13269 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13270 "qXfer:spu:read", "read-spu-object", 0);
13272 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13273 "qXfer:spu:write", "write-spu-object", 0);
13275 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13276 "qXfer:osdata:read", "osdata", 0);
13278 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13279 "qXfer:threads:read", "threads", 0);
13281 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13282 "qXfer:siginfo:read", "read-siginfo-object", 0);
13284 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13285 "qXfer:siginfo:write", "write-siginfo-object", 0);
13287 add_packet_config_cmd
13288 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13289 "qXfer:traceframe-info:read", "traceframe-info", 0);
13291 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13292 "qXfer:uib:read", "unwind-info-block", 0);
13294 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13295 "qGetTLSAddr", "get-thread-local-storage-address",
13298 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13299 "qGetTIBAddr", "get-thread-information-block-address",
13302 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13303 "bc", "reverse-continue", 0);
13305 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13306 "bs", "reverse-step", 0);
13308 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13309 "qSupported", "supported-packets", 0);
13311 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13312 "qSearch:memory", "search-memory", 0);
13314 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13315 "qTStatus", "trace-status", 0);
13317 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13318 "vFile:setfs", "hostio-setfs", 0);
13320 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13321 "vFile:open", "hostio-open", 0);
13323 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13324 "vFile:pread", "hostio-pread", 0);
13326 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13327 "vFile:pwrite", "hostio-pwrite", 0);
13329 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13330 "vFile:close", "hostio-close", 0);
13332 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13333 "vFile:unlink", "hostio-unlink", 0);
13335 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13336 "vFile:readlink", "hostio-readlink", 0);
13338 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13339 "vFile:fstat", "hostio-fstat", 0);
13341 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13342 "vAttach", "attach", 0);
13344 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13347 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13348 "QStartNoAckMode", "noack", 0);
13350 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13351 "vKill", "kill", 0);
13353 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13354 "qAttached", "query-attached", 0);
13356 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13357 "ConditionalTracepoints",
13358 "conditional-tracepoints", 0);
13360 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13361 "ConditionalBreakpoints",
13362 "conditional-breakpoints", 0);
13364 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13365 "BreakpointCommands",
13366 "breakpoint-commands", 0);
13368 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13369 "FastTracepoints", "fast-tracepoints", 0);
13371 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13372 "TracepointSource", "TracepointSource", 0);
13374 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13375 "QAllow", "allow", 0);
13377 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13378 "StaticTracepoints", "static-tracepoints", 0);
13380 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13381 "InstallInTrace", "install-in-trace", 0);
13383 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13384 "qXfer:statictrace:read", "read-sdata-object", 0);
13386 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13387 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13389 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13390 "QDisableRandomization", "disable-randomization", 0);
13392 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13393 "QAgent", "agent", 0);
13395 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13396 "QTBuffer:size", "trace-buffer-size", 0);
13398 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13399 "Qbtrace:off", "disable-btrace", 0);
13401 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13402 "Qbtrace:bts", "enable-btrace-bts", 0);
13404 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13405 "Qbtrace:pt", "enable-btrace-pt", 0);
13407 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13408 "qXfer:btrace", "read-btrace", 0);
13410 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13411 "qXfer:btrace-conf", "read-btrace-conf", 0);
13413 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13414 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13416 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13417 "multiprocess-feature", "multiprocess-feature", 0);
13419 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13420 "swbreak-feature", "swbreak-feature", 0);
13422 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13423 "hwbreak-feature", "hwbreak-feature", 0);
13425 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13426 "fork-event-feature", "fork-event-feature", 0);
13428 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13429 "vfork-event-feature", "vfork-event-feature", 0);
13431 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13432 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13434 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13435 "exec-event-feature", "exec-event-feature", 0);
13437 /* Assert that we've registered "set remote foo-packet" commands
13438 for all packet configs. */
13442 for (i = 0; i < PACKET_MAX; i++)
13444 /* Ideally all configs would have a command associated. Some
13445 still don't though. */
13450 case PACKET_QNonStop:
13451 case PACKET_EnableDisableTracepoints_feature:
13452 case PACKET_tracenz_feature:
13453 case PACKET_DisconnectedTracing_feature:
13454 case PACKET_augmented_libraries_svr4_read_feature:
13456 /* Additions to this list need to be well justified:
13457 pre-existing packets are OK; new packets are not. */
13465 /* This catches both forgetting to add a config command, and
13466 forgetting to remove a packet from the exception list. */
13467 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13471 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13472 Z sub-packet has its own set and show commands, but users may
13473 have sets to this variable in their .gdbinit files (or in their
13475 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13476 &remote_Z_packet_detect, _("\
13477 Set use of remote protocol `Z' packets"), _("\
13478 Show use of remote protocol `Z' packets "), _("\
13479 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13481 set_remote_protocol_Z_packet_cmd,
13482 show_remote_protocol_Z_packet_cmd,
13483 /* FIXME: i18n: Use of remote protocol
13484 `Z' packets is %s. */
13485 &remote_set_cmdlist, &remote_show_cmdlist);
13487 add_prefix_cmd ("remote", class_files, remote_command, _("\
13488 Manipulate files on the remote system\n\
13489 Transfer files to and from the remote target system."),
13490 &remote_cmdlist, "remote ",
13491 0 /* allow-unknown */, &cmdlist);
13493 add_cmd ("put", class_files, remote_put_command,
13494 _("Copy a local file to the remote system."),
13497 add_cmd ("get", class_files, remote_get_command,
13498 _("Copy a remote file to the local system."),
13501 add_cmd ("delete", class_files, remote_delete_command,
13502 _("Delete a remote file."),
13505 add_setshow_string_noescape_cmd ("exec-file", class_files,
13506 &remote_exec_file_var, _("\
13507 Set the remote pathname for \"run\""), _("\
13508 Show the remote pathname for \"run\""), NULL,
13509 set_remote_exec_file,
13510 show_remote_exec_file,
13511 &remote_set_cmdlist,
13512 &remote_show_cmdlist);
13514 add_setshow_boolean_cmd ("range-stepping", class_run,
13515 &use_range_stepping, _("\
13516 Enable or disable range stepping."), _("\
13517 Show whether target-assisted range stepping is enabled."), _("\
13518 If on, and the target supports it, when stepping a source line, GDB\n\
13519 tells the target to step the corresponding range of addresses itself instead\n\
13520 of issuing multiple single-steps. This speeds up source level\n\
13521 stepping. If off, GDB always issues single-steps, even if range\n\
13522 stepping is supported by the target. The default is on."),
13523 set_range_stepping,
13524 show_range_stepping,
13528 /* Eventually initialize fileio. See fileio.c */
13529 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13531 /* Take advantage of the fact that the TID field is not used, to tag
13532 special ptids with it set to != 0. */
13533 magic_null_ptid = ptid_build (42000, -1, 1);
13534 not_sent_ptid = ptid_build (42000, -2, 1);
13535 any_thread_ptid = ptid_build (42000, 0, 1);
13537 target_buf_size = 2048;
13538 target_buf = xmalloc (target_buf_size);