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 /* Insert fork catchpoint target routine. If fork events are enabled
1600 then return success, nothing more to do. */
1603 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1605 struct remote_state *rs = get_remote_state ();
1607 return !remote_fork_event_p (rs);
1610 /* Remove fork catchpoint target routine. Nothing to do, just
1614 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1619 /* Insert vfork catchpoint target routine. If vfork events are enabled
1620 then return success, nothing more to do. */
1623 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1625 struct remote_state *rs = get_remote_state ();
1627 return !remote_vfork_event_p (rs);
1630 /* Remove vfork catchpoint target routine. Nothing to do, just
1634 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1639 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1640 static struct async_signal_handler *async_sigint_remote_twice_token;
1641 static struct async_signal_handler *async_sigint_remote_token;
1644 /* Asynchronous signal handle registered as event loop source for
1645 when we have pending events ready to be passed to the core. */
1647 static struct async_event_handler *remote_async_inferior_event_token;
1651 static ptid_t magic_null_ptid;
1652 static ptid_t not_sent_ptid;
1653 static ptid_t any_thread_ptid;
1655 /* Find out if the stub attached to PID (and hence GDB should offer to
1656 detach instead of killing it when bailing out). */
1659 remote_query_attached (int pid)
1661 struct remote_state *rs = get_remote_state ();
1662 size_t size = get_remote_packet_size ();
1664 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1667 if (remote_multi_process_p (rs))
1668 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1670 xsnprintf (rs->buf, size, "qAttached");
1673 getpkt (&rs->buf, &rs->buf_size, 0);
1675 switch (packet_ok (rs->buf,
1676 &remote_protocol_packets[PACKET_qAttached]))
1679 if (strcmp (rs->buf, "1") == 0)
1683 warning (_("Remote failure reply: %s"), rs->buf);
1685 case PACKET_UNKNOWN:
1692 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1693 has been invented by GDB, instead of reported by the target. Since
1694 we can be connected to a remote system before before knowing about
1695 any inferior, mark the target with execution when we find the first
1696 inferior. If ATTACHED is 1, then we had just attached to this
1697 inferior. If it is 0, then we just created this inferior. If it
1698 is -1, then try querying the remote stub to find out if it had
1699 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1700 attempt to open this inferior's executable as the main executable
1701 if no main executable is open already. */
1703 static struct inferior *
1704 remote_add_inferior (int fake_pid_p, int pid, int attached,
1707 struct inferior *inf;
1709 /* Check whether this process we're learning about is to be
1710 considered attached, or if is to be considered to have been
1711 spawned by the stub. */
1713 attached = remote_query_attached (pid);
1715 if (gdbarch_has_global_solist (target_gdbarch ()))
1717 /* If the target shares code across all inferiors, then every
1718 attach adds a new inferior. */
1719 inf = add_inferior (pid);
1721 /* ... and every inferior is bound to the same program space.
1722 However, each inferior may still have its own address
1724 inf->aspace = maybe_new_address_space ();
1725 inf->pspace = current_program_space;
1729 /* In the traditional debugging scenario, there's a 1-1 match
1730 between program/address spaces. We simply bind the inferior
1731 to the program space's address space. */
1732 inf = current_inferior ();
1733 inferior_appeared (inf, pid);
1736 inf->attach_flag = attached;
1737 inf->fake_pid_p = fake_pid_p;
1739 /* If no main executable is currently open then attempt to
1740 open the file that was executed to create this inferior. */
1741 if (try_open_exec && get_exec_file (0) == NULL)
1742 exec_file_locate_attach (pid, 1);
1747 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1748 according to RUNNING. */
1751 remote_add_thread (ptid_t ptid, int running)
1753 struct remote_state *rs = get_remote_state ();
1755 /* GDB historically didn't pull threads in the initial connection
1756 setup. If the remote target doesn't even have a concept of
1757 threads (e.g., a bare-metal target), even if internally we
1758 consider that a single-threaded target, mentioning a new thread
1759 might be confusing to the user. Be silent then, preserving the
1760 age old behavior. */
1761 if (rs->starting_up)
1762 add_thread_silent (ptid);
1766 set_executing (ptid, running);
1767 set_running (ptid, running);
1770 /* Come here when we learn about a thread id from the remote target.
1771 It may be the first time we hear about such thread, so take the
1772 opportunity to add it to GDB's thread list. In case this is the
1773 first time we're noticing its corresponding inferior, add it to
1774 GDB's inferior list as well. */
1777 remote_notice_new_inferior (ptid_t currthread, int running)
1779 /* If this is a new thread, add it to GDB's thread list.
1780 If we leave it up to WFI to do this, bad things will happen. */
1782 if (in_thread_list (currthread) && is_exited (currthread))
1784 /* We're seeing an event on a thread id we knew had exited.
1785 This has to be a new thread reusing the old id. Add it. */
1786 remote_add_thread (currthread, running);
1790 if (!in_thread_list (currthread))
1792 struct inferior *inf = NULL;
1793 int pid = ptid_get_pid (currthread);
1795 if (ptid_is_pid (inferior_ptid)
1796 && pid == ptid_get_pid (inferior_ptid))
1798 /* inferior_ptid has no thread member yet. This can happen
1799 with the vAttach -> remote_wait,"TAAthread:" path if the
1800 stub doesn't support qC. This is the first stop reported
1801 after an attach, so this is the main thread. Update the
1802 ptid in the thread list. */
1803 if (in_thread_list (pid_to_ptid (pid)))
1804 thread_change_ptid (inferior_ptid, currthread);
1807 remote_add_thread (currthread, running);
1808 inferior_ptid = currthread;
1813 if (ptid_equal (magic_null_ptid, inferior_ptid))
1815 /* inferior_ptid is not set yet. This can happen with the
1816 vRun -> remote_wait,"TAAthread:" path if the stub
1817 doesn't support qC. This is the first stop reported
1818 after an attach, so this is the main thread. Update the
1819 ptid in the thread list. */
1820 thread_change_ptid (inferior_ptid, currthread);
1824 /* When connecting to a target remote, or to a target
1825 extended-remote which already was debugging an inferior, we
1826 may not know about it yet. Add it before adding its child
1827 thread, so notifications are emitted in a sensible order. */
1828 if (!in_inferior_list (ptid_get_pid (currthread)))
1830 struct remote_state *rs = get_remote_state ();
1831 int fake_pid_p = !remote_multi_process_p (rs);
1833 inf = remote_add_inferior (fake_pid_p,
1834 ptid_get_pid (currthread), -1, 1);
1837 /* This is really a new thread. Add it. */
1838 remote_add_thread (currthread, running);
1840 /* If we found a new inferior, let the common code do whatever
1841 it needs to with it (e.g., read shared libraries, insert
1842 breakpoints), unless we're just setting up an all-stop
1846 struct remote_state *rs = get_remote_state ();
1848 if (non_stop || !rs->starting_up)
1849 notice_new_inferior (currthread, running, 0);
1854 /* Return the private thread data, creating it if necessary. */
1856 static struct private_thread_info *
1857 demand_private_info (ptid_t ptid)
1859 struct thread_info *info = find_thread_ptid (ptid);
1865 info->priv = XNEW (struct private_thread_info);
1866 info->private_dtor = free_private_thread_info;
1867 info->priv->core = -1;
1868 info->priv->extra = 0;
1874 /* Call this function as a result of
1875 1) A halt indication (T packet) containing a thread id
1876 2) A direct query of currthread
1877 3) Successful execution of set thread */
1880 record_currthread (struct remote_state *rs, ptid_t currthread)
1882 rs->general_thread = currthread;
1885 /* If 'QPassSignals' is supported, tell the remote stub what signals
1886 it can simply pass through to the inferior without reporting. */
1889 remote_pass_signals (struct target_ops *self,
1890 int numsigs, unsigned char *pass_signals)
1892 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1894 char *pass_packet, *p;
1896 struct remote_state *rs = get_remote_state ();
1898 gdb_assert (numsigs < 256);
1899 for (i = 0; i < numsigs; i++)
1901 if (pass_signals[i])
1904 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1905 strcpy (pass_packet, "QPassSignals:");
1906 p = pass_packet + strlen (pass_packet);
1907 for (i = 0; i < numsigs; i++)
1909 if (pass_signals[i])
1912 *p++ = tohex (i >> 4);
1913 *p++ = tohex (i & 15);
1922 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1924 putpkt (pass_packet);
1925 getpkt (&rs->buf, &rs->buf_size, 0);
1926 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1927 if (rs->last_pass_packet)
1928 xfree (rs->last_pass_packet);
1929 rs->last_pass_packet = pass_packet;
1932 xfree (pass_packet);
1936 /* If 'QProgramSignals' is supported, tell the remote stub what
1937 signals it should pass through to the inferior when detaching. */
1940 remote_program_signals (struct target_ops *self,
1941 int numsigs, unsigned char *signals)
1943 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1947 struct remote_state *rs = get_remote_state ();
1949 gdb_assert (numsigs < 256);
1950 for (i = 0; i < numsigs; i++)
1955 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1956 strcpy (packet, "QProgramSignals:");
1957 p = packet + strlen (packet);
1958 for (i = 0; i < numsigs; i++)
1960 if (signal_pass_state (i))
1963 *p++ = tohex (i >> 4);
1964 *p++ = tohex (i & 15);
1973 if (!rs->last_program_signals_packet
1974 || strcmp (rs->last_program_signals_packet, packet) != 0)
1977 getpkt (&rs->buf, &rs->buf_size, 0);
1978 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1979 xfree (rs->last_program_signals_packet);
1980 rs->last_program_signals_packet = packet;
1987 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1988 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1989 thread. If GEN is set, set the general thread, if not, then set
1990 the step/continue thread. */
1992 set_thread (struct ptid ptid, int gen)
1994 struct remote_state *rs = get_remote_state ();
1995 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1996 char *buf = rs->buf;
1997 char *endbuf = rs->buf + get_remote_packet_size ();
1999 if (ptid_equal (state, ptid))
2003 *buf++ = gen ? 'g' : 'c';
2004 if (ptid_equal (ptid, magic_null_ptid))
2005 xsnprintf (buf, endbuf - buf, "0");
2006 else if (ptid_equal (ptid, any_thread_ptid))
2007 xsnprintf (buf, endbuf - buf, "0");
2008 else if (ptid_equal (ptid, minus_one_ptid))
2009 xsnprintf (buf, endbuf - buf, "-1");
2011 write_ptid (buf, endbuf, ptid);
2013 getpkt (&rs->buf, &rs->buf_size, 0);
2015 rs->general_thread = ptid;
2017 rs->continue_thread = ptid;
2021 set_general_thread (struct ptid ptid)
2023 set_thread (ptid, 1);
2027 set_continue_thread (struct ptid ptid)
2029 set_thread (ptid, 0);
2032 /* Change the remote current process. Which thread within the process
2033 ends up selected isn't important, as long as it is the same process
2034 as what INFERIOR_PTID points to.
2036 This comes from that fact that there is no explicit notion of
2037 "selected process" in the protocol. The selected process for
2038 general operations is the process the selected general thread
2042 set_general_process (void)
2044 struct remote_state *rs = get_remote_state ();
2046 /* If the remote can't handle multiple processes, don't bother. */
2047 if (!rs->extended || !remote_multi_process_p (rs))
2050 /* We only need to change the remote current thread if it's pointing
2051 at some other process. */
2052 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2053 set_general_thread (inferior_ptid);
2057 /* Return nonzero if this is the main thread that we made up ourselves
2058 to model non-threaded targets as single-threaded. */
2061 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2063 struct remote_state *rs = get_remote_state ();
2066 if (ptid_equal (ptid, magic_null_ptid))
2067 /* The main thread is always alive. */
2070 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2071 /* The main thread is always alive. This can happen after a
2072 vAttach, if the remote side doesn't support
2079 /* Return nonzero if the thread PTID is still alive on the remote
2083 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2085 struct remote_state *rs = get_remote_state ();
2088 /* Check if this is a thread that we made up ourselves to model
2089 non-threaded targets as single-threaded. */
2090 if (remote_thread_always_alive (ops, ptid))
2094 endp = rs->buf + get_remote_packet_size ();
2097 write_ptid (p, endp, ptid);
2100 getpkt (&rs->buf, &rs->buf_size, 0);
2101 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2104 /* About these extended threadlist and threadinfo packets. They are
2105 variable length packets but, the fields within them are often fixed
2106 length. They are redundent enough to send over UDP as is the
2107 remote protocol in general. There is a matching unit test module
2110 /* WARNING: This threadref data structure comes from the remote O.S.,
2111 libstub protocol encoding, and remote.c. It is not particularly
2114 /* Right now, the internal structure is int. We want it to be bigger.
2115 Plan to fix this. */
2117 typedef int gdb_threadref; /* Internal GDB thread reference. */
2119 /* gdb_ext_thread_info is an internal GDB data structure which is
2120 equivalent to the reply of the remote threadinfo packet. */
2122 struct gdb_ext_thread_info
2124 threadref threadid; /* External form of thread reference. */
2125 int active; /* Has state interesting to GDB?
2127 char display[256]; /* Brief state display, name,
2128 blocked/suspended. */
2129 char shortname[32]; /* To be used to name threads. */
2130 char more_display[256]; /* Long info, statistics, queue depth,
2134 /* The volume of remote transfers can be limited by submitting
2135 a mask containing bits specifying the desired information.
2136 Use a union of these values as the 'selection' parameter to
2137 get_thread_info. FIXME: Make these TAG names more thread specific. */
2139 #define TAG_THREADID 1
2140 #define TAG_EXISTS 2
2141 #define TAG_DISPLAY 4
2142 #define TAG_THREADNAME 8
2143 #define TAG_MOREDISPLAY 16
2145 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2147 static char *unpack_nibble (char *buf, int *val);
2149 static char *unpack_byte (char *buf, int *value);
2151 static char *pack_int (char *buf, int value);
2153 static char *unpack_int (char *buf, int *value);
2155 static char *unpack_string (char *src, char *dest, int length);
2157 static char *pack_threadid (char *pkt, threadref *id);
2159 static char *unpack_threadid (char *inbuf, threadref *id);
2161 void int_to_threadref (threadref *id, int value);
2163 static int threadref_to_int (threadref *ref);
2165 static void copy_threadref (threadref *dest, threadref *src);
2167 static int threadmatch (threadref *dest, threadref *src);
2169 static char *pack_threadinfo_request (char *pkt, int mode,
2172 static int remote_unpack_thread_info_response (char *pkt,
2173 threadref *expectedref,
2174 struct gdb_ext_thread_info
2178 static int remote_get_threadinfo (threadref *threadid,
2179 int fieldset, /*TAG mask */
2180 struct gdb_ext_thread_info *info);
2182 static char *pack_threadlist_request (char *pkt, int startflag,
2184 threadref *nextthread);
2186 static int parse_threadlist_response (char *pkt,
2188 threadref *original_echo,
2189 threadref *resultlist,
2192 static int remote_get_threadlist (int startflag,
2193 threadref *nextthread,
2197 threadref *threadlist);
2199 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2201 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2202 void *context, int looplimit);
2204 static int remote_newthread_step (threadref *ref, void *context);
2207 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2208 buffer we're allowed to write to. Returns
2209 BUF+CHARACTERS_WRITTEN. */
2212 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2215 struct remote_state *rs = get_remote_state ();
2217 if (remote_multi_process_p (rs))
2219 pid = ptid_get_pid (ptid);
2221 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2223 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2225 tid = ptid_get_lwp (ptid);
2227 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2229 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2234 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2235 passed the last parsed char. Returns null_ptid on error. */
2238 read_ptid (char *buf, char **obuf)
2242 ULONGEST pid = 0, tid = 0;
2246 /* Multi-process ptid. */
2247 pp = unpack_varlen_hex (p + 1, &pid);
2249 error (_("invalid remote ptid: %s"), p);
2252 pp = unpack_varlen_hex (p + 1, &tid);
2255 return ptid_build (pid, tid, 0);
2258 /* No multi-process. Just a tid. */
2259 pp = unpack_varlen_hex (p, &tid);
2261 /* Return null_ptid when no thread id is found. */
2269 /* Since the stub is not sending a process id, then default to
2270 what's in inferior_ptid, unless it's null at this point. If so,
2271 then since there's no way to know the pid of the reported
2272 threads, use the magic number. */
2273 if (ptid_equal (inferior_ptid, null_ptid))
2274 pid = ptid_get_pid (magic_null_ptid);
2276 pid = ptid_get_pid (inferior_ptid);
2280 return ptid_build (pid, tid, 0);
2286 if (ch >= 'a' && ch <= 'f')
2287 return ch - 'a' + 10;
2288 if (ch >= '0' && ch <= '9')
2290 if (ch >= 'A' && ch <= 'F')
2291 return ch - 'A' + 10;
2296 stub_unpack_int (char *buff, int fieldlength)
2303 nibble = stubhex (*buff++);
2307 retval = retval << 4;
2313 unpack_nibble (char *buf, int *val)
2315 *val = fromhex (*buf++);
2320 unpack_byte (char *buf, int *value)
2322 *value = stub_unpack_int (buf, 2);
2327 pack_int (char *buf, int value)
2329 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2330 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2331 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2332 buf = pack_hex_byte (buf, (value & 0xff));
2337 unpack_int (char *buf, int *value)
2339 *value = stub_unpack_int (buf, 8);
2343 #if 0 /* Currently unused, uncomment when needed. */
2344 static char *pack_string (char *pkt, char *string);
2347 pack_string (char *pkt, char *string)
2352 len = strlen (string);
2354 len = 200; /* Bigger than most GDB packets, junk??? */
2355 pkt = pack_hex_byte (pkt, len);
2359 if ((ch == '\0') || (ch == '#'))
2360 ch = '*'; /* Protect encapsulation. */
2365 #endif /* 0 (unused) */
2368 unpack_string (char *src, char *dest, int length)
2377 pack_threadid (char *pkt, threadref *id)
2380 unsigned char *altid;
2382 altid = (unsigned char *) id;
2383 limit = pkt + BUF_THREAD_ID_SIZE;
2385 pkt = pack_hex_byte (pkt, *altid++);
2391 unpack_threadid (char *inbuf, threadref *id)
2394 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2397 altref = (char *) id;
2399 while (inbuf < limit)
2401 x = stubhex (*inbuf++);
2402 y = stubhex (*inbuf++);
2403 *altref++ = (x << 4) | y;
2408 /* Externally, threadrefs are 64 bits but internally, they are still
2409 ints. This is due to a mismatch of specifications. We would like
2410 to use 64bit thread references internally. This is an adapter
2414 int_to_threadref (threadref *id, int value)
2416 unsigned char *scan;
2418 scan = (unsigned char *) id;
2424 *scan++ = (value >> 24) & 0xff;
2425 *scan++ = (value >> 16) & 0xff;
2426 *scan++ = (value >> 8) & 0xff;
2427 *scan++ = (value & 0xff);
2431 threadref_to_int (threadref *ref)
2434 unsigned char *scan;
2440 value = (value << 8) | ((*scan++) & 0xff);
2445 copy_threadref (threadref *dest, threadref *src)
2448 unsigned char *csrc, *cdest;
2450 csrc = (unsigned char *) src;
2451 cdest = (unsigned char *) dest;
2458 threadmatch (threadref *dest, threadref *src)
2460 /* Things are broken right now, so just assume we got a match. */
2462 unsigned char *srcp, *destp;
2464 srcp = (char *) src;
2465 destp = (char *) dest;
2469 result &= (*srcp++ == *destp++) ? 1 : 0;
2476 threadid:1, # always request threadid
2483 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2486 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2488 *pkt++ = 'q'; /* Info Query */
2489 *pkt++ = 'P'; /* process or thread info */
2490 pkt = pack_int (pkt, mode); /* mode */
2491 pkt = pack_threadid (pkt, id); /* threadid */
2492 *pkt = '\0'; /* terminate */
2496 /* These values tag the fields in a thread info response packet. */
2497 /* Tagging the fields allows us to request specific fields and to
2498 add more fields as time goes by. */
2500 #define TAG_THREADID 1 /* Echo the thread identifier. */
2501 #define TAG_EXISTS 2 /* Is this process defined enough to
2502 fetch registers and its stack? */
2503 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2504 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2505 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2509 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2510 struct gdb_ext_thread_info *info)
2512 struct remote_state *rs = get_remote_state ();
2516 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2519 /* info->threadid = 0; FIXME: implement zero_threadref. */
2521 info->display[0] = '\0';
2522 info->shortname[0] = '\0';
2523 info->more_display[0] = '\0';
2525 /* Assume the characters indicating the packet type have been
2527 pkt = unpack_int (pkt, &mask); /* arg mask */
2528 pkt = unpack_threadid (pkt, &ref);
2531 warning (_("Incomplete response to threadinfo request."));
2532 if (!threadmatch (&ref, expectedref))
2533 { /* This is an answer to a different request. */
2534 warning (_("ERROR RMT Thread info mismatch."));
2537 copy_threadref (&info->threadid, &ref);
2539 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2541 /* Packets are terminated with nulls. */
2542 while ((pkt < limit) && mask && *pkt)
2544 pkt = unpack_int (pkt, &tag); /* tag */
2545 pkt = unpack_byte (pkt, &length); /* length */
2546 if (!(tag & mask)) /* Tags out of synch with mask. */
2548 warning (_("ERROR RMT: threadinfo tag mismatch."));
2552 if (tag == TAG_THREADID)
2556 warning (_("ERROR RMT: length of threadid is not 16."));
2560 pkt = unpack_threadid (pkt, &ref);
2561 mask = mask & ~TAG_THREADID;
2564 if (tag == TAG_EXISTS)
2566 info->active = stub_unpack_int (pkt, length);
2568 mask = mask & ~(TAG_EXISTS);
2571 warning (_("ERROR RMT: 'exists' length too long."));
2577 if (tag == TAG_THREADNAME)
2579 pkt = unpack_string (pkt, &info->shortname[0], length);
2580 mask = mask & ~TAG_THREADNAME;
2583 if (tag == TAG_DISPLAY)
2585 pkt = unpack_string (pkt, &info->display[0], length);
2586 mask = mask & ~TAG_DISPLAY;
2589 if (tag == TAG_MOREDISPLAY)
2591 pkt = unpack_string (pkt, &info->more_display[0], length);
2592 mask = mask & ~TAG_MOREDISPLAY;
2595 warning (_("ERROR RMT: unknown thread info tag."));
2596 break; /* Not a tag we know about. */
2602 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2603 struct gdb_ext_thread_info *info)
2605 struct remote_state *rs = get_remote_state ();
2608 pack_threadinfo_request (rs->buf, fieldset, threadid);
2610 getpkt (&rs->buf, &rs->buf_size, 0);
2612 if (rs->buf[0] == '\0')
2615 result = remote_unpack_thread_info_response (rs->buf + 2,
2620 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2623 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2624 threadref *nextthread)
2626 *pkt++ = 'q'; /* info query packet */
2627 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2628 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2629 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2630 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2635 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2638 parse_threadlist_response (char *pkt, int result_limit,
2639 threadref *original_echo, threadref *resultlist,
2642 struct remote_state *rs = get_remote_state ();
2644 int count, resultcount, done;
2647 /* Assume the 'q' and 'M chars have been stripped. */
2648 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2649 /* done parse past here */
2650 pkt = unpack_byte (pkt, &count); /* count field */
2651 pkt = unpack_nibble (pkt, &done);
2652 /* The first threadid is the argument threadid. */
2653 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2654 while ((count-- > 0) && (pkt < limit))
2656 pkt = unpack_threadid (pkt, resultlist++);
2657 if (resultcount++ >= result_limit)
2665 /* Fetch the next batch of threads from the remote. Returns -1 if the
2666 qL packet is not supported, 0 on error and 1 on success. */
2669 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2670 int *done, int *result_count, threadref *threadlist)
2672 struct remote_state *rs = get_remote_state ();
2675 /* Trancate result limit to be smaller than the packet size. */
2676 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2677 >= get_remote_packet_size ())
2678 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2680 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2682 getpkt (&rs->buf, &rs->buf_size, 0);
2683 if (*rs->buf == '\0')
2685 /* Packet not supported. */
2690 parse_threadlist_response (rs->buf + 2, result_limit,
2691 &rs->echo_nextthread, threadlist, done);
2693 if (!threadmatch (&rs->echo_nextthread, nextthread))
2695 /* FIXME: This is a good reason to drop the packet. */
2696 /* Possably, there is a duplicate response. */
2698 retransmit immediatly - race conditions
2699 retransmit after timeout - yes
2701 wait for packet, then exit
2703 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2704 return 0; /* I choose simply exiting. */
2706 if (*result_count <= 0)
2710 warning (_("RMT ERROR : failed to get remote thread list."));
2713 return result; /* break; */
2715 if (*result_count > result_limit)
2718 warning (_("RMT ERROR: threadlist response longer than requested."));
2724 /* Fetch the list of remote threads, with the qL packet, and call
2725 STEPFUNCTION for each thread found. Stops iterating and returns 1
2726 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2727 STEPFUNCTION returns false. If the packet is not supported,
2731 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2734 struct remote_state *rs = get_remote_state ();
2735 int done, i, result_count;
2743 if (loopcount++ > looplimit)
2746 warning (_("Remote fetch threadlist -infinite loop-."));
2749 result = remote_get_threadlist (startflag, &rs->nextthread,
2750 MAXTHREADLISTRESULTS,
2751 &done, &result_count,
2752 rs->resultthreadlist);
2755 /* Clear for later iterations. */
2757 /* Setup to resume next batch of thread references, set nextthread. */
2758 if (result_count >= 1)
2759 copy_threadref (&rs->nextthread,
2760 &rs->resultthreadlist[result_count - 1]);
2762 while (result_count--)
2764 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2774 /* A thread found on the remote target. */
2776 typedef struct thread_item
2778 /* The thread's PTID. */
2781 /* The thread's extra info. May be NULL. */
2784 /* The core the thread was running on. -1 if not known. */
2787 DEF_VEC_O(thread_item_t);
2789 /* Context passed around to the various methods listing remote
2790 threads. As new threads are found, they're added to the ITEMS
2793 struct threads_listing_context
2795 /* The threads found on the remote target. */
2796 VEC (thread_item_t) *items;
2799 /* Discard the contents of the constructed thread listing context. */
2802 clear_threads_listing_context (void *p)
2804 struct threads_listing_context *context = p;
2806 struct thread_item *item;
2808 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2809 xfree (item->extra);
2811 VEC_free (thread_item_t, context->items);
2814 /* Remove the thread specified as the related_pid field of WS
2815 from the CONTEXT list. */
2818 threads_listing_context_remove (struct target_waitstatus *ws,
2819 struct threads_listing_context *context)
2821 struct thread_item *item;
2823 ptid_t child_ptid = ws->value.related_pid;
2825 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2827 if (ptid_equal (item->ptid, child_ptid))
2829 VEC_ordered_remove (thread_item_t, context->items, i);
2836 remote_newthread_step (threadref *ref, void *data)
2838 struct threads_listing_context *context = data;
2839 struct thread_item item;
2840 int pid = ptid_get_pid (inferior_ptid);
2842 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2846 VEC_safe_push (thread_item_t, context->items, &item);
2848 return 1; /* continue iterator */
2851 #define CRAZY_MAX_THREADS 1000
2854 remote_current_thread (ptid_t oldpid)
2856 struct remote_state *rs = get_remote_state ();
2859 getpkt (&rs->buf, &rs->buf_size, 0);
2860 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2865 result = read_ptid (&rs->buf[2], &obuf);
2866 if (*obuf != '\0' && remote_debug)
2867 fprintf_unfiltered (gdb_stdlog,
2868 "warning: garbage in qC reply\n");
2876 /* List remote threads using the deprecated qL packet. */
2879 remote_get_threads_with_ql (struct target_ops *ops,
2880 struct threads_listing_context *context)
2882 if (remote_threadlist_iterator (remote_newthread_step, context,
2883 CRAZY_MAX_THREADS) >= 0)
2889 #if defined(HAVE_LIBEXPAT)
2892 start_thread (struct gdb_xml_parser *parser,
2893 const struct gdb_xml_element *element,
2894 void *user_data, VEC(gdb_xml_value_s) *attributes)
2896 struct threads_listing_context *data = user_data;
2898 struct thread_item item;
2900 struct gdb_xml_value *attr;
2902 id = xml_find_attribute (attributes, "id")->value;
2903 item.ptid = read_ptid (id, NULL);
2905 attr = xml_find_attribute (attributes, "core");
2907 item.core = *(ULONGEST *) attr->value;
2913 VEC_safe_push (thread_item_t, data->items, &item);
2917 end_thread (struct gdb_xml_parser *parser,
2918 const struct gdb_xml_element *element,
2919 void *user_data, const char *body_text)
2921 struct threads_listing_context *data = user_data;
2923 if (body_text && *body_text)
2924 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2927 const struct gdb_xml_attribute thread_attributes[] = {
2928 { "id", GDB_XML_AF_NONE, NULL, NULL },
2929 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2930 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2933 const struct gdb_xml_element thread_children[] = {
2934 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2937 const struct gdb_xml_element threads_children[] = {
2938 { "thread", thread_attributes, thread_children,
2939 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2940 start_thread, end_thread },
2941 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2944 const struct gdb_xml_element threads_elements[] = {
2945 { "threads", NULL, threads_children,
2946 GDB_XML_EF_NONE, NULL, NULL },
2947 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2952 /* List remote threads using qXfer:threads:read. */
2955 remote_get_threads_with_qxfer (struct target_ops *ops,
2956 struct threads_listing_context *context)
2958 #if defined(HAVE_LIBEXPAT)
2959 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2961 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2962 struct cleanup *back_to = make_cleanup (xfree, xml);
2964 if (xml != NULL && *xml != '\0')
2966 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2967 threads_elements, xml, context);
2970 do_cleanups (back_to);
2978 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2981 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2982 struct threads_listing_context *context)
2984 struct remote_state *rs = get_remote_state ();
2986 if (rs->use_threadinfo_query)
2990 putpkt ("qfThreadInfo");
2991 getpkt (&rs->buf, &rs->buf_size, 0);
2993 if (bufp[0] != '\0') /* q packet recognized */
2995 while (*bufp++ == 'm') /* reply contains one or more TID */
2999 struct thread_item item;
3001 item.ptid = read_ptid (bufp, &bufp);
3005 VEC_safe_push (thread_item_t, context->items, &item);
3007 while (*bufp++ == ','); /* comma-separated list */
3008 putpkt ("qsThreadInfo");
3009 getpkt (&rs->buf, &rs->buf_size, 0);
3016 /* Packet not recognized. */
3017 rs->use_threadinfo_query = 0;
3024 /* Implement the to_update_thread_list function for the remote
3028 remote_update_thread_list (struct target_ops *ops)
3030 struct remote_state *rs = get_remote_state ();
3031 struct threads_listing_context context;
3032 struct cleanup *old_chain;
3035 context.items = NULL;
3036 old_chain = make_cleanup (clear_threads_listing_context, &context);
3038 /* We have a few different mechanisms to fetch the thread list. Try
3039 them all, starting with the most preferred one first, falling
3040 back to older methods. */
3041 if (remote_get_threads_with_qxfer (ops, &context)
3042 || remote_get_threads_with_qthreadinfo (ops, &context)
3043 || remote_get_threads_with_ql (ops, &context))
3046 struct thread_item *item;
3047 struct thread_info *tp, *tmp;
3051 if (VEC_empty (thread_item_t, context.items)
3052 && remote_thread_always_alive (ops, inferior_ptid))
3054 /* Some targets don't really support threads, but still
3055 reply an (empty) thread list in response to the thread
3056 listing packets, instead of replying "packet not
3057 supported". Exit early so we don't delete the main
3059 do_cleanups (old_chain);
3063 /* CONTEXT now holds the current thread list on the remote
3064 target end. Delete GDB-side threads no longer found on the
3066 ALL_THREADS_SAFE (tp, tmp)
3069 VEC_iterate (thread_item_t, context.items, i, item);
3072 if (ptid_equal (item->ptid, tp->ptid))
3076 if (i == VEC_length (thread_item_t, context.items))
3079 delete_thread (tp->ptid);
3083 /* Remove any unreported fork child threads from CONTEXT so
3084 that we don't interfere with follow fork, which is where
3085 creation of such threads is handled. */
3086 remove_new_fork_children (&context);
3088 /* And now add threads we don't know about yet to our list. */
3090 VEC_iterate (thread_item_t, context.items, i, item);
3093 if (!ptid_equal (item->ptid, null_ptid))
3095 struct private_thread_info *info;
3096 /* In non-stop mode, we assume new found threads are
3097 running until proven otherwise with a stop reply. In
3098 all-stop, we can only get here if all threads are
3100 int running = non_stop ? 1 : 0;
3102 remote_notice_new_inferior (item->ptid, running);
3104 info = demand_private_info (item->ptid);
3105 info->core = item->core;
3106 info->extra = item->extra;
3114 /* If no thread listing method is supported, then query whether
3115 each known thread is alive, one by one, with the T packet.
3116 If the target doesn't support threads at all, then this is a
3117 no-op. See remote_thread_alive. */
3121 do_cleanups (old_chain);
3125 * Collect a descriptive string about the given thread.
3126 * The target may say anything it wants to about the thread
3127 * (typically info about its blocked / runnable state, name, etc.).
3128 * This string will appear in the info threads display.
3130 * Optional: targets are not required to implement this function.
3134 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3136 struct remote_state *rs = get_remote_state ();
3140 struct gdb_ext_thread_info threadinfo;
3141 static char display_buf[100]; /* arbitrary... */
3142 int n = 0; /* position in display_buf */
3144 if (rs->remote_desc == 0) /* paranoia */
3145 internal_error (__FILE__, __LINE__,
3146 _("remote_threads_extra_info"));
3148 if (ptid_equal (tp->ptid, magic_null_ptid)
3149 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3150 /* This is the main thread which was added by GDB. The remote
3151 server doesn't know about it. */
3154 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3156 struct thread_info *info = find_thread_ptid (tp->ptid);
3158 if (info && info->priv)
3159 return info->priv->extra;
3164 if (rs->use_threadextra_query)
3167 char *endb = rs->buf + get_remote_packet_size ();
3169 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3171 write_ptid (b, endb, tp->ptid);
3174 getpkt (&rs->buf, &rs->buf_size, 0);
3175 if (rs->buf[0] != 0)
3177 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3178 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3179 display_buf [result] = '\0';
3184 /* If the above query fails, fall back to the old method. */
3185 rs->use_threadextra_query = 0;
3186 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3187 | TAG_MOREDISPLAY | TAG_DISPLAY;
3188 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3189 if (remote_get_threadinfo (&id, set, &threadinfo))
3190 if (threadinfo.active)
3192 if (*threadinfo.shortname)
3193 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3194 " Name: %s,", threadinfo.shortname);
3195 if (*threadinfo.display)
3196 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3197 " State: %s,", threadinfo.display);
3198 if (*threadinfo.more_display)
3199 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3200 " Priority: %s", threadinfo.more_display);
3204 /* For purely cosmetic reasons, clear up trailing commas. */
3205 if (',' == display_buf[n-1])
3206 display_buf[n-1] = ' ';
3215 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3216 struct static_tracepoint_marker *marker)
3218 struct remote_state *rs = get_remote_state ();
3221 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3223 p += hexnumstr (p, addr);
3225 getpkt (&rs->buf, &rs->buf_size, 0);
3229 error (_("Remote failure reply: %s"), p);
3233 parse_static_tracepoint_marker_definition (p, &p, marker);
3240 static VEC(static_tracepoint_marker_p) *
3241 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3244 struct remote_state *rs = get_remote_state ();
3245 VEC(static_tracepoint_marker_p) *markers = NULL;
3246 struct static_tracepoint_marker *marker = NULL;
3247 struct cleanup *old_chain;
3250 /* Ask for a first packet of static tracepoint marker
3253 getpkt (&rs->buf, &rs->buf_size, 0);
3256 error (_("Remote failure reply: %s"), p);
3258 old_chain = make_cleanup (free_current_marker, &marker);
3263 marker = XCNEW (struct static_tracepoint_marker);
3267 parse_static_tracepoint_marker_definition (p, &p, marker);
3269 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3271 VEC_safe_push (static_tracepoint_marker_p,
3277 release_static_tracepoint_marker (marker);
3278 memset (marker, 0, sizeof (*marker));
3281 while (*p++ == ','); /* comma-separated list */
3282 /* Ask for another packet of static tracepoint definition. */
3284 getpkt (&rs->buf, &rs->buf_size, 0);
3288 do_cleanups (old_chain);
3293 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3296 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3298 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3302 /* Restart the remote side; this is an extended protocol operation. */
3305 extended_remote_restart (void)
3307 struct remote_state *rs = get_remote_state ();
3309 /* Send the restart command; for reasons I don't understand the
3310 remote side really expects a number after the "R". */
3311 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3314 remote_fileio_reset ();
3317 /* Clean up connection to a remote debugger. */
3320 remote_close (struct target_ops *self)
3322 struct remote_state *rs = get_remote_state ();
3324 if (rs->remote_desc == NULL)
3325 return; /* already closed */
3327 /* Make sure we leave stdin registered in the event loop, and we
3328 don't leave the async SIGINT signal handler installed. */
3329 remote_terminal_ours (self);
3331 serial_close (rs->remote_desc);
3332 rs->remote_desc = NULL;
3334 /* We don't have a connection to the remote stub anymore. Get rid
3335 of all the inferiors and their threads we were controlling.
3336 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3337 will be unable to find the thread corresponding to (pid, 0, 0). */
3338 inferior_ptid = null_ptid;
3339 discard_all_inferiors ();
3341 /* We are closing the remote target, so we should discard
3342 everything of this target. */
3343 discard_pending_stop_replies_in_queue (rs);
3345 if (remote_async_inferior_event_token)
3346 delete_async_event_handler (&remote_async_inferior_event_token);
3348 remote_notif_state_xfree (rs->notif_state);
3350 trace_reset_local_state ();
3353 /* Query the remote side for the text, data and bss offsets. */
3358 struct remote_state *rs = get_remote_state ();
3361 int lose, num_segments = 0, do_sections, do_segments;
3362 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3363 struct section_offsets *offs;
3364 struct symfile_segment_data *data;
3366 if (symfile_objfile == NULL)
3369 putpkt ("qOffsets");
3370 getpkt (&rs->buf, &rs->buf_size, 0);
3373 if (buf[0] == '\000')
3374 return; /* Return silently. Stub doesn't support
3378 warning (_("Remote failure reply: %s"), buf);
3382 /* Pick up each field in turn. This used to be done with scanf, but
3383 scanf will make trouble if CORE_ADDR size doesn't match
3384 conversion directives correctly. The following code will work
3385 with any size of CORE_ADDR. */
3386 text_addr = data_addr = bss_addr = 0;
3390 if (startswith (ptr, "Text="))
3393 /* Don't use strtol, could lose on big values. */
3394 while (*ptr && *ptr != ';')
3395 text_addr = (text_addr << 4) + fromhex (*ptr++);
3397 if (startswith (ptr, ";Data="))
3400 while (*ptr && *ptr != ';')
3401 data_addr = (data_addr << 4) + fromhex (*ptr++);
3406 if (!lose && startswith (ptr, ";Bss="))
3409 while (*ptr && *ptr != ';')
3410 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3412 if (bss_addr != data_addr)
3413 warning (_("Target reported unsupported offsets: %s"), buf);
3418 else if (startswith (ptr, "TextSeg="))
3421 /* Don't use strtol, could lose on big values. */
3422 while (*ptr && *ptr != ';')
3423 text_addr = (text_addr << 4) + fromhex (*ptr++);
3426 if (startswith (ptr, ";DataSeg="))
3429 while (*ptr && *ptr != ';')
3430 data_addr = (data_addr << 4) + fromhex (*ptr++);
3438 error (_("Malformed response to offset query, %s"), buf);
3439 else if (*ptr != '\0')
3440 warning (_("Target reported unsupported offsets: %s"), buf);
3442 offs = ((struct section_offsets *)
3443 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3444 memcpy (offs, symfile_objfile->section_offsets,
3445 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3447 data = get_symfile_segment_data (symfile_objfile->obfd);
3448 do_segments = (data != NULL);
3449 do_sections = num_segments == 0;
3451 if (num_segments > 0)
3453 segments[0] = text_addr;
3454 segments[1] = data_addr;
3456 /* If we have two segments, we can still try to relocate everything
3457 by assuming that the .text and .data offsets apply to the whole
3458 text and data segments. Convert the offsets given in the packet
3459 to base addresses for symfile_map_offsets_to_segments. */
3460 else if (data && data->num_segments == 2)
3462 segments[0] = data->segment_bases[0] + text_addr;
3463 segments[1] = data->segment_bases[1] + data_addr;
3466 /* If the object file has only one segment, assume that it is text
3467 rather than data; main programs with no writable data are rare,
3468 but programs with no code are useless. Of course the code might
3469 have ended up in the data segment... to detect that we would need
3470 the permissions here. */
3471 else if (data && data->num_segments == 1)
3473 segments[0] = data->segment_bases[0] + text_addr;
3476 /* There's no way to relocate by segment. */
3482 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3483 offs, num_segments, segments);
3485 if (ret == 0 && !do_sections)
3486 error (_("Can not handle qOffsets TextSeg "
3487 "response with this symbol file"));
3494 free_symfile_segment_data (data);
3498 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3500 /* This is a temporary kludge to force data and bss to use the
3501 same offsets because that's what nlmconv does now. The real
3502 solution requires changes to the stub and remote.c that I
3503 don't have time to do right now. */
3505 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3506 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3509 objfile_relocate (symfile_objfile, offs);
3512 /* Send interrupt_sequence to remote target. */
3514 send_interrupt_sequence (void)
3516 struct remote_state *rs = get_remote_state ();
3518 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3519 remote_serial_write ("\x03", 1);
3520 else if (interrupt_sequence_mode == interrupt_sequence_break)
3521 serial_send_break (rs->remote_desc);
3522 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3524 serial_send_break (rs->remote_desc);
3525 remote_serial_write ("g", 1);
3528 internal_error (__FILE__, __LINE__,
3529 _("Invalid value for interrupt_sequence_mode: %s."),
3530 interrupt_sequence_mode);
3534 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3535 and extract the PTID. Returns NULL_PTID if not found. */
3538 stop_reply_extract_thread (char *stop_reply)
3540 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3544 /* Txx r:val ; r:val (...) */
3547 /* Look for "register" named "thread". */
3552 p1 = strchr (p, ':');
3556 if (strncmp (p, "thread", p1 - p) == 0)
3557 return read_ptid (++p1, &p);
3559 p1 = strchr (p, ';');
3571 /* Determine the remote side's current thread. If we have a stop
3572 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3573 "thread" register we can extract the current thread from. If not,
3574 ask the remote which is the current thread with qC. The former
3575 method avoids a roundtrip. */
3578 get_current_thread (char *wait_status)
3580 ptid_t ptid = null_ptid;
3582 /* Note we don't use remote_parse_stop_reply as that makes use of
3583 the target architecture, which we haven't yet fully determined at
3585 if (wait_status != NULL)
3586 ptid = stop_reply_extract_thread (wait_status);
3587 if (ptid_equal (ptid, null_ptid))
3588 ptid = remote_current_thread (inferior_ptid);
3593 /* Query the remote target for which is the current thread/process,
3594 add it to our tables, and update INFERIOR_PTID. The caller is
3595 responsible for setting the state such that the remote end is ready
3596 to return the current thread.
3598 This function is called after handling the '?' or 'vRun' packets,
3599 whose response is a stop reply from which we can also try
3600 extracting the thread. If the target doesn't support the explicit
3601 qC query, we infer the current thread from that stop reply, passed
3602 in in WAIT_STATUS, which may be NULL. */
3605 add_current_inferior_and_thread (char *wait_status)
3607 struct remote_state *rs = get_remote_state ();
3611 inferior_ptid = null_ptid;
3613 /* Now, if we have thread information, update inferior_ptid. */
3614 ptid = get_current_thread (wait_status);
3616 if (!ptid_equal (ptid, null_ptid))
3618 if (!remote_multi_process_p (rs))
3621 inferior_ptid = ptid;
3625 /* Without this, some commands which require an active target
3626 (such as kill) won't work. This variable serves (at least)
3627 double duty as both the pid of the target process (if it has
3628 such), and as a flag indicating that a target is active. */
3629 inferior_ptid = magic_null_ptid;
3633 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3635 /* Add the main thread. */
3636 add_thread_silent (inferior_ptid);
3639 /* Process all initial stop replies the remote side sent in response
3640 to the ? packet. These indicate threads that were already stopped
3641 on initial connection. We mark these threads as stopped and print
3642 their current frame before giving the user the prompt. */
3645 process_initial_stop_replies (void)
3647 int pending_stop_replies = stop_reply_queue_length ();
3649 /* Consume the initial pending events. */
3650 while (pending_stop_replies-- > 0)
3652 ptid_t waiton_ptid = minus_one_ptid;
3654 struct target_waitstatus ws;
3655 int ignore_event = 0;
3657 memset (&ws, 0, sizeof (ws));
3658 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3660 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3664 case TARGET_WAITKIND_IGNORE:
3665 case TARGET_WAITKIND_NO_RESUMED:
3666 case TARGET_WAITKIND_SIGNALLED:
3667 case TARGET_WAITKIND_EXITED:
3668 /* We shouldn't see these, but if we do, just ignore. */
3670 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3674 case TARGET_WAITKIND_EXECD:
3675 xfree (ws.value.execd_pathname);
3684 switch_to_thread (event_ptid);
3685 set_executing (event_ptid, 0);
3686 set_running (event_ptid, 0);
3688 stop_pc = get_frame_pc (get_current_frame ());
3689 set_current_sal_from_frame (get_current_frame ());
3691 if (ws.kind == TARGET_WAITKIND_STOPPED)
3693 enum gdb_signal sig = ws.value.sig;
3695 /* Stubs traditionally report SIGTRAP as initial signal,
3696 instead of signal 0. Suppress it. */
3697 if (sig == GDB_SIGNAL_TRAP)
3699 inferior_thread ()->suspend.stop_signal = sig;
3701 if (signal_print_state (sig))
3702 observer_notify_signal_received (sig);
3705 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
3706 observer_notify_normal_stop (NULL, 1);
3711 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3713 struct remote_state *rs = get_remote_state ();
3714 struct packet_config *noack_config;
3715 char *wait_status = NULL;
3717 immediate_quit++; /* Allow user to interrupt it. */
3720 if (interrupt_on_connect)
3721 send_interrupt_sequence ();
3723 /* Ack any packet which the remote side has already sent. */
3724 serial_write (rs->remote_desc, "+", 1);
3726 /* Signal other parts that we're going through the initial setup,
3727 and so things may not be stable yet. */
3728 rs->starting_up = 1;
3730 /* The first packet we send to the target is the optional "supported
3731 packets" request. If the target can answer this, it will tell us
3732 which later probes to skip. */
3733 remote_query_supported ();
3735 /* If the stub wants to get a QAllow, compose one and send it. */
3736 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3737 remote_set_permissions (target);
3739 /* Next, we possibly activate noack mode.
3741 If the QStartNoAckMode packet configuration is set to AUTO,
3742 enable noack mode if the stub reported a wish for it with
3745 If set to TRUE, then enable noack mode even if the stub didn't
3746 report it in qSupported. If the stub doesn't reply OK, the
3747 session ends with an error.
3749 If FALSE, then don't activate noack mode, regardless of what the
3750 stub claimed should be the default with qSupported. */
3752 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3753 if (packet_config_support (noack_config) != PACKET_DISABLE)
3755 putpkt ("QStartNoAckMode");
3756 getpkt (&rs->buf, &rs->buf_size, 0);
3757 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3763 /* Tell the remote that we are using the extended protocol. */
3765 getpkt (&rs->buf, &rs->buf_size, 0);
3768 /* Let the target know which signals it is allowed to pass down to
3770 update_signals_program_target ();
3772 /* Next, if the target can specify a description, read it. We do
3773 this before anything involving memory or registers. */
3774 target_find_description ();
3776 /* Next, now that we know something about the target, update the
3777 address spaces in the program spaces. */
3778 update_address_spaces ();
3780 /* On OSs where the list of libraries is global to all
3781 processes, we fetch them early. */
3782 if (gdbarch_has_global_solist (target_gdbarch ()))
3783 solib_add (NULL, from_tty, target, auto_solib_add);
3787 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3788 error (_("Non-stop mode requested, but remote "
3789 "does not support non-stop"));
3791 putpkt ("QNonStop:1");
3792 getpkt (&rs->buf, &rs->buf_size, 0);
3794 if (strcmp (rs->buf, "OK") != 0)
3795 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3797 /* Find about threads and processes the stub is already
3798 controlling. We default to adding them in the running state.
3799 The '?' query below will then tell us about which threads are
3801 remote_update_thread_list (target);
3803 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3805 /* Don't assume that the stub can operate in all-stop mode.
3806 Request it explicitly. */
3807 putpkt ("QNonStop:0");
3808 getpkt (&rs->buf, &rs->buf_size, 0);
3810 if (strcmp (rs->buf, "OK") != 0)
3811 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3814 /* Upload TSVs regardless of whether the target is running or not. The
3815 remote stub, such as GDBserver, may have some predefined or builtin
3816 TSVs, even if the target is not running. */
3817 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3819 struct uploaded_tsv *uploaded_tsvs = NULL;
3821 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3822 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3825 /* Check whether the target is running now. */
3827 getpkt (&rs->buf, &rs->buf_size, 0);
3833 struct inferior *inf;
3835 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3838 error (_("The target is not running (try extended-remote?)"));
3840 /* We're connected, but not running. Drop out before we
3841 call start_remote. */
3842 rs->starting_up = 0;
3847 /* Save the reply for later. */
3848 wait_status = alloca (strlen (rs->buf) + 1);
3849 strcpy (wait_status, rs->buf);
3852 /* Fetch thread list. */
3853 target_update_thread_list ();
3855 /* Let the stub know that we want it to return the thread. */
3856 set_continue_thread (minus_one_ptid);
3858 if (thread_count () == 0)
3860 /* Target has no concept of threads at all. GDB treats
3861 non-threaded target as single-threaded; add a main
3863 add_current_inferior_and_thread (wait_status);
3867 /* We have thread information; select the thread the target
3868 says should be current. If we're reconnecting to a
3869 multi-threaded program, this will ideally be the thread
3870 that last reported an event before GDB disconnected. */
3871 inferior_ptid = get_current_thread (wait_status);
3872 if (ptid_equal (inferior_ptid, null_ptid))
3874 /* Odd... The target was able to list threads, but not
3875 tell us which thread was current (no "thread"
3876 register in T stop reply?). Just pick the first
3877 thread in the thread list then. */
3880 fprintf_unfiltered (gdb_stdlog,
3881 "warning: couldn't determine remote "
3882 "current thread; picking first in list.\n");
3884 inferior_ptid = thread_list->ptid;
3888 /* init_wait_for_inferior should be called before get_offsets in order
3889 to manage `inserted' flag in bp loc in a correct state.
3890 breakpoint_init_inferior, called from init_wait_for_inferior, set
3891 `inserted' flag to 0, while before breakpoint_re_set, called from
3892 start_remote, set `inserted' flag to 1. In the initialization of
3893 inferior, breakpoint_init_inferior should be called first, and then
3894 breakpoint_re_set can be called. If this order is broken, state of
3895 `inserted' flag is wrong, and cause some problems on breakpoint
3897 init_wait_for_inferior ();
3899 get_offsets (); /* Get text, data & bss offsets. */
3901 /* If we could not find a description using qXfer, and we know
3902 how to do it some other way, try again. This is not
3903 supported for non-stop; it could be, but it is tricky if
3904 there are no stopped threads when we connect. */
3905 if (remote_read_description_p (target)
3906 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3908 target_clear_description ();
3909 target_find_description ();
3912 /* Use the previously fetched status. */
3913 gdb_assert (wait_status != NULL);
3914 strcpy (rs->buf, wait_status);
3915 rs->cached_wait_status = 1;
3918 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3922 ptid_t current_ptid;
3924 /* Clear WFI global state. Do this before finding about new
3925 threads and inferiors, and setting the current inferior.
3926 Otherwise we would clear the proceed status of the current
3927 inferior when we want its stop_soon state to be preserved
3928 (see notice_new_inferior). */
3929 init_wait_for_inferior ();
3931 /* In non-stop, we will either get an "OK", meaning that there
3932 are no stopped threads at this time; or, a regular stop
3933 reply. In the latter case, there may be more than one thread
3934 stopped --- we pull them all out using the vStopped
3936 if (strcmp (rs->buf, "OK") != 0)
3938 struct notif_client *notif = ¬if_client_stop;
3940 /* remote_notif_get_pending_replies acks this one, and gets
3942 rs->notif_state->pending_event[notif_client_stop.id]
3943 = remote_notif_parse (notif, rs->buf);
3944 remote_notif_get_pending_events (notif);
3947 if (thread_count () == 0)
3950 error (_("The target is not running (try extended-remote?)"));
3952 /* We're connected, but not running. Drop out before we
3953 call start_remote. */
3954 rs->starting_up = 0;
3958 /* Let the stub know that we want it to return the thread. */
3960 /* Force the stub to choose a thread. */
3961 set_general_thread (null_ptid);
3964 current_ptid = remote_current_thread (minus_one_ptid);
3965 if (ptid_equal (inferior_ptid, minus_one_ptid))
3966 error (_("remote didn't report the current thread in non-stop mode"));
3968 inferior_ptid = current_ptid;
3969 get_offsets (); /* Get text, data & bss offsets. */
3971 /* In non-stop mode, any cached wait status will be stored in
3972 the stop reply queue. */
3973 gdb_assert (wait_status == NULL);
3975 /* Report all signals during attach/startup. */
3976 remote_pass_signals (target, 0, NULL);
3978 /* If there are already stopped threads, mark them stopped and
3979 report their stops before giving the prompt to the user. */
3980 process_initial_stop_replies ();
3982 switch_to_thread (current_ptid);
3984 if (target_can_async_p ())
3988 /* If we connected to a live target, do some additional setup. */
3989 if (target_has_execution)
3991 if (symfile_objfile) /* No use without a symbol-file. */
3992 remote_check_symbols ();
3995 /* Possibly the target has been engaged in a trace run started
3996 previously; find out where things are at. */
3997 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3999 struct uploaded_tp *uploaded_tps = NULL;
4001 if (current_trace_status ()->running)
4002 printf_filtered (_("Trace is already running on the target.\n"));
4004 remote_upload_tracepoints (target, &uploaded_tps);
4006 merge_uploaded_tracepoints (&uploaded_tps);
4009 /* The thread and inferior lists are now synchronized with the
4010 target, our symbols have been relocated, and we're merged the
4011 target's tracepoints with ours. We're done with basic start
4013 rs->starting_up = 0;
4015 /* Maybe breakpoints are global and need to be inserted now. */
4016 if (breakpoints_should_be_inserted_now ())
4017 insert_breakpoints ();
4020 /* Open a connection to a remote debugger.
4021 NAME is the filename used for communication. */
4024 remote_open (const char *name, int from_tty)
4026 remote_open_1 (name, from_tty, &remote_ops, 0);
4029 /* Open a connection to a remote debugger using the extended
4030 remote gdb protocol. NAME is the filename used for communication. */
4033 extended_remote_open (const char *name, int from_tty)
4035 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4038 /* Reset all packets back to "unknown support". Called when opening a
4039 new connection to a remote target. */
4042 reset_all_packet_configs_support (void)
4046 for (i = 0; i < PACKET_MAX; i++)
4047 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4050 /* Initialize all packet configs. */
4053 init_all_packet_configs (void)
4057 for (i = 0; i < PACKET_MAX; i++)
4059 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4060 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4064 /* Symbol look-up. */
4067 remote_check_symbols (void)
4069 struct remote_state *rs = get_remote_state ();
4070 char *msg, *reply, *tmp;
4071 struct bound_minimal_symbol sym;
4073 struct cleanup *old_chain;
4075 /* The remote side has no concept of inferiors that aren't running
4076 yet, it only knows about running processes. If we're connected
4077 but our current inferior is not running, we should not invite the
4078 remote target to request symbol lookups related to its
4079 (unrelated) current process. */
4080 if (!target_has_execution)
4083 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4086 /* Make sure the remote is pointing at the right process. Note
4087 there's no way to select "no process". */
4088 set_general_process ();
4090 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4091 because we need both at the same time. */
4092 msg = xmalloc (get_remote_packet_size ());
4093 old_chain = make_cleanup (xfree, msg);
4095 /* Invite target to request symbol lookups. */
4097 putpkt ("qSymbol::");
4098 getpkt (&rs->buf, &rs->buf_size, 0);
4099 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4102 while (startswith (reply, "qSymbol:"))
4104 struct bound_minimal_symbol sym;
4107 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4109 sym = lookup_minimal_symbol (msg, NULL, NULL);
4110 if (sym.minsym == NULL)
4111 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4114 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4115 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4117 /* If this is a function address, return the start of code
4118 instead of any data function descriptor. */
4119 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4123 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4124 phex_nz (sym_addr, addr_size), &reply[8]);
4128 getpkt (&rs->buf, &rs->buf_size, 0);
4132 do_cleanups (old_chain);
4135 static struct serial *
4136 remote_serial_open (const char *name)
4138 static int udp_warning = 0;
4140 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4141 of in ser-tcp.c, because it is the remote protocol assuming that the
4142 serial connection is reliable and not the serial connection promising
4144 if (!udp_warning && startswith (name, "udp:"))
4146 warning (_("The remote protocol may be unreliable over UDP.\n"
4147 "Some events may be lost, rendering further debugging "
4152 return serial_open (name);
4155 /* Inform the target of our permission settings. The permission flags
4156 work without this, but if the target knows the settings, it can do
4157 a couple things. First, it can add its own check, to catch cases
4158 that somehow manage to get by the permissions checks in target
4159 methods. Second, if the target is wired to disallow particular
4160 settings (for instance, a system in the field that is not set up to
4161 be able to stop at a breakpoint), it can object to any unavailable
4165 remote_set_permissions (struct target_ops *self)
4167 struct remote_state *rs = get_remote_state ();
4169 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4170 "WriteReg:%x;WriteMem:%x;"
4171 "InsertBreak:%x;InsertTrace:%x;"
4172 "InsertFastTrace:%x;Stop:%x",
4173 may_write_registers, may_write_memory,
4174 may_insert_breakpoints, may_insert_tracepoints,
4175 may_insert_fast_tracepoints, may_stop);
4177 getpkt (&rs->buf, &rs->buf_size, 0);
4179 /* If the target didn't like the packet, warn the user. Do not try
4180 to undo the user's settings, that would just be maddening. */
4181 if (strcmp (rs->buf, "OK") != 0)
4182 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4185 /* This type describes each known response to the qSupported
4187 struct protocol_feature
4189 /* The name of this protocol feature. */
4192 /* The default for this protocol feature. */
4193 enum packet_support default_support;
4195 /* The function to call when this feature is reported, or after
4196 qSupported processing if the feature is not supported.
4197 The first argument points to this structure. The second
4198 argument indicates whether the packet requested support be
4199 enabled, disabled, or probed (or the default, if this function
4200 is being called at the end of processing and this feature was
4201 not reported). The third argument may be NULL; if not NULL, it
4202 is a NUL-terminated string taken from the packet following
4203 this feature's name and an equals sign. */
4204 void (*func) (const struct protocol_feature *, enum packet_support,
4207 /* The corresponding packet for this feature. Only used if
4208 FUNC is remote_supported_packet. */
4213 remote_supported_packet (const struct protocol_feature *feature,
4214 enum packet_support support,
4215 const char *argument)
4219 warning (_("Remote qSupported response supplied an unexpected value for"
4220 " \"%s\"."), feature->name);
4224 remote_protocol_packets[feature->packet].support = support;
4228 remote_packet_size (const struct protocol_feature *feature,
4229 enum packet_support support, const char *value)
4231 struct remote_state *rs = get_remote_state ();
4236 if (support != PACKET_ENABLE)
4239 if (value == NULL || *value == '\0')
4241 warning (_("Remote target reported \"%s\" without a size."),
4247 packet_size = strtol (value, &value_end, 16);
4248 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4250 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4251 feature->name, value);
4255 /* Record the new maximum packet size. */
4256 rs->explicit_packet_size = packet_size;
4259 static const struct protocol_feature remote_protocol_features[] = {
4260 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4261 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4262 PACKET_qXfer_auxv },
4263 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4264 PACKET_qXfer_exec_file },
4265 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4266 PACKET_qXfer_features },
4267 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4268 PACKET_qXfer_libraries },
4269 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4270 PACKET_qXfer_libraries_svr4 },
4271 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4272 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4273 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4274 PACKET_qXfer_memory_map },
4275 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4276 PACKET_qXfer_spu_read },
4277 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4278 PACKET_qXfer_spu_write },
4279 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4280 PACKET_qXfer_osdata },
4281 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4282 PACKET_qXfer_threads },
4283 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4284 PACKET_qXfer_traceframe_info },
4285 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4286 PACKET_QPassSignals },
4287 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4288 PACKET_QProgramSignals },
4289 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4290 PACKET_QStartNoAckMode },
4291 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4292 PACKET_multiprocess_feature },
4293 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4294 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4295 PACKET_qXfer_siginfo_read },
4296 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4297 PACKET_qXfer_siginfo_write },
4298 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4299 PACKET_ConditionalTracepoints },
4300 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4301 PACKET_ConditionalBreakpoints },
4302 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4303 PACKET_BreakpointCommands },
4304 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4305 PACKET_FastTracepoints },
4306 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4307 PACKET_StaticTracepoints },
4308 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4309 PACKET_InstallInTrace},
4310 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4311 PACKET_DisconnectedTracing_feature },
4312 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4314 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4316 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4317 PACKET_TracepointSource },
4318 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4320 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4321 PACKET_EnableDisableTracepoints_feature },
4322 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4323 PACKET_qXfer_fdpic },
4324 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4326 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4327 PACKET_QDisableRandomization },
4328 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4329 { "QTBuffer:size", PACKET_DISABLE,
4330 remote_supported_packet, PACKET_QTBuffer_size},
4331 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4332 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4333 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4334 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4335 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4336 PACKET_qXfer_btrace },
4337 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4338 PACKET_qXfer_btrace_conf },
4339 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4340 PACKET_Qbtrace_conf_bts_size },
4341 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4342 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4343 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4344 PACKET_fork_event_feature },
4345 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4346 PACKET_vfork_event_feature },
4347 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4348 PACKET_exec_event_feature },
4349 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4350 PACKET_Qbtrace_conf_pt_size }
4353 static char *remote_support_xml;
4355 /* Register string appended to "xmlRegisters=" in qSupported query. */
4358 register_remote_support_xml (const char *xml)
4360 #if defined(HAVE_LIBEXPAT)
4361 if (remote_support_xml == NULL)
4362 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4365 char *copy = xstrdup (remote_support_xml + 13);
4366 char *p = strtok (copy, ",");
4370 if (strcmp (p, xml) == 0)
4377 while ((p = strtok (NULL, ",")) != NULL);
4380 remote_support_xml = reconcat (remote_support_xml,
4381 remote_support_xml, ",", xml,
4388 remote_query_supported_append (char *msg, const char *append)
4391 return reconcat (msg, msg, ";", append, (char *) NULL);
4393 return xstrdup (append);
4397 remote_query_supported (void)
4399 struct remote_state *rs = get_remote_state ();
4402 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4404 /* The packet support flags are handled differently for this packet
4405 than for most others. We treat an error, a disabled packet, and
4406 an empty response identically: any features which must be reported
4407 to be used will be automatically disabled. An empty buffer
4408 accomplishes this, since that is also the representation for a list
4409 containing no features. */
4412 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4415 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4417 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4418 q = remote_query_supported_append (q, "multiprocess+");
4420 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4421 q = remote_query_supported_append (q, "swbreak+");
4422 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4423 q = remote_query_supported_append (q, "hwbreak+");
4425 if (remote_support_xml)
4426 q = remote_query_supported_append (q, remote_support_xml);
4428 q = remote_query_supported_append (q, "qRelocInsn+");
4432 if (packet_set_cmd_state (PACKET_fork_event_feature)
4433 != AUTO_BOOLEAN_FALSE)
4434 q = remote_query_supported_append (q, "fork-events+");
4435 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4436 != AUTO_BOOLEAN_FALSE)
4437 q = remote_query_supported_append (q, "vfork-events+");
4438 if (packet_set_cmd_state (PACKET_exec_event_feature)
4439 != AUTO_BOOLEAN_FALSE)
4440 q = remote_query_supported_append (q, "exec-events+");
4443 q = reconcat (q, "qSupported:", q, (char *) NULL);
4446 do_cleanups (old_chain);
4448 getpkt (&rs->buf, &rs->buf_size, 0);
4450 /* If an error occured, warn, but do not return - just reset the
4451 buffer to empty and go on to disable features. */
4452 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4455 warning (_("Remote failure reply: %s"), rs->buf);
4460 memset (seen, 0, sizeof (seen));
4465 enum packet_support is_supported;
4466 char *p, *end, *name_end, *value;
4468 /* First separate out this item from the rest of the packet. If
4469 there's another item after this, we overwrite the separator
4470 (terminated strings are much easier to work with). */
4472 end = strchr (p, ';');
4475 end = p + strlen (p);
4485 warning (_("empty item in \"qSupported\" response"));
4490 name_end = strchr (p, '=');
4493 /* This is a name=value entry. */
4494 is_supported = PACKET_ENABLE;
4495 value = name_end + 1;
4504 is_supported = PACKET_ENABLE;
4508 is_supported = PACKET_DISABLE;
4512 is_supported = PACKET_SUPPORT_UNKNOWN;
4516 warning (_("unrecognized item \"%s\" "
4517 "in \"qSupported\" response"), p);
4523 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4524 if (strcmp (remote_protocol_features[i].name, p) == 0)
4526 const struct protocol_feature *feature;
4529 feature = &remote_protocol_features[i];
4530 feature->func (feature, is_supported, value);
4535 /* If we increased the packet size, make sure to increase the global
4536 buffer size also. We delay this until after parsing the entire
4537 qSupported packet, because this is the same buffer we were
4539 if (rs->buf_size < rs->explicit_packet_size)
4541 rs->buf_size = rs->explicit_packet_size;
4542 rs->buf = xrealloc (rs->buf, rs->buf_size);
4545 /* Handle the defaults for unmentioned features. */
4546 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4549 const struct protocol_feature *feature;
4551 feature = &remote_protocol_features[i];
4552 feature->func (feature, feature->default_support, NULL);
4556 /* Remove any of the remote.c targets from target stack. Upper targets depend
4557 on it so remove them first. */
4560 remote_unpush_target (void)
4562 pop_all_targets_above (process_stratum - 1);
4566 remote_open_1 (const char *name, int from_tty,
4567 struct target_ops *target, int extended_p)
4569 struct remote_state *rs = get_remote_state ();
4572 error (_("To open a remote debug connection, you need to specify what\n"
4573 "serial device is attached to the remote system\n"
4574 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4576 /* See FIXME above. */
4577 if (!target_async_permitted)
4578 wait_forever_enabled_p = 1;
4580 /* If we're connected to a running target, target_preopen will kill it.
4581 Ask this question first, before target_preopen has a chance to kill
4583 if (rs->remote_desc != NULL && !have_inferiors ())
4586 && !query (_("Already connected to a remote target. Disconnect? ")))
4587 error (_("Still connected."));
4590 /* Here the possibly existing remote target gets unpushed. */
4591 target_preopen (from_tty);
4593 /* Make sure we send the passed signals list the next time we resume. */
4594 xfree (rs->last_pass_packet);
4595 rs->last_pass_packet = NULL;
4597 /* Make sure we send the program signals list the next time we
4599 xfree (rs->last_program_signals_packet);
4600 rs->last_program_signals_packet = NULL;
4602 remote_fileio_reset ();
4603 reopen_exec_file ();
4606 rs->remote_desc = remote_serial_open (name);
4607 if (!rs->remote_desc)
4608 perror_with_name (name);
4610 if (baud_rate != -1)
4612 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4614 /* The requested speed could not be set. Error out to
4615 top level after closing remote_desc. Take care to
4616 set remote_desc to NULL to avoid closing remote_desc
4618 serial_close (rs->remote_desc);
4619 rs->remote_desc = NULL;
4620 perror_with_name (name);
4624 serial_setparity (rs->remote_desc, serial_parity);
4625 serial_raw (rs->remote_desc);
4627 /* If there is something sitting in the buffer we might take it as a
4628 response to a command, which would be bad. */
4629 serial_flush_input (rs->remote_desc);
4633 puts_filtered ("Remote debugging using ");
4634 puts_filtered (name);
4635 puts_filtered ("\n");
4637 push_target (target); /* Switch to using remote target now. */
4639 /* Register extra event sources in the event loop. */
4640 remote_async_inferior_event_token
4641 = create_async_event_handler (remote_async_inferior_event_handler,
4643 rs->notif_state = remote_notif_state_allocate ();
4645 /* Reset the target state; these things will be queried either by
4646 remote_query_supported or as they are needed. */
4647 reset_all_packet_configs_support ();
4648 rs->cached_wait_status = 0;
4649 rs->explicit_packet_size = 0;
4651 rs->extended = extended_p;
4652 rs->waiting_for_stop_reply = 0;
4653 rs->ctrlc_pending_p = 0;
4655 rs->general_thread = not_sent_ptid;
4656 rs->continue_thread = not_sent_ptid;
4657 rs->remote_traceframe_number = -1;
4659 /* Probe for ability to use "ThreadInfo" query, as required. */
4660 rs->use_threadinfo_query = 1;
4661 rs->use_threadextra_query = 1;
4663 readahead_cache_invalidate ();
4665 if (target_async_permitted)
4667 /* With this target we start out by owning the terminal. */
4668 remote_async_terminal_ours_p = 1;
4670 /* FIXME: cagney/1999-09-23: During the initial connection it is
4671 assumed that the target is already ready and able to respond to
4672 requests. Unfortunately remote_start_remote() eventually calls
4673 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4674 around this. Eventually a mechanism that allows
4675 wait_for_inferior() to expect/get timeouts will be
4677 wait_forever_enabled_p = 0;
4680 /* First delete any symbols previously loaded from shared libraries. */
4681 no_shared_libraries (NULL, 0);
4684 init_thread_list ();
4686 /* Start the remote connection. If error() or QUIT, discard this
4687 target (we'd otherwise be in an inconsistent state) and then
4688 propogate the error on up the exception chain. This ensures that
4689 the caller doesn't stumble along blindly assuming that the
4690 function succeeded. The CLI doesn't have this problem but other
4691 UI's, such as MI do.
4693 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4694 this function should return an error indication letting the
4695 caller restore the previous state. Unfortunately the command
4696 ``target remote'' is directly wired to this function making that
4697 impossible. On a positive note, the CLI side of this problem has
4698 been fixed - the function set_cmd_context() makes it possible for
4699 all the ``target ....'' commands to share a common callback
4700 function. See cli-dump.c. */
4705 remote_start_remote (from_tty, target, extended_p);
4707 CATCH (ex, RETURN_MASK_ALL)
4709 /* Pop the partially set up target - unless something else did
4710 already before throwing the exception. */
4711 if (rs->remote_desc != NULL)
4712 remote_unpush_target ();
4713 if (target_async_permitted)
4714 wait_forever_enabled_p = 1;
4715 throw_exception (ex);
4720 remote_btrace_reset ();
4722 if (target_async_permitted)
4723 wait_forever_enabled_p = 1;
4726 /* Detach the specified process. */
4729 remote_detach_pid (int pid)
4731 struct remote_state *rs = get_remote_state ();
4733 if (remote_multi_process_p (rs))
4734 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4736 strcpy (rs->buf, "D");
4739 getpkt (&rs->buf, &rs->buf_size, 0);
4741 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4743 else if (rs->buf[0] == '\0')
4744 error (_("Remote doesn't know how to detach"));
4746 error (_("Can't detach process."));
4749 /* This detaches a program to which we previously attached, using
4750 inferior_ptid to identify the process. After this is done, GDB
4751 can be used to debug some other program. We better not have left
4752 any breakpoints in the target program or it'll die when it hits
4756 remote_detach_1 (const char *args, int from_tty)
4758 int pid = ptid_get_pid (inferior_ptid);
4759 struct remote_state *rs = get_remote_state ();
4760 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4764 error (_("Argument given to \"detach\" when remotely debugging."));
4766 if (!target_has_execution)
4767 error (_("No process to detach from."));
4771 char *exec_file = get_exec_file (0);
4772 if (exec_file == NULL)
4774 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4775 target_pid_to_str (pid_to_ptid (pid)));
4776 gdb_flush (gdb_stdout);
4779 /* Tell the remote target to detach. */
4780 remote_detach_pid (pid);
4782 if (from_tty && !rs->extended)
4783 puts_filtered (_("Ending remote debugging.\n"));
4785 /* Check to see if we are detaching a fork parent. Note that if we
4786 are detaching a fork child, tp == NULL. */
4787 is_fork_parent = (tp != NULL
4788 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4790 /* If doing detach-on-fork, we don't mourn, because that will delete
4791 breakpoints that should be available for the followed inferior. */
4792 if (!is_fork_parent)
4793 target_mourn_inferior ();
4796 inferior_ptid = null_ptid;
4797 detach_inferior (pid);
4802 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4804 remote_detach_1 (args, from_tty);
4808 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4810 remote_detach_1 (args, from_tty);
4813 /* Target follow-fork function for remote targets. On entry, and
4814 at return, the current inferior is the fork parent.
4816 Note that although this is currently only used for extended-remote,
4817 it is named remote_follow_fork in anticipation of using it for the
4818 remote target as well. */
4821 remote_follow_fork (struct target_ops *ops, int follow_child,
4824 struct remote_state *rs = get_remote_state ();
4825 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
4827 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4828 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
4830 /* When following the parent and detaching the child, we detach
4831 the child here. For the case of following the child and
4832 detaching the parent, the detach is done in the target-
4833 independent follow fork code in infrun.c. We can't use
4834 target_detach when detaching an unfollowed child because
4835 the client side doesn't know anything about the child. */
4836 if (detach_fork && !follow_child)
4838 /* Detach the fork child. */
4842 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4843 child_pid = ptid_get_pid (child_ptid);
4845 remote_detach_pid (child_pid);
4846 detach_inferior (child_pid);
4852 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
4853 in the program space of the new inferior. On entry and at return the
4854 current inferior is the exec'ing inferior. INF is the new exec'd
4855 inferior, which may be the same as the exec'ing inferior unless
4856 follow-exec-mode is "new". */
4859 remote_follow_exec (struct target_ops *ops,
4860 struct inferior *inf, char *execd_pathname)
4862 /* We know that this is a target file name, so if it has the "target:"
4863 prefix we strip it off before saving it in the program space. */
4864 if (is_target_filename (execd_pathname))
4865 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
4867 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
4870 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4873 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4876 error (_("Argument given to \"disconnect\" when remotely debugging."));
4878 /* Make sure we unpush even the extended remote targets; mourn
4879 won't do it. So call remote_mourn directly instead of
4880 target_mourn_inferior. */
4881 remote_mourn (target);
4884 puts_filtered ("Ending remote debugging.\n");
4887 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4888 be chatty about it. */
4891 extended_remote_attach (struct target_ops *target, const char *args,
4894 struct remote_state *rs = get_remote_state ();
4896 char *wait_status = NULL;
4898 pid = parse_pid_to_attach (args);
4900 /* Remote PID can be freely equal to getpid, do not check it here the same
4901 way as in other targets. */
4903 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4904 error (_("This target does not support attaching to a process"));
4908 char *exec_file = get_exec_file (0);
4911 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4912 target_pid_to_str (pid_to_ptid (pid)));
4914 printf_unfiltered (_("Attaching to %s\n"),
4915 target_pid_to_str (pid_to_ptid (pid)));
4917 gdb_flush (gdb_stdout);
4920 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4922 getpkt (&rs->buf, &rs->buf_size, 0);
4924 switch (packet_ok (rs->buf,
4925 &remote_protocol_packets[PACKET_vAttach]))
4930 /* Save the reply for later. */
4931 wait_status = alloca (strlen (rs->buf) + 1);
4932 strcpy (wait_status, rs->buf);
4934 else if (strcmp (rs->buf, "OK") != 0)
4935 error (_("Attaching to %s failed with: %s"),
4936 target_pid_to_str (pid_to_ptid (pid)),
4939 case PACKET_UNKNOWN:
4940 error (_("This target does not support attaching to a process"));
4942 error (_("Attaching to %s failed"),
4943 target_pid_to_str (pid_to_ptid (pid)));
4946 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
4948 inferior_ptid = pid_to_ptid (pid);
4952 struct thread_info *thread;
4954 /* Get list of threads. */
4955 remote_update_thread_list (target);
4957 thread = first_thread_of_process (pid);
4959 inferior_ptid = thread->ptid;
4961 inferior_ptid = pid_to_ptid (pid);
4963 /* Invalidate our notion of the remote current thread. */
4964 record_currthread (rs, minus_one_ptid);
4968 /* Now, if we have thread information, update inferior_ptid. */
4969 inferior_ptid = remote_current_thread (inferior_ptid);
4971 /* Add the main thread to the thread list. */
4972 add_thread_silent (inferior_ptid);
4975 /* Next, if the target can specify a description, read it. We do
4976 this before anything involving memory or registers. */
4977 target_find_description ();
4981 /* Use the previously fetched status. */
4982 gdb_assert (wait_status != NULL);
4984 if (target_can_async_p ())
4986 struct notif_event *reply
4987 = remote_notif_parse (¬if_client_stop, wait_status);
4989 push_stop_reply ((struct stop_reply *) reply);
4995 gdb_assert (wait_status != NULL);
4996 strcpy (rs->buf, wait_status);
4997 rs->cached_wait_status = 1;
5001 gdb_assert (wait_status == NULL);
5004 /* Implementation of the to_post_attach method. */
5007 extended_remote_post_attach (struct target_ops *ops, int pid)
5009 /* In certain cases GDB might not have had the chance to start
5010 symbol lookup up until now. This could happen if the debugged
5011 binary is not using shared libraries, the vsyscall page is not
5012 present (on Linux) and the binary itself hadn't changed since the
5013 debugging process was started. */
5014 if (symfile_objfile != NULL)
5015 remote_check_symbols();
5019 /* Check for the availability of vCont. This function should also check
5023 remote_vcont_probe (struct remote_state *rs)
5027 strcpy (rs->buf, "vCont?");
5029 getpkt (&rs->buf, &rs->buf_size, 0);
5032 /* Make sure that the features we assume are supported. */
5033 if (startswith (buf, "vCont"))
5036 int support_s, support_S, support_c, support_C;
5042 rs->supports_vCont.t = 0;
5043 rs->supports_vCont.r = 0;
5044 while (p && *p == ';')
5047 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5049 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5051 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5053 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5055 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5056 rs->supports_vCont.t = 1;
5057 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5058 rs->supports_vCont.r = 1;
5060 p = strchr (p, ';');
5063 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
5064 BUF will make packet_ok disable the packet. */
5065 if (!support_s || !support_S || !support_c || !support_C)
5069 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5072 /* Helper function for building "vCont" resumptions. Write a
5073 resumption to P. ENDP points to one-passed-the-end of the buffer
5074 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5075 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5076 resumed thread should be single-stepped and/or signalled. If PTID
5077 equals minus_one_ptid, then all threads are resumed; if PTID
5078 represents a process, then all threads of the process are resumed;
5079 the thread to be stepped and/or signalled is given in the global
5083 append_resumption (char *p, char *endp,
5084 ptid_t ptid, int step, enum gdb_signal siggnal)
5086 struct remote_state *rs = get_remote_state ();
5088 if (step && siggnal != GDB_SIGNAL_0)
5089 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5091 /* GDB is willing to range step. */
5092 && use_range_stepping
5093 /* Target supports range stepping. */
5094 && rs->supports_vCont.r
5095 /* We don't currently support range stepping multiple
5096 threads with a wildcard (though the protocol allows it,
5097 so stubs shouldn't make an active effort to forbid
5099 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5101 struct thread_info *tp;
5103 if (ptid_equal (ptid, minus_one_ptid))
5105 /* If we don't know about the target thread's tid, then
5106 we're resuming magic_null_ptid (see caller). */
5107 tp = find_thread_ptid (magic_null_ptid);
5110 tp = find_thread_ptid (ptid);
5111 gdb_assert (tp != NULL);
5113 if (tp->control.may_range_step)
5115 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5117 p += xsnprintf (p, endp - p, ";r%s,%s",
5118 phex_nz (tp->control.step_range_start,
5120 phex_nz (tp->control.step_range_end,
5124 p += xsnprintf (p, endp - p, ";s");
5127 p += xsnprintf (p, endp - p, ";s");
5128 else if (siggnal != GDB_SIGNAL_0)
5129 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5131 p += xsnprintf (p, endp - p, ";c");
5133 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5137 /* All (-1) threads of process. */
5138 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5140 p += xsnprintf (p, endp - p, ":");
5141 p = write_ptid (p, endp, nptid);
5143 else if (!ptid_equal (ptid, minus_one_ptid))
5145 p += xsnprintf (p, endp - p, ":");
5146 p = write_ptid (p, endp, ptid);
5152 /* Append a vCont continue-with-signal action for threads that have a
5153 non-zero stop signal. */
5156 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5158 struct thread_info *thread;
5160 ALL_NON_EXITED_THREADS (thread)
5161 if (ptid_match (thread->ptid, ptid)
5162 && !ptid_equal (inferior_ptid, thread->ptid)
5163 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5165 p = append_resumption (p, endp, thread->ptid,
5166 0, thread->suspend.stop_signal);
5167 thread->suspend.stop_signal = GDB_SIGNAL_0;
5173 /* Resume the remote inferior by using a "vCont" packet. The thread
5174 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5175 resumed thread should be single-stepped and/or signalled. If PTID
5176 equals minus_one_ptid, then all threads are resumed; the thread to
5177 be stepped and/or signalled is given in the global INFERIOR_PTID.
5178 This function returns non-zero iff it resumes the inferior.
5180 This function issues a strict subset of all possible vCont commands at the
5184 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5186 struct remote_state *rs = get_remote_state ();
5190 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5191 remote_vcont_probe (rs);
5193 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5197 endp = rs->buf + get_remote_packet_size ();
5199 /* If we could generate a wider range of packets, we'd have to worry
5200 about overflowing BUF. Should there be a generic
5201 "multi-part-packet" packet? */
5203 p += xsnprintf (p, endp - p, "vCont");
5205 if (ptid_equal (ptid, magic_null_ptid))
5207 /* MAGIC_NULL_PTID means that we don't have any active threads,
5208 so we don't have any TID numbers the inferior will
5209 understand. Make sure to only send forms that do not specify
5211 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5213 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5215 /* Resume all threads (of all processes, or of a single
5216 process), with preference for INFERIOR_PTID. This assumes
5217 inferior_ptid belongs to the set of all threads we are about
5219 if (step || siggnal != GDB_SIGNAL_0)
5221 /* Step inferior_ptid, with or without signal. */
5222 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5225 /* Also pass down any pending signaled resumption for other
5226 threads not the current. */
5227 p = append_pending_thread_resumptions (p, endp, ptid);
5229 /* And continue others without a signal. */
5230 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5234 /* Scheduler locking; resume only PTID. */
5235 append_resumption (p, endp, ptid, step, siggnal);
5238 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5243 /* In non-stop, the stub replies to vCont with "OK". The stop
5244 reply will be reported asynchronously by means of a `%Stop'
5246 getpkt (&rs->buf, &rs->buf_size, 0);
5247 if (strcmp (rs->buf, "OK") != 0)
5248 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5254 /* Tell the remote machine to resume. */
5257 remote_resume (struct target_ops *ops,
5258 ptid_t ptid, int step, enum gdb_signal siggnal)
5260 struct remote_state *rs = get_remote_state ();
5263 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5264 (explained in remote-notif.c:handle_notification) so
5265 remote_notif_process is not called. We need find a place where
5266 it is safe to start a 'vNotif' sequence. It is good to do it
5267 before resuming inferior, because inferior was stopped and no RSP
5268 traffic at that moment. */
5270 remote_notif_process (rs->notif_state, ¬if_client_stop);
5272 rs->last_sent_signal = siggnal;
5273 rs->last_sent_step = step;
5275 /* The vCont packet doesn't need to specify threads via Hc. */
5276 /* No reverse support (yet) for vCont. */
5277 if (execution_direction != EXEC_REVERSE)
5278 if (remote_vcont_resume (ptid, step, siggnal))
5281 /* All other supported resume packets do use Hc, so set the continue
5283 if (ptid_equal (ptid, minus_one_ptid))
5284 set_continue_thread (any_thread_ptid);
5286 set_continue_thread (ptid);
5289 if (execution_direction == EXEC_REVERSE)
5291 /* We don't pass signals to the target in reverse exec mode. */
5292 if (info_verbose && siggnal != GDB_SIGNAL_0)
5293 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5296 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5297 error (_("Remote reverse-step not supported."));
5298 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5299 error (_("Remote reverse-continue not supported."));
5301 strcpy (buf, step ? "bs" : "bc");
5303 else if (siggnal != GDB_SIGNAL_0)
5305 buf[0] = step ? 'S' : 'C';
5306 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5307 buf[2] = tohex (((int) siggnal) & 0xf);
5311 strcpy (buf, step ? "s" : "c");
5316 /* We are about to start executing the inferior, let's register it
5317 with the event loop. NOTE: this is the one place where all the
5318 execution commands end up. We could alternatively do this in each
5319 of the execution commands in infcmd.c. */
5320 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5321 into infcmd.c in order to allow inferior function calls to work
5322 NOT asynchronously. */
5323 if (target_can_async_p ())
5326 /* We've just told the target to resume. The remote server will
5327 wait for the inferior to stop, and then send a stop reply. In
5328 the mean time, we can't start another command/query ourselves
5329 because the stub wouldn't be ready to process it. This applies
5330 only to the base all-stop protocol, however. In non-stop (which
5331 only supports vCont), the stub replies with an "OK", and is
5332 immediate able to process further serial input. */
5334 rs->waiting_for_stop_reply = 1;
5338 /* Set up the signal handler for SIGINT, while the target is
5339 executing, ovewriting the 'regular' SIGINT signal handler. */
5341 async_initialize_sigint_signal_handler (void)
5343 signal (SIGINT, async_handle_remote_sigint);
5346 /* Signal handler for SIGINT, while the target is executing. */
5348 async_handle_remote_sigint (int sig)
5350 signal (sig, async_handle_remote_sigint_twice);
5351 /* Note we need to go through gdb_call_async_signal_handler in order
5352 to wake up the event loop on Windows. */
5353 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5356 /* Signal handler for SIGINT, installed after SIGINT has already been
5357 sent once. It will take effect the second time that the user sends
5360 async_handle_remote_sigint_twice (int sig)
5362 signal (sig, async_handle_remote_sigint);
5363 /* See note in async_handle_remote_sigint. */
5364 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5367 /* Implementation of to_check_pending_interrupt. */
5370 remote_check_pending_interrupt (struct target_ops *self)
5372 struct async_signal_handler *token = async_sigint_remote_twice_token;
5374 if (async_signal_handler_is_marked (token))
5376 clear_async_signal_handler (token);
5377 call_async_signal_handler (token);
5381 /* Perform the real interruption of the target execution, in response
5384 async_remote_interrupt (gdb_client_data arg)
5387 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5389 target_stop (inferior_ptid);
5392 /* Perform interrupt, if the first attempt did not succeed. Just give
5393 up on the target alltogether. */
5395 async_remote_interrupt_twice (gdb_client_data arg)
5398 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5403 /* Reinstall the usual SIGINT handlers, after the target has
5406 async_cleanup_sigint_signal_handler (void *dummy)
5408 signal (SIGINT, handle_sigint);
5411 /* Send ^C to target to halt it. Target will respond, and send us a
5413 static void (*ofunc) (int);
5415 /* The command line interface's interrupt routine. This function is installed
5416 as a signal handler for SIGINT. The first time a user requests an
5417 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5418 response from the target (it didn't stop when the user requested it),
5419 we ask the user if he'd like to detach from the target. */
5422 sync_remote_interrupt (int signo)
5424 /* If this doesn't work, try more severe steps. */
5425 signal (signo, sync_remote_interrupt_twice);
5427 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5430 /* The user typed ^C twice. */
5433 sync_remote_interrupt_twice (int signo)
5435 signal (signo, ofunc);
5436 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5437 signal (signo, sync_remote_interrupt);
5440 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5441 thread, all threads of a remote process, or all threads of all
5445 remote_stop_ns (ptid_t ptid)
5447 struct remote_state *rs = get_remote_state ();
5449 char *endp = rs->buf + get_remote_packet_size ();
5451 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5452 remote_vcont_probe (rs);
5454 if (!rs->supports_vCont.t)
5455 error (_("Remote server does not support stopping threads"));
5457 if (ptid_equal (ptid, minus_one_ptid)
5458 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5459 p += xsnprintf (p, endp - p, "vCont;t");
5464 p += xsnprintf (p, endp - p, "vCont;t:");
5466 if (ptid_is_pid (ptid))
5467 /* All (-1) threads of process. */
5468 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5471 /* Small optimization: if we already have a stop reply for
5472 this thread, no use in telling the stub we want this
5474 if (peek_stop_reply (ptid))
5480 write_ptid (p, endp, nptid);
5483 /* In non-stop, we get an immediate OK reply. The stop reply will
5484 come in asynchronously by notification. */
5486 getpkt (&rs->buf, &rs->buf_size, 0);
5487 if (strcmp (rs->buf, "OK") != 0)
5488 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5491 /* All-stop version of target_interrupt. Sends a break or a ^C to
5492 interrupt the remote target. It is undefined which thread of which
5493 process reports the interrupt. */
5496 remote_interrupt_as (ptid_t ptid)
5498 struct remote_state *rs = get_remote_state ();
5500 rs->ctrlc_pending_p = 1;
5502 /* If the inferior is stopped already, but the core didn't know
5503 about it yet, just ignore the request. The cached wait status
5504 will be collected in remote_wait. */
5505 if (rs->cached_wait_status)
5508 /* Send interrupt_sequence to remote target. */
5509 send_interrupt_sequence ();
5512 /* Implement the to_stop function for the remote targets. */
5515 remote_stop (struct target_ops *self, ptid_t ptid)
5518 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5521 remote_stop_ns (ptid);
5524 /* We don't currently have a way to transparently pause the
5525 remote target in all-stop mode. Interrupt it instead. */
5526 remote_interrupt_as (ptid);
5530 /* Implement the to_interrupt function for the remote targets. */
5533 remote_interrupt (struct target_ops *self, ptid_t ptid)
5536 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5540 /* We don't currently have a way to ^C the remote target in
5541 non-stop mode. Stop it (with no signal) instead. */
5542 remote_stop_ns (ptid);
5545 remote_interrupt_as (ptid);
5548 /* Ask the user what to do when an interrupt is received. */
5551 interrupt_query (void)
5553 struct remote_state *rs = get_remote_state ();
5554 struct cleanup *old_chain;
5556 old_chain = make_cleanup_restore_target_terminal ();
5557 target_terminal_ours ();
5559 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5561 if (query (_("The target is not responding to interrupt requests.\n"
5562 "Stop debugging it? ")))
5564 remote_unpush_target ();
5565 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5570 if (query (_("Interrupted while waiting for the program.\n"
5571 "Give up waiting? ")))
5575 do_cleanups (old_chain);
5578 /* Enable/disable target terminal ownership. Most targets can use
5579 terminal groups to control terminal ownership. Remote targets are
5580 different in that explicit transfer of ownership to/from GDB/target
5584 remote_terminal_inferior (struct target_ops *self)
5586 if (!target_async_permitted)
5587 /* Nothing to do. */
5590 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5591 idempotent. The event-loop GDB talking to an asynchronous target
5592 with a synchronous command calls this function from both
5593 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5594 transfer the terminal to the target when it shouldn't this guard
5596 if (!remote_async_terminal_ours_p)
5598 delete_file_handler (input_fd);
5599 remote_async_terminal_ours_p = 0;
5600 async_initialize_sigint_signal_handler ();
5601 /* NOTE: At this point we could also register our selves as the
5602 recipient of all input. Any characters typed could then be
5603 passed on down to the target. */
5607 remote_terminal_ours (struct target_ops *self)
5609 if (!target_async_permitted)
5610 /* Nothing to do. */
5613 /* See FIXME in remote_terminal_inferior. */
5614 if (remote_async_terminal_ours_p)
5616 async_cleanup_sigint_signal_handler (NULL);
5617 add_file_handler (input_fd, stdin_event_handler, 0);
5618 remote_async_terminal_ours_p = 1;
5622 remote_console_output (char *msg)
5626 for (p = msg; p[0] && p[1]; p += 2)
5629 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5633 fputs_unfiltered (tb, gdb_stdtarg);
5635 gdb_flush (gdb_stdtarg);
5638 typedef struct cached_reg
5641 gdb_byte data[MAX_REGISTER_SIZE];
5644 DEF_VEC_O(cached_reg_t);
5646 typedef struct stop_reply
5648 struct notif_event base;
5650 /* The identifier of the thread about this event */
5653 /* The remote state this event is associated with. When the remote
5654 connection, represented by a remote_state object, is closed,
5655 all the associated stop_reply events should be released. */
5656 struct remote_state *rs;
5658 struct target_waitstatus ws;
5660 /* Expedited registers. This makes remote debugging a bit more
5661 efficient for those targets that provide critical registers as
5662 part of their normal status mechanism (as another roundtrip to
5663 fetch them is avoided). */
5664 VEC(cached_reg_t) *regcache;
5666 enum target_stop_reason stop_reason;
5668 CORE_ADDR watch_data_address;
5673 DECLARE_QUEUE_P (stop_reply_p);
5674 DEFINE_QUEUE_P (stop_reply_p);
5675 /* The list of already fetched and acknowledged stop events. This
5676 queue is used for notification Stop, and other notifications
5677 don't need queue for their events, because the notification events
5678 of Stop can't be consumed immediately, so that events should be
5679 queued first, and be consumed by remote_wait_{ns,as} one per
5680 time. Other notifications can consume their events immediately,
5681 so queue is not needed for them. */
5682 static QUEUE (stop_reply_p) *stop_reply_queue;
5685 stop_reply_xfree (struct stop_reply *r)
5687 notif_event_xfree ((struct notif_event *) r);
5690 /* Return the length of the stop reply queue. */
5693 stop_reply_queue_length (void)
5695 return QUEUE_length (stop_reply_p, stop_reply_queue);
5699 remote_notif_stop_parse (struct notif_client *self, char *buf,
5700 struct notif_event *event)
5702 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5706 remote_notif_stop_ack (struct notif_client *self, char *buf,
5707 struct notif_event *event)
5709 struct stop_reply *stop_reply = (struct stop_reply *) event;
5712 putpkt ((char *) self->ack_command);
5714 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5715 /* We got an unknown stop reply. */
5716 error (_("Unknown stop reply"));
5718 push_stop_reply (stop_reply);
5722 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5724 /* We can't get pending events in remote_notif_process for
5725 notification stop, and we have to do this in remote_wait_ns
5726 instead. If we fetch all queued events from stub, remote stub
5727 may exit and we have no chance to process them back in
5729 mark_async_event_handler (remote_async_inferior_event_token);
5734 stop_reply_dtr (struct notif_event *event)
5736 struct stop_reply *r = (struct stop_reply *) event;
5738 VEC_free (cached_reg_t, r->regcache);
5741 static struct notif_event *
5742 remote_notif_stop_alloc_reply (void)
5744 /* We cast to a pointer to the "base class". */
5745 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5747 r->dtr = stop_reply_dtr;
5752 /* A client of notification Stop. */
5754 struct notif_client notif_client_stop =
5758 remote_notif_stop_parse,
5759 remote_notif_stop_ack,
5760 remote_notif_stop_can_get_pending_events,
5761 remote_notif_stop_alloc_reply,
5765 /* A parameter to pass data in and out. */
5767 struct queue_iter_param
5770 struct stop_reply *output;
5773 /* Determine if THREAD is a pending fork parent thread. ARG contains
5774 the pid of the process that owns the threads we want to check, or
5775 -1 if we want to check all threads. */
5778 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5781 if (ws->kind == TARGET_WAITKIND_FORKED
5782 || ws->kind == TARGET_WAITKIND_VFORKED)
5784 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5791 /* Check whether EVENT is a fork event, and if it is, remove the
5792 fork child from the context list passed in DATA. */
5795 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5796 QUEUE_ITER (stop_reply_p) *iter,
5800 struct queue_iter_param *param = data;
5801 struct threads_listing_context *context = param->input;
5803 if (event->ws.kind == TARGET_WAITKIND_FORKED
5804 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5806 threads_listing_context_remove (&event->ws, context);
5812 /* If CONTEXT contains any fork child threads that have not been
5813 reported yet, remove them from the CONTEXT list. If such a
5814 thread exists it is because we are stopped at a fork catchpoint
5815 and have not yet called follow_fork, which will set up the
5816 host-side data structures for the new process. */
5819 remove_new_fork_children (struct threads_listing_context *context)
5821 struct thread_info * thread;
5823 struct notif_client *notif = ¬if_client_stop;
5824 struct queue_iter_param param;
5826 /* For any threads stopped at a fork event, remove the corresponding
5827 fork child threads from the CONTEXT list. */
5828 ALL_NON_EXITED_THREADS (thread)
5830 struct target_waitstatus *ws = &thread->pending_follow;
5832 if (is_pending_fork_parent (ws, pid, thread->ptid))
5834 threads_listing_context_remove (ws, context);
5838 /* Check for any pending fork events (not reported or processed yet)
5839 in process PID and remove those fork child threads from the
5840 CONTEXT list as well. */
5841 remote_notif_get_pending_events (notif);
5842 param.input = context;
5843 param.output = NULL;
5844 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5845 remove_child_of_pending_fork, ¶m);
5848 /* Remove stop replies in the queue if its pid is equal to the given
5852 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5853 QUEUE_ITER (stop_reply_p) *iter,
5857 struct queue_iter_param *param = data;
5858 struct inferior *inf = param->input;
5860 if (ptid_get_pid (event->ptid) == inf->pid)
5862 stop_reply_xfree (event);
5863 QUEUE_remove_elem (stop_reply_p, q, iter);
5869 /* Discard all pending stop replies of inferior INF. */
5872 discard_pending_stop_replies (struct inferior *inf)
5875 struct queue_iter_param param;
5876 struct stop_reply *reply;
5877 struct remote_state *rs = get_remote_state ();
5878 struct remote_notif_state *rns = rs->notif_state;
5880 /* This function can be notified when an inferior exists. When the
5881 target is not remote, the notification state is NULL. */
5882 if (rs->remote_desc == NULL)
5885 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5887 /* Discard the in-flight notification. */
5888 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5890 stop_reply_xfree (reply);
5891 rns->pending_event[notif_client_stop.id] = NULL;
5895 param.output = NULL;
5896 /* Discard the stop replies we have already pulled with
5898 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5899 remove_stop_reply_for_inferior, ¶m);
5902 /* If its remote state is equal to the given remote state,
5903 remove EVENT from the stop reply queue. */
5906 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5907 QUEUE_ITER (stop_reply_p) *iter,
5911 struct queue_iter_param *param = data;
5912 struct remote_state *rs = param->input;
5914 if (event->rs == rs)
5916 stop_reply_xfree (event);
5917 QUEUE_remove_elem (stop_reply_p, q, iter);
5923 /* Discard the stop replies for RS in stop_reply_queue. */
5926 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5928 struct queue_iter_param param;
5931 param.output = NULL;
5932 /* Discard the stop replies we have already pulled with
5934 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5935 remove_stop_reply_of_remote_state, ¶m);
5938 /* A parameter to pass data in and out. */
5941 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5942 QUEUE_ITER (stop_reply_p) *iter,
5946 struct queue_iter_param *param = data;
5947 ptid_t *ptid = param->input;
5949 if (ptid_match (event->ptid, *ptid))
5951 param->output = event;
5952 QUEUE_remove_elem (stop_reply_p, q, iter);
5959 /* Remove the first reply in 'stop_reply_queue' which matches
5962 static struct stop_reply *
5963 remote_notif_remove_queued_reply (ptid_t ptid)
5965 struct queue_iter_param param;
5967 param.input = &ptid;
5968 param.output = NULL;
5970 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5971 remote_notif_remove_once_on_match, ¶m);
5973 fprintf_unfiltered (gdb_stdlog,
5974 "notif: discard queued event: 'Stop' in %s\n",
5975 target_pid_to_str (ptid));
5977 return param.output;
5980 /* Look for a queued stop reply belonging to PTID. If one is found,
5981 remove it from the queue, and return it. Returns NULL if none is
5982 found. If there are still queued events left to process, tell the
5983 event loop to get back to target_wait soon. */
5985 static struct stop_reply *
5986 queued_stop_reply (ptid_t ptid)
5988 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5990 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5991 /* There's still at least an event left. */
5992 mark_async_event_handler (remote_async_inferior_event_token);
5997 /* Push a fully parsed stop reply in the stop reply queue. Since we
5998 know that we now have at least one queued event left to pass to the
5999 core side, tell the event loop to get back to target_wait soon. */
6002 push_stop_reply (struct stop_reply *new_event)
6004 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6007 fprintf_unfiltered (gdb_stdlog,
6008 "notif: push 'Stop' %s to queue %d\n",
6009 target_pid_to_str (new_event->ptid),
6010 QUEUE_length (stop_reply_p,
6013 mark_async_event_handler (remote_async_inferior_event_token);
6017 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6018 QUEUE_ITER (stop_reply_p) *iter,
6019 struct stop_reply *event,
6022 ptid_t *ptid = data;
6024 return !(ptid_equal (*ptid, event->ptid)
6025 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6028 /* Returns true if we have a stop reply for PTID. */
6031 peek_stop_reply (ptid_t ptid)
6033 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6034 stop_reply_match_ptid_and_ws, &ptid);
6037 /* Skip PACKET until the next semi-colon (or end of string). */
6040 skip_to_semicolon (char *p)
6042 while (*p != '\0' && *p != ';')
6047 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6048 starting with P and ending with PEND matches PREFIX. */
6051 strprefix (const char *p, const char *pend, const char *prefix)
6053 for ( ; p < pend; p++, prefix++)
6056 return *prefix == '\0';
6059 /* Parse the stop reply in BUF. Either the function succeeds, and the
6060 result is stored in EVENT, or throws an error. */
6063 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6065 struct remote_arch_state *rsa = get_remote_arch_state ();
6070 event->ptid = null_ptid;
6071 event->rs = get_remote_state ();
6072 event->ws.kind = TARGET_WAITKIND_IGNORE;
6073 event->ws.value.integer = 0;
6074 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6075 event->regcache = NULL;
6080 case 'T': /* Status with PC, SP, FP, ... */
6081 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6082 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6084 n... = register number
6085 r... = register contents
6088 p = &buf[3]; /* after Txx */
6094 p1 = strchr (p, ':');
6096 error (_("Malformed packet(a) (missing colon): %s\n\
6100 error (_("Malformed packet(a) (missing register number): %s\n\
6104 /* Some "registers" are actually extended stop information.
6105 Note if you're adding a new entry here: GDB 7.9 and
6106 earlier assume that all register "numbers" that start
6107 with an hex digit are real register numbers. Make sure
6108 the server only sends such a packet if it knows the
6109 client understands it. */
6111 if (strprefix (p, p1, "thread"))
6112 event->ptid = read_ptid (++p1, &p);
6113 else if (strprefix (p, p1, "watch")
6114 || strprefix (p, p1, "rwatch")
6115 || strprefix (p, p1, "awatch"))
6117 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6118 p = unpack_varlen_hex (++p1, &addr);
6119 event->watch_data_address = (CORE_ADDR) addr;
6121 else if (strprefix (p, p1, "swbreak"))
6123 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6125 /* Make sure the stub doesn't forget to indicate support
6127 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6128 error (_("Unexpected swbreak stop reason"));
6130 /* The value part is documented as "must be empty",
6131 though we ignore it, in case we ever decide to make
6132 use of it in a backward compatible way. */
6133 p = skip_to_semicolon (p1 + 1);
6135 else if (strprefix (p, p1, "hwbreak"))
6137 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6139 /* Make sure the stub doesn't forget to indicate support
6141 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6142 error (_("Unexpected hwbreak stop reason"));
6145 p = skip_to_semicolon (p1 + 1);
6147 else if (strprefix (p, p1, "library"))
6149 event->ws.kind = TARGET_WAITKIND_LOADED;
6150 p = skip_to_semicolon (p1 + 1);
6152 else if (strprefix (p, p1, "replaylog"))
6154 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6155 /* p1 will indicate "begin" or "end", but it makes
6156 no difference for now, so ignore it. */
6157 p = skip_to_semicolon (p1 + 1);
6159 else if (strprefix (p, p1, "core"))
6163 p = unpack_varlen_hex (++p1, &c);
6166 else if (strprefix (p, p1, "fork"))
6168 event->ws.value.related_pid = read_ptid (++p1, &p);
6169 event->ws.kind = TARGET_WAITKIND_FORKED;
6171 else if (strprefix (p, p1, "vfork"))
6173 event->ws.value.related_pid = read_ptid (++p1, &p);
6174 event->ws.kind = TARGET_WAITKIND_VFORKED;
6176 else if (strprefix (p, p1, "vforkdone"))
6178 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6179 p = skip_to_semicolon (p1 + 1);
6181 else if (strncmp (p, "exec", p1 - p) == 0)
6184 char pathname[PATH_MAX];
6187 /* Determine the length of the execd pathname. */
6188 p = unpack_varlen_hex (++p1, &ignored);
6189 pathlen = (p - p1) / 2;
6191 /* Save the pathname for event reporting and for
6192 the next run command. */
6193 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6194 pathname[pathlen] = '\0';
6196 /* This is freed during event handling. */
6197 event->ws.value.execd_pathname = xstrdup (pathname);
6198 event->ws.kind = TARGET_WAITKIND_EXECD;
6200 /* Skip the registers included in this packet, since
6201 they may be for an architecture different from the
6202 one used by the original program. */
6212 p = skip_to_semicolon (p1 + 1);
6217 /* Maybe a real ``P'' register number. */
6218 p_temp = unpack_varlen_hex (p, &pnum);
6219 /* If the first invalid character is the colon, we got a
6220 register number. Otherwise, it's an unknown stop
6224 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6225 cached_reg_t cached_reg;
6228 error (_("Remote sent bad register number %s: %s\n\
6230 hex_string (pnum), p, buf);
6232 cached_reg.num = reg->regnum;
6235 fieldsize = hex2bin (p, cached_reg.data,
6236 register_size (target_gdbarch (),
6239 if (fieldsize < register_size (target_gdbarch (),
6241 warning (_("Remote reply is too short: %s"), buf);
6243 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6247 /* Not a number. Silently skip unknown optional
6249 p = skip_to_semicolon (p1 + 1);
6254 error (_("Remote register badly formatted: %s\nhere: %s"),
6259 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6263 case 'S': /* Old style status, just signal only. */
6267 event->ws.kind = TARGET_WAITKIND_STOPPED;
6268 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6269 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6270 event->ws.value.sig = (enum gdb_signal) sig;
6272 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6275 case 'W': /* Target exited. */
6282 /* GDB used to accept only 2 hex chars here. Stubs should
6283 only send more if they detect GDB supports multi-process
6285 p = unpack_varlen_hex (&buf[1], &value);
6289 /* The remote process exited. */
6290 event->ws.kind = TARGET_WAITKIND_EXITED;
6291 event->ws.value.integer = value;
6295 /* The remote process exited with a signal. */
6296 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6297 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6298 event->ws.value.sig = (enum gdb_signal) value;
6300 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6303 /* If no process is specified, assume inferior_ptid. */
6304 pid = ptid_get_pid (inferior_ptid);
6313 else if (startswith (p, "process:"))
6317 p += sizeof ("process:") - 1;
6318 unpack_varlen_hex (p, &upid);
6322 error (_("unknown stop reply packet: %s"), buf);
6325 error (_("unknown stop reply packet: %s"), buf);
6326 event->ptid = pid_to_ptid (pid);
6331 if (non_stop && ptid_equal (event->ptid, null_ptid))
6332 error (_("No process or thread specified in stop reply: %s"), buf);
6335 /* When the stub wants to tell GDB about a new notification reply, it
6336 sends a notification (%Stop, for example). Those can come it at
6337 any time, hence, we have to make sure that any pending
6338 putpkt/getpkt sequence we're making is finished, before querying
6339 the stub for more events with the corresponding ack command
6340 (vStopped, for example). E.g., if we started a vStopped sequence
6341 immediately upon receiving the notification, something like this
6349 1.6) <-- (registers reply to step #1.3)
6351 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6354 To solve this, whenever we parse a %Stop notification successfully,
6355 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6356 doing whatever we were doing:
6362 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6363 2.5) <-- (registers reply to step #2.3)
6365 Eventualy after step #2.5, we return to the event loop, which
6366 notices there's an event on the
6367 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6368 associated callback --- the function below. At this point, we're
6369 always safe to start a vStopped sequence. :
6372 2.7) <-- T05 thread:2
6378 remote_notif_get_pending_events (struct notif_client *nc)
6380 struct remote_state *rs = get_remote_state ();
6382 if (rs->notif_state->pending_event[nc->id] != NULL)
6385 fprintf_unfiltered (gdb_stdlog,
6386 "notif: process: '%s' ack pending event\n",
6390 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6391 rs->notif_state->pending_event[nc->id] = NULL;
6395 getpkt (&rs->buf, &rs->buf_size, 0);
6396 if (strcmp (rs->buf, "OK") == 0)
6399 remote_notif_ack (nc, rs->buf);
6405 fprintf_unfiltered (gdb_stdlog,
6406 "notif: process: '%s' no pending reply\n",
6411 /* Called when it is decided that STOP_REPLY holds the info of the
6412 event that is to be returned to the core. This function always
6413 destroys STOP_REPLY. */
6416 process_stop_reply (struct stop_reply *stop_reply,
6417 struct target_waitstatus *status)
6421 *status = stop_reply->ws;
6422 ptid = stop_reply->ptid;
6424 /* If no thread/process was reported by the stub, assume the current
6426 if (ptid_equal (ptid, null_ptid))
6427 ptid = inferior_ptid;
6429 if (status->kind != TARGET_WAITKIND_EXITED
6430 && status->kind != TARGET_WAITKIND_SIGNALLED)
6432 struct remote_state *rs = get_remote_state ();
6434 /* Expedited registers. */
6435 if (stop_reply->regcache)
6437 struct regcache *regcache
6438 = get_thread_arch_regcache (ptid, target_gdbarch ());
6443 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6445 regcache_raw_supply (regcache, reg->num, reg->data);
6446 VEC_free (cached_reg_t, stop_reply->regcache);
6449 rs->stop_reason = stop_reply->stop_reason;
6450 rs->remote_watch_data_address = stop_reply->watch_data_address;
6452 remote_notice_new_inferior (ptid, 0);
6453 demand_private_info (ptid)->core = stop_reply->core;
6456 stop_reply_xfree (stop_reply);
6460 /* The non-stop mode version of target_wait. */
6463 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6465 struct remote_state *rs = get_remote_state ();
6466 struct stop_reply *stop_reply;
6470 /* If in non-stop mode, get out of getpkt even if a
6471 notification is received. */
6473 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6474 0 /* forever */, &is_notif);
6477 if (ret != -1 && !is_notif)
6480 case 'E': /* Error of some sort. */
6481 /* We're out of sync with the target now. Did it continue
6482 or not? We can't tell which thread it was in non-stop,
6483 so just ignore this. */
6484 warning (_("Remote failure reply: %s"), rs->buf);
6486 case 'O': /* Console output. */
6487 remote_console_output (rs->buf + 1);
6490 warning (_("Invalid remote reply: %s"), rs->buf);
6494 /* Acknowledge a pending stop reply that may have arrived in the
6496 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6497 remote_notif_get_pending_events (¬if_client_stop);
6499 /* If indeed we noticed a stop reply, we're done. */
6500 stop_reply = queued_stop_reply (ptid);
6501 if (stop_reply != NULL)
6502 return process_stop_reply (stop_reply, status);
6504 /* Still no event. If we're just polling for an event, then
6505 return to the event loop. */
6506 if (options & TARGET_WNOHANG)
6508 status->kind = TARGET_WAITKIND_IGNORE;
6509 return minus_one_ptid;
6512 /* Otherwise do a blocking wait. */
6513 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6514 1 /* forever */, &is_notif);
6518 /* Wait until the remote machine stops, then return, storing status in
6519 STATUS just as `wait' would. */
6522 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6524 struct remote_state *rs = get_remote_state ();
6525 ptid_t event_ptid = null_ptid;
6527 struct stop_reply *stop_reply;
6531 status->kind = TARGET_WAITKIND_IGNORE;
6532 status->value.integer = 0;
6534 stop_reply = queued_stop_reply (ptid);
6535 if (stop_reply != NULL)
6536 return process_stop_reply (stop_reply, status);
6538 if (rs->cached_wait_status)
6539 /* Use the cached wait status, but only once. */
6540 rs->cached_wait_status = 0;
6545 int forever = ((options & TARGET_WNOHANG) == 0
6546 && wait_forever_enabled_p);
6548 if (!rs->waiting_for_stop_reply)
6550 status->kind = TARGET_WAITKIND_NO_RESUMED;
6551 return minus_one_ptid;
6554 if (!target_is_async_p ())
6556 ofunc = signal (SIGINT, sync_remote_interrupt);
6557 /* If the user hit C-c before this packet, or between packets,
6558 pretend that it was hit right here. */
6559 if (check_quit_flag ())
6562 sync_remote_interrupt (SIGINT);
6566 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6567 _never_ wait for ever -> test on target_is_async_p().
6568 However, before we do that we need to ensure that the caller
6569 knows how to take the target into/out of async mode. */
6570 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6571 forever, &is_notif);
6573 if (!target_is_async_p ())
6574 signal (SIGINT, ofunc);
6576 /* GDB gets a notification. Return to core as this event is
6578 if (ret != -1 && is_notif)
6579 return minus_one_ptid;
6581 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6582 return minus_one_ptid;
6587 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6589 /* We got something. */
6590 rs->waiting_for_stop_reply = 0;
6592 /* Assume that the target has acknowledged Ctrl-C unless we receive
6593 an 'F' or 'O' packet. */
6594 if (buf[0] != 'F' && buf[0] != 'O')
6595 rs->ctrlc_pending_p = 0;
6599 case 'E': /* Error of some sort. */
6600 /* We're out of sync with the target now. Did it continue or
6601 not? Not is more likely, so report a stop. */
6602 warning (_("Remote failure reply: %s"), buf);
6603 status->kind = TARGET_WAITKIND_STOPPED;
6604 status->value.sig = GDB_SIGNAL_0;
6606 case 'F': /* File-I/O request. */
6607 remote_fileio_request (buf, rs->ctrlc_pending_p);
6608 rs->ctrlc_pending_p = 0;
6610 case 'T': case 'S': case 'X': case 'W':
6612 struct stop_reply *stop_reply
6613 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6616 event_ptid = process_stop_reply (stop_reply, status);
6619 case 'O': /* Console output. */
6620 remote_console_output (buf + 1);
6622 /* The target didn't really stop; keep waiting. */
6623 rs->waiting_for_stop_reply = 1;
6627 if (rs->last_sent_signal != GDB_SIGNAL_0)
6629 /* Zero length reply means that we tried 'S' or 'C' and the
6630 remote system doesn't support it. */
6631 target_terminal_ours_for_output ();
6633 ("Can't send signals to this remote system. %s not sent.\n",
6634 gdb_signal_to_name (rs->last_sent_signal));
6635 rs->last_sent_signal = GDB_SIGNAL_0;
6636 target_terminal_inferior ();
6638 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6639 putpkt ((char *) buf);
6641 /* We just told the target to resume, so a stop reply is in
6643 rs->waiting_for_stop_reply = 1;
6646 /* else fallthrough */
6648 warning (_("Invalid remote reply: %s"), buf);
6650 rs->waiting_for_stop_reply = 1;
6654 if (status->kind == TARGET_WAITKIND_IGNORE)
6656 /* Nothing interesting happened. If we're doing a non-blocking
6657 poll, we're done. Otherwise, go back to waiting. */
6658 if (options & TARGET_WNOHANG)
6659 return minus_one_ptid;
6663 else if (status->kind != TARGET_WAITKIND_EXITED
6664 && status->kind != TARGET_WAITKIND_SIGNALLED)
6666 if (!ptid_equal (event_ptid, null_ptid))
6667 record_currthread (rs, event_ptid);
6669 event_ptid = inferior_ptid;
6672 /* A process exit. Invalidate our notion of current thread. */
6673 record_currthread (rs, minus_one_ptid);
6678 /* Wait until the remote machine stops, then return, storing status in
6679 STATUS just as `wait' would. */
6682 remote_wait (struct target_ops *ops,
6683 ptid_t ptid, struct target_waitstatus *status, int options)
6688 event_ptid = remote_wait_ns (ptid, status, options);
6690 event_ptid = remote_wait_as (ptid, status, options);
6692 if (target_is_async_p ())
6694 /* If there are are events left in the queue tell the event loop
6696 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6697 mark_async_event_handler (remote_async_inferior_event_token);
6703 /* Fetch a single register using a 'p' packet. */
6706 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6708 struct remote_state *rs = get_remote_state ();
6710 char regp[MAX_REGISTER_SIZE];
6713 if (packet_support (PACKET_p) == PACKET_DISABLE)
6716 if (reg->pnum == -1)
6721 p += hexnumstr (p, reg->pnum);
6724 getpkt (&rs->buf, &rs->buf_size, 0);
6728 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6732 case PACKET_UNKNOWN:
6735 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6736 gdbarch_register_name (get_regcache_arch (regcache),
6741 /* If this register is unfetchable, tell the regcache. */
6744 regcache_raw_supply (regcache, reg->regnum, NULL);
6748 /* Otherwise, parse and supply the value. */
6754 error (_("fetch_register_using_p: early buf termination"));
6756 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6759 regcache_raw_supply (regcache, reg->regnum, regp);
6763 /* Fetch the registers included in the target's 'g' packet. */
6766 send_g_packet (void)
6768 struct remote_state *rs = get_remote_state ();
6771 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6772 remote_send (&rs->buf, &rs->buf_size);
6774 /* We can get out of synch in various cases. If the first character
6775 in the buffer is not a hex character, assume that has happened
6776 and try to fetch another packet to read. */
6777 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6778 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6779 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6780 && rs->buf[0] != 'x') /* New: unavailable register value. */
6783 fprintf_unfiltered (gdb_stdlog,
6784 "Bad register packet; fetching a new packet\n");
6785 getpkt (&rs->buf, &rs->buf_size, 0);
6788 buf_len = strlen (rs->buf);
6790 /* Sanity check the received packet. */
6791 if (buf_len % 2 != 0)
6792 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6798 process_g_packet (struct regcache *regcache)
6800 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6801 struct remote_state *rs = get_remote_state ();
6802 struct remote_arch_state *rsa = get_remote_arch_state ();
6807 buf_len = strlen (rs->buf);
6809 /* Further sanity checks, with knowledge of the architecture. */
6810 if (buf_len > 2 * rsa->sizeof_g_packet)
6811 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6813 /* Save the size of the packet sent to us by the target. It is used
6814 as a heuristic when determining the max size of packets that the
6815 target can safely receive. */
6816 if (rsa->actual_register_packet_size == 0)
6817 rsa->actual_register_packet_size = buf_len;
6819 /* If this is smaller than we guessed the 'g' packet would be,
6820 update our records. A 'g' reply that doesn't include a register's
6821 value implies either that the register is not available, or that
6822 the 'p' packet must be used. */
6823 if (buf_len < 2 * rsa->sizeof_g_packet)
6825 rsa->sizeof_g_packet = buf_len / 2;
6827 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6829 if (rsa->regs[i].pnum == -1)
6832 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6833 rsa->regs[i].in_g_packet = 0;
6835 rsa->regs[i].in_g_packet = 1;
6839 regs = alloca (rsa->sizeof_g_packet);
6841 /* Unimplemented registers read as all bits zero. */
6842 memset (regs, 0, rsa->sizeof_g_packet);
6844 /* Reply describes registers byte by byte, each byte encoded as two
6845 hex characters. Suck them all up, then supply them to the
6846 register cacheing/storage mechanism. */
6849 for (i = 0; i < rsa->sizeof_g_packet; i++)
6851 if (p[0] == 0 || p[1] == 0)
6852 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6853 internal_error (__FILE__, __LINE__,
6854 _("unexpected end of 'g' packet reply"));
6856 if (p[0] == 'x' && p[1] == 'x')
6857 regs[i] = 0; /* 'x' */
6859 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6863 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6865 struct packet_reg *r = &rsa->regs[i];
6869 if (r->offset * 2 >= strlen (rs->buf))
6870 /* This shouldn't happen - we adjusted in_g_packet above. */
6871 internal_error (__FILE__, __LINE__,
6872 _("unexpected end of 'g' packet reply"));
6873 else if (rs->buf[r->offset * 2] == 'x')
6875 gdb_assert (r->offset * 2 < strlen (rs->buf));
6876 /* The register isn't available, mark it as such (at
6877 the same time setting the value to zero). */
6878 regcache_raw_supply (regcache, r->regnum, NULL);
6881 regcache_raw_supply (regcache, r->regnum,
6888 fetch_registers_using_g (struct regcache *regcache)
6891 process_g_packet (regcache);
6894 /* Make the remote selected traceframe match GDB's selected
6898 set_remote_traceframe (void)
6901 struct remote_state *rs = get_remote_state ();
6903 if (rs->remote_traceframe_number == get_traceframe_number ())
6906 /* Avoid recursion, remote_trace_find calls us again. */
6907 rs->remote_traceframe_number = get_traceframe_number ();
6909 newnum = target_trace_find (tfind_number,
6910 get_traceframe_number (), 0, 0, NULL);
6912 /* Should not happen. If it does, all bets are off. */
6913 if (newnum != get_traceframe_number ())
6914 warning (_("could not set remote traceframe"));
6918 remote_fetch_registers (struct target_ops *ops,
6919 struct regcache *regcache, int regnum)
6921 struct remote_arch_state *rsa = get_remote_arch_state ();
6924 set_remote_traceframe ();
6925 set_general_thread (inferior_ptid);
6929 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6931 gdb_assert (reg != NULL);
6933 /* If this register might be in the 'g' packet, try that first -
6934 we are likely to read more than one register. If this is the
6935 first 'g' packet, we might be overly optimistic about its
6936 contents, so fall back to 'p'. */
6937 if (reg->in_g_packet)
6939 fetch_registers_using_g (regcache);
6940 if (reg->in_g_packet)
6944 if (fetch_register_using_p (regcache, reg))
6947 /* This register is not available. */
6948 regcache_raw_supply (regcache, reg->regnum, NULL);
6953 fetch_registers_using_g (regcache);
6955 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6956 if (!rsa->regs[i].in_g_packet)
6957 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6959 /* This register is not available. */
6960 regcache_raw_supply (regcache, i, NULL);
6964 /* Prepare to store registers. Since we may send them all (using a
6965 'G' request), we have to read out the ones we don't want to change
6969 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6971 struct remote_arch_state *rsa = get_remote_arch_state ();
6973 gdb_byte buf[MAX_REGISTER_SIZE];
6975 /* Make sure the entire registers array is valid. */
6976 switch (packet_support (PACKET_P))
6978 case PACKET_DISABLE:
6979 case PACKET_SUPPORT_UNKNOWN:
6980 /* Make sure all the necessary registers are cached. */
6981 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6982 if (rsa->regs[i].in_g_packet)
6983 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6990 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6991 packet was not recognized. */
6994 store_register_using_P (const struct regcache *regcache,
6995 struct packet_reg *reg)
6997 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6998 struct remote_state *rs = get_remote_state ();
6999 /* Try storing a single register. */
7000 char *buf = rs->buf;
7001 gdb_byte regp[MAX_REGISTER_SIZE];
7004 if (packet_support (PACKET_P) == PACKET_DISABLE)
7007 if (reg->pnum == -1)
7010 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7011 p = buf + strlen (buf);
7012 regcache_raw_collect (regcache, reg->regnum, regp);
7013 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7015 getpkt (&rs->buf, &rs->buf_size, 0);
7017 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7022 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7023 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7024 case PACKET_UNKNOWN:
7027 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7031 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7032 contents of the register cache buffer. FIXME: ignores errors. */
7035 store_registers_using_G (const struct regcache *regcache)
7037 struct remote_state *rs = get_remote_state ();
7038 struct remote_arch_state *rsa = get_remote_arch_state ();
7042 /* Extract all the registers in the regcache copying them into a
7047 regs = alloca (rsa->sizeof_g_packet);
7048 memset (regs, 0, rsa->sizeof_g_packet);
7049 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7051 struct packet_reg *r = &rsa->regs[i];
7054 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7058 /* Command describes registers byte by byte,
7059 each byte encoded as two hex characters. */
7062 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7064 bin2hex (regs, p, rsa->sizeof_g_packet);
7066 getpkt (&rs->buf, &rs->buf_size, 0);
7067 if (packet_check_result (rs->buf) == PACKET_ERROR)
7068 error (_("Could not write registers; remote failure reply '%s'"),
7072 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7073 of the register cache buffer. FIXME: ignores errors. */
7076 remote_store_registers (struct target_ops *ops,
7077 struct regcache *regcache, int regnum)
7079 struct remote_arch_state *rsa = get_remote_arch_state ();
7082 set_remote_traceframe ();
7083 set_general_thread (inferior_ptid);
7087 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7089 gdb_assert (reg != NULL);
7091 /* Always prefer to store registers using the 'P' packet if
7092 possible; we often change only a small number of registers.
7093 Sometimes we change a larger number; we'd need help from a
7094 higher layer to know to use 'G'. */
7095 if (store_register_using_P (regcache, reg))
7098 /* For now, don't complain if we have no way to write the
7099 register. GDB loses track of unavailable registers too
7100 easily. Some day, this may be an error. We don't have
7101 any way to read the register, either... */
7102 if (!reg->in_g_packet)
7105 store_registers_using_G (regcache);
7109 store_registers_using_G (regcache);
7111 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7112 if (!rsa->regs[i].in_g_packet)
7113 if (!store_register_using_P (regcache, &rsa->regs[i]))
7114 /* See above for why we do not issue an error here. */
7119 /* Return the number of hex digits in num. */
7122 hexnumlen (ULONGEST num)
7126 for (i = 0; num != 0; i++)
7132 /* Set BUF to the minimum number of hex digits representing NUM. */
7135 hexnumstr (char *buf, ULONGEST num)
7137 int len = hexnumlen (num);
7139 return hexnumnstr (buf, num, len);
7143 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7146 hexnumnstr (char *buf, ULONGEST num, int width)
7152 for (i = width - 1; i >= 0; i--)
7154 buf[i] = "0123456789abcdef"[(num & 0xf)];
7161 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7164 remote_address_masked (CORE_ADDR addr)
7166 unsigned int address_size = remote_address_size;
7168 /* If "remoteaddresssize" was not set, default to target address size. */
7170 address_size = gdbarch_addr_bit (target_gdbarch ());
7172 if (address_size > 0
7173 && address_size < (sizeof (ULONGEST) * 8))
7175 /* Only create a mask when that mask can safely be constructed
7176 in a ULONGEST variable. */
7179 mask = (mask << address_size) - 1;
7185 /* Determine whether the remote target supports binary downloading.
7186 This is accomplished by sending a no-op memory write of zero length
7187 to the target at the specified address. It does not suffice to send
7188 the whole packet, since many stubs strip the eighth bit and
7189 subsequently compute a wrong checksum, which causes real havoc with
7192 NOTE: This can still lose if the serial line is not eight-bit
7193 clean. In cases like this, the user should clear "remote
7197 check_binary_download (CORE_ADDR addr)
7199 struct remote_state *rs = get_remote_state ();
7201 switch (packet_support (PACKET_X))
7203 case PACKET_DISABLE:
7207 case PACKET_SUPPORT_UNKNOWN:
7213 p += hexnumstr (p, (ULONGEST) addr);
7215 p += hexnumstr (p, (ULONGEST) 0);
7219 putpkt_binary (rs->buf, (int) (p - rs->buf));
7220 getpkt (&rs->buf, &rs->buf_size, 0);
7222 if (rs->buf[0] == '\0')
7225 fprintf_unfiltered (gdb_stdlog,
7226 "binary downloading NOT "
7227 "supported by target\n");
7228 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7233 fprintf_unfiltered (gdb_stdlog,
7234 "binary downloading supported by target\n");
7235 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7242 /* Helper function to resize the payload in order to try to get a good
7243 alignment. We try to write an amount of data such that the next write will
7244 start on an address aligned on REMOTE_ALIGN_WRITES. */
7247 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7249 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7252 /* Write memory data directly to the remote machine.
7253 This does not inform the data cache; the data cache uses this.
7254 HEADER is the starting part of the packet.
7255 MEMADDR is the address in the remote memory space.
7256 MYADDR is the address of the buffer in our space.
7257 LEN_UNITS is the number of addressable units to write.
7258 UNIT_SIZE is the length in bytes of an addressable unit.
7259 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7260 should send data as binary ('X'), or hex-encoded ('M').
7262 The function creates packet of the form
7263 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7265 where encoding of <DATA> is terminated by PACKET_FORMAT.
7267 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7270 Return the transferred status, error or OK (an
7271 'enum target_xfer_status' value). Save the number of addressable units
7272 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7274 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7275 exchange between gdb and the stub could look like (?? in place of the
7281 -> $M1000,3:eeeeffffeeee#??
7285 <- eeeeffffeeeedddd */
7287 static enum target_xfer_status
7288 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7289 const gdb_byte *myaddr, ULONGEST len_units,
7290 int unit_size, ULONGEST *xfered_len_units,
7291 char packet_format, int use_length)
7293 struct remote_state *rs = get_remote_state ();
7299 int payload_capacity_bytes;
7300 int payload_length_bytes;
7302 if (packet_format != 'X' && packet_format != 'M')
7303 internal_error (__FILE__, __LINE__,
7304 _("remote_write_bytes_aux: bad packet format"));
7307 return TARGET_XFER_EOF;
7309 payload_capacity_bytes = get_memory_write_packet_size ();
7311 /* The packet buffer will be large enough for the payload;
7312 get_memory_packet_size ensures this. */
7315 /* Compute the size of the actual payload by subtracting out the
7316 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7318 payload_capacity_bytes -= strlen ("$,:#NN");
7320 /* The comma won't be used. */
7321 payload_capacity_bytes += 1;
7322 payload_capacity_bytes -= strlen (header);
7323 payload_capacity_bytes -= hexnumlen (memaddr);
7325 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7327 strcat (rs->buf, header);
7328 p = rs->buf + strlen (header);
7330 /* Compute a best guess of the number of bytes actually transfered. */
7331 if (packet_format == 'X')
7333 /* Best guess at number of bytes that will fit. */
7334 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7336 payload_capacity_bytes -= hexnumlen (todo_units);
7337 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7341 /* Number of bytes that will fit. */
7342 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7344 payload_capacity_bytes -= hexnumlen (todo_units);
7345 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7348 if (todo_units <= 0)
7349 internal_error (__FILE__, __LINE__,
7350 _("minimum packet size too small to write data"));
7352 /* If we already need another packet, then try to align the end
7353 of this packet to a useful boundary. */
7354 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7355 todo_units = align_for_efficient_write (todo_units, memaddr);
7357 /* Append "<memaddr>". */
7358 memaddr = remote_address_masked (memaddr);
7359 p += hexnumstr (p, (ULONGEST) memaddr);
7366 /* Append the length and retain its location and size. It may need to be
7367 adjusted once the packet body has been created. */
7369 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7377 /* Append the packet body. */
7378 if (packet_format == 'X')
7380 /* Binary mode. Send target system values byte by byte, in
7381 increasing byte addresses. Only escape certain critical
7383 payload_length_bytes =
7384 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7385 &units_written, payload_capacity_bytes);
7387 /* If not all TODO units fit, then we'll need another packet. Make
7388 a second try to keep the end of the packet aligned. Don't do
7389 this if the packet is tiny. */
7390 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7394 new_todo_units = align_for_efficient_write (units_written, memaddr);
7396 if (new_todo_units != units_written)
7397 payload_length_bytes =
7398 remote_escape_output (myaddr, new_todo_units, unit_size,
7399 (gdb_byte *) p, &units_written,
7400 payload_capacity_bytes);
7403 p += payload_length_bytes;
7404 if (use_length && units_written < todo_units)
7406 /* Escape chars have filled up the buffer prematurely,
7407 and we have actually sent fewer units than planned.
7408 Fix-up the length field of the packet. Use the same
7409 number of characters as before. */
7410 plen += hexnumnstr (plen, (ULONGEST) units_written,
7412 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7417 /* Normal mode: Send target system values byte by byte, in
7418 increasing byte addresses. Each byte is encoded as a two hex
7420 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7421 units_written = todo_units;
7424 putpkt_binary (rs->buf, (int) (p - rs->buf));
7425 getpkt (&rs->buf, &rs->buf_size, 0);
7427 if (rs->buf[0] == 'E')
7428 return TARGET_XFER_E_IO;
7430 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7431 send fewer units than we'd planned. */
7432 *xfered_len_units = (ULONGEST) units_written;
7433 return TARGET_XFER_OK;
7436 /* Write memory data directly to the remote machine.
7437 This does not inform the data cache; the data cache uses this.
7438 MEMADDR is the address in the remote memory space.
7439 MYADDR is the address of the buffer in our space.
7440 LEN is the number of bytes.
7442 Return the transferred status, error or OK (an
7443 'enum target_xfer_status' value). Save the number of bytes
7444 transferred in *XFERED_LEN. Only transfer a single packet. */
7446 static enum target_xfer_status
7447 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7448 int unit_size, ULONGEST *xfered_len)
7450 char *packet_format = 0;
7452 /* Check whether the target supports binary download. */
7453 check_binary_download (memaddr);
7455 switch (packet_support (PACKET_X))
7458 packet_format = "X";
7460 case PACKET_DISABLE:
7461 packet_format = "M";
7463 case PACKET_SUPPORT_UNKNOWN:
7464 internal_error (__FILE__, __LINE__,
7465 _("remote_write_bytes: bad internal state"));
7467 internal_error (__FILE__, __LINE__, _("bad switch"));
7470 return remote_write_bytes_aux (packet_format,
7471 memaddr, myaddr, len, unit_size, xfered_len,
7472 packet_format[0], 1);
7475 /* Read memory data directly from the remote machine.
7476 This does not use the data cache; the data cache uses this.
7477 MEMADDR is the address in the remote memory space.
7478 MYADDR is the address of the buffer in our space.
7479 LEN_UNITS is the number of addressable memory units to read..
7480 UNIT_SIZE is the length in bytes of an addressable unit.
7482 Return the transferred status, error or OK (an
7483 'enum target_xfer_status' value). Save the number of bytes
7484 transferred in *XFERED_LEN_UNITS.
7486 See the comment of remote_write_bytes_aux for an example of
7487 memory read/write exchange between gdb and the stub. */
7489 static enum target_xfer_status
7490 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7491 int unit_size, ULONGEST *xfered_len_units)
7493 struct remote_state *rs = get_remote_state ();
7494 int buf_size_bytes; /* Max size of packet output buffer. */
7499 buf_size_bytes = get_memory_read_packet_size ();
7500 /* The packet buffer will be large enough for the payload;
7501 get_memory_packet_size ensures this. */
7503 /* Number of units that will fit. */
7504 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7506 /* Construct "m"<memaddr>","<len>". */
7507 memaddr = remote_address_masked (memaddr);
7510 p += hexnumstr (p, (ULONGEST) memaddr);
7512 p += hexnumstr (p, (ULONGEST) todo_units);
7515 getpkt (&rs->buf, &rs->buf_size, 0);
7516 if (rs->buf[0] == 'E'
7517 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7518 && rs->buf[3] == '\0')
7519 return TARGET_XFER_E_IO;
7520 /* Reply describes memory byte by byte, each byte encoded as two hex
7523 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7524 /* Return what we have. Let higher layers handle partial reads. */
7525 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7526 return TARGET_XFER_OK;
7529 /* Using the set of read-only target sections of remote, read live
7532 For interface/parameters/return description see target.h,
7535 static enum target_xfer_status
7536 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7537 ULONGEST memaddr, ULONGEST len,
7538 int unit_size, ULONGEST *xfered_len)
7540 struct target_section *secp;
7541 struct target_section_table *table;
7543 secp = target_section_by_addr (ops, memaddr);
7545 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7546 secp->the_bfd_section)
7549 struct target_section *p;
7550 ULONGEST memend = memaddr + len;
7552 table = target_get_section_table (ops);
7554 for (p = table->sections; p < table->sections_end; p++)
7556 if (memaddr >= p->addr)
7558 if (memend <= p->endaddr)
7560 /* Entire transfer is within this section. */
7561 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7564 else if (memaddr >= p->endaddr)
7566 /* This section ends before the transfer starts. */
7571 /* This section overlaps the transfer. Just do half. */
7572 len = p->endaddr - memaddr;
7573 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7580 return TARGET_XFER_EOF;
7583 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7584 first if the requested memory is unavailable in traceframe.
7585 Otherwise, fall back to remote_read_bytes_1. */
7587 static enum target_xfer_status
7588 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7589 gdb_byte *myaddr, ULONGEST len, int unit_size,
7590 ULONGEST *xfered_len)
7593 return TARGET_XFER_EOF;
7595 if (get_traceframe_number () != -1)
7597 VEC(mem_range_s) *available;
7599 /* If we fail to get the set of available memory, then the
7600 target does not support querying traceframe info, and so we
7601 attempt reading from the traceframe anyway (assuming the
7602 target implements the old QTro packet then). */
7603 if (traceframe_available_memory (&available, memaddr, len))
7605 struct cleanup *old_chain;
7607 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7609 if (VEC_empty (mem_range_s, available)
7610 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7612 enum target_xfer_status res;
7614 /* Don't read into the traceframe's available
7616 if (!VEC_empty (mem_range_s, available))
7618 LONGEST oldlen = len;
7620 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7621 gdb_assert (len <= oldlen);
7624 do_cleanups (old_chain);
7626 /* This goes through the topmost target again. */
7627 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7628 len, unit_size, xfered_len);
7629 if (res == TARGET_XFER_OK)
7630 return TARGET_XFER_OK;
7633 /* No use trying further, we know some memory starting
7634 at MEMADDR isn't available. */
7636 return TARGET_XFER_UNAVAILABLE;
7640 /* Don't try to read more than how much is available, in
7641 case the target implements the deprecated QTro packet to
7642 cater for older GDBs (the target's knowledge of read-only
7643 sections may be outdated by now). */
7644 len = VEC_index (mem_range_s, available, 0)->length;
7646 do_cleanups (old_chain);
7650 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7655 /* Sends a packet with content determined by the printf format string
7656 FORMAT and the remaining arguments, then gets the reply. Returns
7657 whether the packet was a success, a failure, or unknown. */
7659 static enum packet_result remote_send_printf (const char *format, ...)
7660 ATTRIBUTE_PRINTF (1, 2);
7662 static enum packet_result
7663 remote_send_printf (const char *format, ...)
7665 struct remote_state *rs = get_remote_state ();
7666 int max_size = get_remote_packet_size ();
7669 va_start (ap, format);
7672 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7673 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7675 if (putpkt (rs->buf) < 0)
7676 error (_("Communication problem with target."));
7679 getpkt (&rs->buf, &rs->buf_size, 0);
7681 return packet_check_result (rs->buf);
7685 restore_remote_timeout (void *p)
7687 int value = *(int *)p;
7689 remote_timeout = value;
7692 /* Flash writing can take quite some time. We'll set
7693 effectively infinite timeout for flash operations.
7694 In future, we'll need to decide on a better approach. */
7695 static const int remote_flash_timeout = 1000;
7698 remote_flash_erase (struct target_ops *ops,
7699 ULONGEST address, LONGEST length)
7701 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7702 int saved_remote_timeout = remote_timeout;
7703 enum packet_result ret;
7704 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7705 &saved_remote_timeout);
7707 remote_timeout = remote_flash_timeout;
7709 ret = remote_send_printf ("vFlashErase:%s,%s",
7710 phex (address, addr_size),
7714 case PACKET_UNKNOWN:
7715 error (_("Remote target does not support flash erase"));
7717 error (_("Error erasing flash with vFlashErase packet"));
7722 do_cleanups (back_to);
7725 static enum target_xfer_status
7726 remote_flash_write (struct target_ops *ops, ULONGEST address,
7727 ULONGEST length, ULONGEST *xfered_len,
7728 const gdb_byte *data)
7730 int saved_remote_timeout = remote_timeout;
7731 enum target_xfer_status ret;
7732 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7733 &saved_remote_timeout);
7735 remote_timeout = remote_flash_timeout;
7736 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7738 do_cleanups (back_to);
7744 remote_flash_done (struct target_ops *ops)
7746 int saved_remote_timeout = remote_timeout;
7748 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7749 &saved_remote_timeout);
7751 remote_timeout = remote_flash_timeout;
7752 ret = remote_send_printf ("vFlashDone");
7753 do_cleanups (back_to);
7757 case PACKET_UNKNOWN:
7758 error (_("Remote target does not support vFlashDone"));
7760 error (_("Error finishing flash operation"));
7767 remote_files_info (struct target_ops *ignore)
7769 puts_filtered ("Debugging a target over a serial line.\n");
7772 /* Stuff for dealing with the packets which are part of this protocol.
7773 See comment at top of file for details. */
7775 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7776 error to higher layers. Called when a serial error is detected.
7777 The exception message is STRING, followed by a colon and a blank,
7778 the system error message for errno at function entry and final dot
7779 for output compatibility with throw_perror_with_name. */
7782 unpush_and_perror (const char *string)
7784 int saved_errno = errno;
7786 remote_unpush_target ();
7787 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7788 safe_strerror (saved_errno));
7791 /* Read a single character from the remote end. */
7794 readchar (int timeout)
7797 struct remote_state *rs = get_remote_state ();
7799 ch = serial_readchar (rs->remote_desc, timeout);
7804 switch ((enum serial_rc) ch)
7807 remote_unpush_target ();
7808 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7811 unpush_and_perror (_("Remote communication error. "
7812 "Target disconnected."));
7814 case SERIAL_TIMEOUT:
7820 /* Wrapper for serial_write that closes the target and throws if
7824 remote_serial_write (const char *str, int len)
7826 struct remote_state *rs = get_remote_state ();
7828 if (serial_write (rs->remote_desc, str, len))
7830 unpush_and_perror (_("Remote communication error. "
7831 "Target disconnected."));
7835 /* Send the command in *BUF to the remote machine, and read the reply
7836 into *BUF. Report an error if we get an error reply. Resize
7837 *BUF using xrealloc if necessary to hold the result, and update
7841 remote_send (char **buf,
7845 getpkt (buf, sizeof_buf, 0);
7847 if ((*buf)[0] == 'E')
7848 error (_("Remote failure reply: %s"), *buf);
7851 /* Return a pointer to an xmalloc'ed string representing an escaped
7852 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7853 etc. The caller is responsible for releasing the returned
7857 escape_buffer (const char *buf, int n)
7859 struct cleanup *old_chain;
7860 struct ui_file *stb;
7863 stb = mem_fileopen ();
7864 old_chain = make_cleanup_ui_file_delete (stb);
7866 fputstrn_unfiltered (buf, n, '\\', stb);
7867 str = ui_file_xstrdup (stb, NULL);
7868 do_cleanups (old_chain);
7872 /* Display a null-terminated packet on stdout, for debugging, using C
7876 print_packet (const char *buf)
7878 puts_filtered ("\"");
7879 fputstr_filtered (buf, '"', gdb_stdout);
7880 puts_filtered ("\"");
7884 putpkt (const char *buf)
7886 return putpkt_binary (buf, strlen (buf));
7889 /* Send a packet to the remote machine, with error checking. The data
7890 of the packet is in BUF. The string in BUF can be at most
7891 get_remote_packet_size () - 5 to account for the $, # and checksum,
7892 and for a possible /0 if we are debugging (remote_debug) and want
7893 to print the sent packet as a string. */
7896 putpkt_binary (const char *buf, int cnt)
7898 struct remote_state *rs = get_remote_state ();
7900 unsigned char csum = 0;
7901 char *buf2 = xmalloc (cnt + 6);
7902 struct cleanup *old_chain = make_cleanup (xfree, buf2);
7909 /* Catch cases like trying to read memory or listing threads while
7910 we're waiting for a stop reply. The remote server wouldn't be
7911 ready to handle this request, so we'd hang and timeout. We don't
7912 have to worry about this in synchronous mode, because in that
7913 case it's not possible to issue a command while the target is
7914 running. This is not a problem in non-stop mode, because in that
7915 case, the stub is always ready to process serial input. */
7916 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7918 error (_("Cannot execute this command while the target is running.\n"
7919 "Use the \"interrupt\" command to stop the target\n"
7920 "and then try again."));
7923 /* We're sending out a new packet. Make sure we don't look at a
7924 stale cached response. */
7925 rs->cached_wait_status = 0;
7927 /* Copy the packet into buffer BUF2, encapsulating it
7928 and giving it a checksum. */
7933 for (i = 0; i < cnt; i++)
7939 *p++ = tohex ((csum >> 4) & 0xf);
7940 *p++ = tohex (csum & 0xf);
7942 /* Send it over and over until we get a positive ack. */
7946 int started_error_output = 0;
7950 struct cleanup *old_chain;
7954 str = escape_buffer (buf2, p - buf2);
7955 old_chain = make_cleanup (xfree, str);
7956 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7957 gdb_flush (gdb_stdlog);
7958 do_cleanups (old_chain);
7960 remote_serial_write (buf2, p - buf2);
7962 /* If this is a no acks version of the remote protocol, send the
7963 packet and move on. */
7967 /* Read until either a timeout occurs (-2) or '+' is read.
7968 Handle any notification that arrives in the mean time. */
7971 ch = readchar (remote_timeout);
7979 case SERIAL_TIMEOUT:
7982 if (started_error_output)
7984 putchar_unfiltered ('\n');
7985 started_error_output = 0;
7994 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7995 do_cleanups (old_chain);
7999 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8001 case SERIAL_TIMEOUT:
8005 do_cleanups (old_chain);
8008 break; /* Retransmit buffer. */
8012 fprintf_unfiltered (gdb_stdlog,
8013 "Packet instead of Ack, ignoring it\n");
8014 /* It's probably an old response sent because an ACK
8015 was lost. Gobble up the packet and ack it so it
8016 doesn't get retransmitted when we resend this
8019 remote_serial_write ("+", 1);
8020 continue; /* Now, go look for +. */
8027 /* If we got a notification, handle it, and go back to looking
8029 /* We've found the start of a notification. Now
8030 collect the data. */
8031 val = read_frame (&rs->buf, &rs->buf_size);
8036 struct cleanup *old_chain;
8039 str = escape_buffer (rs->buf, val);
8040 old_chain = make_cleanup (xfree, str);
8041 fprintf_unfiltered (gdb_stdlog,
8042 " Notification received: %s\n",
8044 do_cleanups (old_chain);
8046 handle_notification (rs->notif_state, rs->buf);
8047 /* We're in sync now, rewait for the ack. */
8054 if (!started_error_output)
8056 started_error_output = 1;
8057 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8059 fputc_unfiltered (ch & 0177, gdb_stdlog);
8060 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8069 if (!started_error_output)
8071 started_error_output = 1;
8072 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8074 fputc_unfiltered (ch & 0177, gdb_stdlog);
8078 break; /* Here to retransmit. */
8082 /* This is wrong. If doing a long backtrace, the user should be
8083 able to get out next time we call QUIT, without anything as
8084 violent as interrupt_query. If we want to provide a way out of
8085 here without getting to the next QUIT, it should be based on
8086 hitting ^C twice as in remote_wait. */
8095 do_cleanups (old_chain);
8099 /* Come here after finding the start of a frame when we expected an
8100 ack. Do our best to discard the rest of this packet. */
8109 c = readchar (remote_timeout);
8112 case SERIAL_TIMEOUT:
8113 /* Nothing we can do. */
8116 /* Discard the two bytes of checksum and stop. */
8117 c = readchar (remote_timeout);
8119 c = readchar (remote_timeout);
8122 case '*': /* Run length encoding. */
8123 /* Discard the repeat count. */
8124 c = readchar (remote_timeout);
8129 /* A regular character. */
8135 /* Come here after finding the start of the frame. Collect the rest
8136 into *BUF, verifying the checksum, length, and handling run-length
8137 compression. NUL terminate the buffer. If there is not enough room,
8138 expand *BUF using xrealloc.
8140 Returns -1 on error, number of characters in buffer (ignoring the
8141 trailing NULL) on success. (could be extended to return one of the
8142 SERIAL status indications). */
8145 read_frame (char **buf_p,
8152 struct remote_state *rs = get_remote_state ();
8159 c = readchar (remote_timeout);
8162 case SERIAL_TIMEOUT:
8164 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8168 fputs_filtered ("Saw new packet start in middle of old one\n",
8170 return -1; /* Start a new packet, count retries. */
8173 unsigned char pktcsum;
8179 check_0 = readchar (remote_timeout);
8181 check_1 = readchar (remote_timeout);
8183 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8186 fputs_filtered ("Timeout in checksum, retrying\n",
8190 else if (check_0 < 0 || check_1 < 0)
8193 fputs_filtered ("Communication error in checksum\n",
8198 /* Don't recompute the checksum; with no ack packets we
8199 don't have any way to indicate a packet retransmission
8204 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8205 if (csum == pktcsum)
8210 struct cleanup *old_chain;
8213 str = escape_buffer (buf, bc);
8214 old_chain = make_cleanup (xfree, str);
8215 fprintf_unfiltered (gdb_stdlog,
8216 "Bad checksum, sentsum=0x%x, "
8217 "csum=0x%x, buf=%s\n",
8218 pktcsum, csum, str);
8219 do_cleanups (old_chain);
8221 /* Number of characters in buffer ignoring trailing
8225 case '*': /* Run length encoding. */
8230 c = readchar (remote_timeout);
8232 repeat = c - ' ' + 3; /* Compute repeat count. */
8234 /* The character before ``*'' is repeated. */
8236 if (repeat > 0 && repeat <= 255 && bc > 0)
8238 if (bc + repeat - 1 >= *sizeof_buf - 1)
8240 /* Make some more room in the buffer. */
8241 *sizeof_buf += repeat;
8242 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8246 memset (&buf[bc], buf[bc - 1], repeat);
8252 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8256 if (bc >= *sizeof_buf - 1)
8258 /* Make some more room in the buffer. */
8260 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8271 /* Read a packet from the remote machine, with error checking, and
8272 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8273 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8274 rather than timing out; this is used (in synchronous mode) to wait
8275 for a target that is is executing user code to stop. */
8276 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8277 don't have to change all the calls to getpkt to deal with the
8278 return value, because at the moment I don't know what the right
8279 thing to do it for those. */
8287 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8291 /* Read a packet from the remote machine, with error checking, and
8292 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8293 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8294 rather than timing out; this is used (in synchronous mode) to wait
8295 for a target that is is executing user code to stop. If FOREVER ==
8296 0, this function is allowed to time out gracefully and return an
8297 indication of this to the caller. Otherwise return the number of
8298 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8299 enough reason to return to the caller. *IS_NOTIF is an output
8300 boolean that indicates whether *BUF holds a notification or not
8301 (a regular packet). */
8304 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8305 int expecting_notif, int *is_notif)
8307 struct remote_state *rs = get_remote_state ();
8313 /* We're reading a new response. Make sure we don't look at a
8314 previously cached response. */
8315 rs->cached_wait_status = 0;
8317 strcpy (*buf, "timeout");
8320 timeout = watchdog > 0 ? watchdog : -1;
8321 else if (expecting_notif)
8322 timeout = 0; /* There should already be a char in the buffer. If
8325 timeout = remote_timeout;
8329 /* Process any number of notifications, and then return when
8333 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8335 for (tries = 1; tries <= MAX_TRIES; tries++)
8337 /* This can loop forever if the remote side sends us
8338 characters continuously, but if it pauses, we'll get
8339 SERIAL_TIMEOUT from readchar because of timeout. Then
8340 we'll count that as a retry.
8342 Note that even when forever is set, we will only wait
8343 forever prior to the start of a packet. After that, we
8344 expect characters to arrive at a brisk pace. They should
8345 show up within remote_timeout intervals. */
8347 c = readchar (timeout);
8348 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8350 if (c == SERIAL_TIMEOUT)
8352 if (expecting_notif)
8353 return -1; /* Don't complain, it's normal to not get
8354 anything in this case. */
8356 if (forever) /* Watchdog went off? Kill the target. */
8359 remote_unpush_target ();
8360 throw_error (TARGET_CLOSE_ERROR,
8361 _("Watchdog timeout has expired. "
8362 "Target detached."));
8365 fputs_filtered ("Timed out.\n", gdb_stdlog);
8369 /* We've found the start of a packet or notification.
8370 Now collect the data. */
8371 val = read_frame (buf, sizeof_buf);
8376 remote_serial_write ("-", 1);
8379 if (tries > MAX_TRIES)
8381 /* We have tried hard enough, and just can't receive the
8382 packet/notification. Give up. */
8383 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8385 /* Skip the ack char if we're in no-ack mode. */
8386 if (!rs->noack_mode)
8387 remote_serial_write ("+", 1);
8391 /* If we got an ordinary packet, return that to our caller. */
8396 struct cleanup *old_chain;
8399 str = escape_buffer (*buf, val);
8400 old_chain = make_cleanup (xfree, str);
8401 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8402 do_cleanups (old_chain);
8405 /* Skip the ack char if we're in no-ack mode. */
8406 if (!rs->noack_mode)
8407 remote_serial_write ("+", 1);
8408 if (is_notif != NULL)
8413 /* If we got a notification, handle it, and go back to looking
8417 gdb_assert (c == '%');
8421 struct cleanup *old_chain;
8424 str = escape_buffer (*buf, val);
8425 old_chain = make_cleanup (xfree, str);
8426 fprintf_unfiltered (gdb_stdlog,
8427 " Notification received: %s\n",
8429 do_cleanups (old_chain);
8431 if (is_notif != NULL)
8434 handle_notification (rs->notif_state, *buf);
8436 /* Notifications require no acknowledgement. */
8438 if (expecting_notif)
8445 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8447 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8451 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8454 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8458 /* Check whether EVENT is a fork event for the process specified
8459 by the pid passed in DATA, and if it is, kill the fork child. */
8462 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8463 QUEUE_ITER (stop_reply_p) *iter,
8467 struct queue_iter_param *param = data;
8468 int parent_pid = *(int *) param->input;
8470 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8472 struct remote_state *rs = get_remote_state ();
8473 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8476 res = remote_vkill (child_pid, rs);
8478 error (_("Can't kill fork child process %d"), child_pid);
8484 /* Kill any new fork children of process PID that haven't been
8485 processed by follow_fork. */
8488 kill_new_fork_children (int pid, struct remote_state *rs)
8490 struct thread_info *thread;
8491 struct notif_client *notif = ¬if_client_stop;
8492 struct queue_iter_param param;
8494 /* Kill the fork child threads of any threads in process PID
8495 that are stopped at a fork event. */
8496 ALL_NON_EXITED_THREADS (thread)
8498 struct target_waitstatus *ws = &thread->pending_follow;
8500 if (is_pending_fork_parent (ws, pid, thread->ptid))
8502 struct remote_state *rs = get_remote_state ();
8503 int child_pid = ptid_get_pid (ws->value.related_pid);
8506 res = remote_vkill (child_pid, rs);
8508 error (_("Can't kill fork child process %d"), child_pid);
8512 /* Check for any pending fork events (not reported or processed yet)
8513 in process PID and kill those fork child threads as well. */
8514 remote_notif_get_pending_events (notif);
8516 param.output = NULL;
8517 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8518 kill_child_of_pending_fork, ¶m);
8523 remote_kill (struct target_ops *ops)
8526 /* Catch errors so the user can quit from gdb even when we
8527 aren't on speaking terms with the remote system. */
8532 CATCH (ex, RETURN_MASK_ERROR)
8534 if (ex.error == TARGET_CLOSE_ERROR)
8536 /* If we got an (EOF) error that caused the target
8537 to go away, then we're done, that's what we wanted.
8538 "k" is susceptible to cause a premature EOF, given
8539 that the remote server isn't actually required to
8540 reply to "k", and it can happen that it doesn't
8541 even get to reply ACK to the "k". */
8545 /* Otherwise, something went wrong. We didn't actually kill
8546 the target. Just propagate the exception, and let the
8547 user or higher layers decide what to do. */
8548 throw_exception (ex);
8552 /* We've killed the remote end, we get to mourn it. Since this is
8553 target remote, single-process, mourning the inferior also
8554 unpushes remote_ops. */
8555 target_mourn_inferior ();
8559 remote_vkill (int pid, struct remote_state *rs)
8561 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8564 /* Tell the remote target to detach. */
8565 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8567 getpkt (&rs->buf, &rs->buf_size, 0);
8569 switch (packet_ok (rs->buf,
8570 &remote_protocol_packets[PACKET_vKill]))
8576 case PACKET_UNKNOWN:
8579 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8584 extended_remote_kill (struct target_ops *ops)
8587 int pid = ptid_get_pid (inferior_ptid);
8588 struct remote_state *rs = get_remote_state ();
8590 /* If we're stopped while forking and we haven't followed yet, kill the
8591 child task. We need to do this before killing the parent task
8592 because if this is a vfork then the parent will be sleeping. */
8593 kill_new_fork_children (pid, rs);
8595 res = remote_vkill (pid, rs);
8596 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8598 /* Don't try 'k' on a multi-process aware stub -- it has no way
8599 to specify the pid. */
8603 getpkt (&rs->buf, &rs->buf_size, 0);
8604 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8607 /* Don't wait for it to die. I'm not really sure it matters whether
8608 we do or not. For the existing stubs, kill is a noop. */
8614 error (_("Can't kill process"));
8616 target_mourn_inferior ();
8620 remote_mourn (struct target_ops *target)
8622 unpush_target (target);
8624 /* remote_close takes care of doing most of the clean up. */
8625 generic_mourn_inferior ();
8629 extended_remote_mourn (struct target_ops *target)
8631 struct remote_state *rs = get_remote_state ();
8633 /* In case we got here due to an error, but we're going to stay
8635 rs->waiting_for_stop_reply = 0;
8637 /* If the current general thread belonged to the process we just
8638 detached from or has exited, the remote side current general
8639 thread becomes undefined. Considering a case like this:
8641 - We just got here due to a detach.
8642 - The process that we're detaching from happens to immediately
8643 report a global breakpoint being hit in non-stop mode, in the
8644 same thread we had selected before.
8645 - GDB attaches to this process again.
8646 - This event happens to be the next event we handle.
8648 GDB would consider that the current general thread didn't need to
8649 be set on the stub side (with Hg), since for all it knew,
8650 GENERAL_THREAD hadn't changed.
8652 Notice that although in all-stop mode, the remote server always
8653 sets the current thread to the thread reporting the stop event,
8654 that doesn't happen in non-stop mode; in non-stop, the stub *must
8655 not* change the current thread when reporting a breakpoint hit,
8656 due to the decoupling of event reporting and event handling.
8658 To keep things simple, we always invalidate our notion of the
8660 record_currthread (rs, minus_one_ptid);
8662 /* Unlike "target remote", we do not want to unpush the target; then
8663 the next time the user says "run", we won't be connected. */
8665 /* Call common code to mark the inferior as not running. */
8666 generic_mourn_inferior ();
8668 if (!have_inferiors ())
8670 if (!remote_multi_process_p (rs))
8672 /* Check whether the target is running now - some remote stubs
8673 automatically restart after kill. */
8675 getpkt (&rs->buf, &rs->buf_size, 0);
8677 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8679 /* Assume that the target has been restarted. Set
8680 inferior_ptid so that bits of core GDB realizes
8681 there's something here, e.g., so that the user can
8682 say "kill" again. */
8683 inferior_ptid = magic_null_ptid;
8690 extended_remote_supports_disable_randomization (struct target_ops *self)
8692 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8696 extended_remote_disable_randomization (int val)
8698 struct remote_state *rs = get_remote_state ();
8701 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8704 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8706 error (_("Target does not support QDisableRandomization."));
8707 if (strcmp (reply, "OK") != 0)
8708 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8712 extended_remote_run (char *args)
8714 struct remote_state *rs = get_remote_state ();
8716 const char *remote_exec_file = get_remote_exec_file ();
8718 /* If the user has disabled vRun support, or we have detected that
8719 support is not available, do not try it. */
8720 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8723 strcpy (rs->buf, "vRun;");
8724 len = strlen (rs->buf);
8726 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8727 error (_("Remote file name too long for run packet"));
8728 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8729 strlen (remote_exec_file));
8731 gdb_assert (args != NULL);
8734 struct cleanup *back_to;
8738 argv = gdb_buildargv (args);
8739 back_to = make_cleanup_freeargv (argv);
8740 for (i = 0; argv[i] != NULL; i++)
8742 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8743 error (_("Argument list too long for run packet"));
8744 rs->buf[len++] = ';';
8745 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8748 do_cleanups (back_to);
8751 rs->buf[len++] = '\0';
8754 getpkt (&rs->buf, &rs->buf_size, 0);
8756 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8759 /* We have a wait response. All is well. */
8761 case PACKET_UNKNOWN:
8764 if (remote_exec_file[0] == '\0')
8765 error (_("Running the default executable on the remote target failed; "
8766 "try \"set remote exec-file\"?"));
8768 error (_("Running \"%s\" on the remote target failed"),
8771 gdb_assert_not_reached (_("bad switch"));
8775 /* In the extended protocol we want to be able to do things like
8776 "run" and have them basically work as expected. So we need
8777 a special create_inferior function. We support changing the
8778 executable file and the command line arguments, but not the
8782 extended_remote_create_inferior (struct target_ops *ops,
8783 char *exec_file, char *args,
8784 char **env, int from_tty)
8788 struct remote_state *rs = get_remote_state ();
8789 const char *remote_exec_file = get_remote_exec_file ();
8791 /* If running asynchronously, register the target file descriptor
8792 with the event loop. */
8793 if (target_can_async_p ())
8796 /* Disable address space randomization if requested (and supported). */
8797 if (extended_remote_supports_disable_randomization (ops))
8798 extended_remote_disable_randomization (disable_randomization);
8800 /* Now restart the remote server. */
8801 run_worked = extended_remote_run (args) != -1;
8804 /* vRun was not supported. Fail if we need it to do what the
8806 if (remote_exec_file[0])
8807 error (_("Remote target does not support \"set remote exec-file\""));
8809 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8811 /* Fall back to "R". */
8812 extended_remote_restart ();
8815 if (!have_inferiors ())
8817 /* Clean up from the last time we ran, before we mark the target
8818 running again. This will mark breakpoints uninserted, and
8819 get_offsets may insert breakpoints. */
8820 init_thread_list ();
8821 init_wait_for_inferior ();
8824 /* vRun's success return is a stop reply. */
8825 stop_reply = run_worked ? rs->buf : NULL;
8826 add_current_inferior_and_thread (stop_reply);
8828 /* Get updated offsets, if the stub uses qOffsets. */
8833 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8834 the list of conditions (in agent expression bytecode format), if any, the
8835 target needs to evaluate. The output is placed into the packet buffer
8836 started from BUF and ended at BUF_END. */
8839 remote_add_target_side_condition (struct gdbarch *gdbarch,
8840 struct bp_target_info *bp_tgt, char *buf,
8843 struct agent_expr *aexpr = NULL;
8846 char *buf_start = buf;
8848 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8851 buf += strlen (buf);
8852 xsnprintf (buf, buf_end - buf, "%s", ";");
8855 /* Send conditions to the target and free the vector. */
8857 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8860 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8861 buf += strlen (buf);
8862 for (i = 0; i < aexpr->len; ++i)
8863 buf = pack_hex_byte (buf, aexpr->buf[i]);
8870 remote_add_target_side_commands (struct gdbarch *gdbarch,
8871 struct bp_target_info *bp_tgt, char *buf)
8873 struct agent_expr *aexpr = NULL;
8876 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8879 buf += strlen (buf);
8881 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8882 buf += strlen (buf);
8884 /* Concatenate all the agent expressions that are commands into the
8887 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8890 sprintf (buf, "X%x,", aexpr->len);
8891 buf += strlen (buf);
8892 for (i = 0; i < aexpr->len; ++i)
8893 buf = pack_hex_byte (buf, aexpr->buf[i]);
8898 /* Insert a breakpoint. On targets that have software breakpoint
8899 support, we ask the remote target to do the work; on targets
8900 which don't, we insert a traditional memory breakpoint. */
8903 remote_insert_breakpoint (struct target_ops *ops,
8904 struct gdbarch *gdbarch,
8905 struct bp_target_info *bp_tgt)
8907 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8908 If it succeeds, then set the support to PACKET_ENABLE. If it
8909 fails, and the user has explicitly requested the Z support then
8910 report an error, otherwise, mark it disabled and go on. */
8912 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8914 CORE_ADDR addr = bp_tgt->reqstd_address;
8915 struct remote_state *rs;
8918 struct condition_list *cond = NULL;
8920 /* Make sure the remote is pointing at the right process, if
8922 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8923 set_general_process ();
8925 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8927 rs = get_remote_state ();
8929 endbuf = rs->buf + get_remote_packet_size ();
8934 addr = (ULONGEST) remote_address_masked (addr);
8935 p += hexnumstr (p, addr);
8936 xsnprintf (p, endbuf - p, ",%d", bpsize);
8938 if (remote_supports_cond_breakpoints (ops))
8939 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8941 if (remote_can_run_breakpoint_commands (ops))
8942 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8945 getpkt (&rs->buf, &rs->buf_size, 0);
8947 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8952 bp_tgt->placed_address = addr;
8953 bp_tgt->placed_size = bpsize;
8955 case PACKET_UNKNOWN:
8960 /* If this breakpoint has target-side commands but this stub doesn't
8961 support Z0 packets, throw error. */
8962 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8963 throw_error (NOT_SUPPORTED_ERROR, _("\
8964 Target doesn't support breakpoints that have target side commands."));
8966 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8970 remote_remove_breakpoint (struct target_ops *ops,
8971 struct gdbarch *gdbarch,
8972 struct bp_target_info *bp_tgt)
8974 CORE_ADDR addr = bp_tgt->placed_address;
8975 struct remote_state *rs = get_remote_state ();
8977 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8980 char *endbuf = rs->buf + get_remote_packet_size ();
8982 /* Make sure the remote is pointing at the right process, if
8984 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8985 set_general_process ();
8991 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8992 p += hexnumstr (p, addr);
8993 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8996 getpkt (&rs->buf, &rs->buf_size, 0);
8998 return (rs->buf[0] == 'E');
9001 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9004 static enum Z_packet_type
9005 watchpoint_to_Z_packet (int type)
9010 return Z_PACKET_WRITE_WP;
9013 return Z_PACKET_READ_WP;
9016 return Z_PACKET_ACCESS_WP;
9019 internal_error (__FILE__, __LINE__,
9020 _("hw_bp_to_z: bad watchpoint type %d"), type);
9025 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9026 enum target_hw_bp_type type, struct expression *cond)
9028 struct remote_state *rs = get_remote_state ();
9029 char *endbuf = rs->buf + get_remote_packet_size ();
9031 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9033 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9036 /* Make sure the remote is pointing at the right process, if
9038 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9039 set_general_process ();
9041 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9042 p = strchr (rs->buf, '\0');
9043 addr = remote_address_masked (addr);
9044 p += hexnumstr (p, (ULONGEST) addr);
9045 xsnprintf (p, endbuf - p, ",%x", len);
9048 getpkt (&rs->buf, &rs->buf_size, 0);
9050 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9054 case PACKET_UNKNOWN:
9059 internal_error (__FILE__, __LINE__,
9060 _("remote_insert_watchpoint: reached end of function"));
9064 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9065 CORE_ADDR start, int length)
9067 CORE_ADDR diff = remote_address_masked (addr - start);
9069 return diff < length;
9074 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9075 enum target_hw_bp_type type, struct expression *cond)
9077 struct remote_state *rs = get_remote_state ();
9078 char *endbuf = rs->buf + get_remote_packet_size ();
9080 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9082 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9085 /* Make sure the remote is pointing at the right process, if
9087 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9088 set_general_process ();
9090 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9091 p = strchr (rs->buf, '\0');
9092 addr = remote_address_masked (addr);
9093 p += hexnumstr (p, (ULONGEST) addr);
9094 xsnprintf (p, endbuf - p, ",%x", len);
9096 getpkt (&rs->buf, &rs->buf_size, 0);
9098 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9101 case PACKET_UNKNOWN:
9106 internal_error (__FILE__, __LINE__,
9107 _("remote_remove_watchpoint: reached end of function"));
9111 int remote_hw_watchpoint_limit = -1;
9112 int remote_hw_watchpoint_length_limit = -1;
9113 int remote_hw_breakpoint_limit = -1;
9116 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9117 CORE_ADDR addr, int len)
9119 if (remote_hw_watchpoint_length_limit == 0)
9121 else if (remote_hw_watchpoint_length_limit < 0)
9123 else if (len <= remote_hw_watchpoint_length_limit)
9130 remote_check_watch_resources (struct target_ops *self,
9131 enum bptype type, int cnt, int ot)
9133 if (type == bp_hardware_breakpoint)
9135 if (remote_hw_breakpoint_limit == 0)
9137 else if (remote_hw_breakpoint_limit < 0)
9139 else if (cnt <= remote_hw_breakpoint_limit)
9144 if (remote_hw_watchpoint_limit == 0)
9146 else if (remote_hw_watchpoint_limit < 0)
9150 else if (cnt <= remote_hw_watchpoint_limit)
9156 /* The to_stopped_by_sw_breakpoint method of target remote. */
9159 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9161 struct remote_state *rs = get_remote_state ();
9163 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9166 /* The to_supports_stopped_by_sw_breakpoint method of target
9170 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9172 struct remote_state *rs = get_remote_state ();
9174 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9177 /* The to_stopped_by_hw_breakpoint method of target remote. */
9180 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9182 struct remote_state *rs = get_remote_state ();
9184 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9187 /* The to_supports_stopped_by_hw_breakpoint method of target
9191 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9193 struct remote_state *rs = get_remote_state ();
9195 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9199 remote_stopped_by_watchpoint (struct target_ops *ops)
9201 struct remote_state *rs = get_remote_state ();
9203 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
9207 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9209 struct remote_state *rs = get_remote_state ();
9212 if (remote_stopped_by_watchpoint (target))
9214 *addr_p = rs->remote_watch_data_address;
9223 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9224 struct bp_target_info *bp_tgt)
9226 CORE_ADDR addr = bp_tgt->reqstd_address;
9227 struct remote_state *rs;
9232 /* The length field should be set to the size of a breakpoint
9233 instruction, even though we aren't inserting one ourselves. */
9235 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9237 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9240 /* Make sure the remote is pointing at the right process, if
9242 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9243 set_general_process ();
9245 rs = get_remote_state ();
9247 endbuf = rs->buf + get_remote_packet_size ();
9253 addr = remote_address_masked (addr);
9254 p += hexnumstr (p, (ULONGEST) addr);
9255 xsnprintf (p, endbuf - p, ",%x", bpsize);
9257 if (remote_supports_cond_breakpoints (self))
9258 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9260 if (remote_can_run_breakpoint_commands (self))
9261 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9264 getpkt (&rs->buf, &rs->buf_size, 0);
9266 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9269 if (rs->buf[1] == '.')
9271 message = strchr (rs->buf + 2, '.');
9273 error (_("Remote failure reply: %s"), message + 1);
9276 case PACKET_UNKNOWN:
9279 bp_tgt->placed_address = addr;
9280 bp_tgt->placed_size = bpsize;
9283 internal_error (__FILE__, __LINE__,
9284 _("remote_insert_hw_breakpoint: reached end of function"));
9289 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9290 struct bp_target_info *bp_tgt)
9293 struct remote_state *rs = get_remote_state ();
9295 char *endbuf = rs->buf + get_remote_packet_size ();
9297 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9300 /* Make sure the remote is pointing at the right process, if
9302 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9303 set_general_process ();
9309 addr = remote_address_masked (bp_tgt->placed_address);
9310 p += hexnumstr (p, (ULONGEST) addr);
9311 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9314 getpkt (&rs->buf, &rs->buf_size, 0);
9316 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9319 case PACKET_UNKNOWN:
9324 internal_error (__FILE__, __LINE__,
9325 _("remote_remove_hw_breakpoint: reached end of function"));
9328 /* Verify memory using the "qCRC:" request. */
9331 remote_verify_memory (struct target_ops *ops,
9332 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9334 struct remote_state *rs = get_remote_state ();
9335 unsigned long host_crc, target_crc;
9338 /* It doesn't make sense to use qCRC if the remote target is
9339 connected but not running. */
9340 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9342 enum packet_result result;
9344 /* Make sure the remote is pointing at the right process. */
9345 set_general_process ();
9347 /* FIXME: assumes lma can fit into long. */
9348 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9349 (long) lma, (long) size);
9352 /* Be clever; compute the host_crc before waiting for target
9354 host_crc = xcrc32 (data, size, 0xffffffff);
9356 getpkt (&rs->buf, &rs->buf_size, 0);
9358 result = packet_ok (rs->buf,
9359 &remote_protocol_packets[PACKET_qCRC]);
9360 if (result == PACKET_ERROR)
9362 else if (result == PACKET_OK)
9364 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9365 target_crc = target_crc * 16 + fromhex (*tmp);
9367 return (host_crc == target_crc);
9371 return simple_verify_memory (ops, data, lma, size);
9374 /* compare-sections command
9376 With no arguments, compares each loadable section in the exec bfd
9377 with the same memory range on the target, and reports mismatches.
9378 Useful for verifying the image on the target against the exec file. */
9381 compare_sections_command (char *args, int from_tty)
9384 struct cleanup *old_chain;
9386 const char *sectname;
9395 error (_("command cannot be used without an exec file"));
9397 /* Make sure the remote is pointing at the right process. */
9398 set_general_process ();
9400 if (args != NULL && strcmp (args, "-r") == 0)
9406 for (s = exec_bfd->sections; s; s = s->next)
9408 if (!(s->flags & SEC_LOAD))
9409 continue; /* Skip non-loadable section. */
9411 if (read_only && (s->flags & SEC_READONLY) == 0)
9412 continue; /* Skip writeable sections */
9414 size = bfd_get_section_size (s);
9416 continue; /* Skip zero-length section. */
9418 sectname = bfd_get_section_name (exec_bfd, s);
9419 if (args && strcmp (args, sectname) != 0)
9420 continue; /* Not the section selected by user. */
9422 matched = 1; /* Do this section. */
9425 sectdata = xmalloc (size);
9426 old_chain = make_cleanup (xfree, sectdata);
9427 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9429 res = target_verify_memory (sectdata, lma, size);
9432 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9433 paddress (target_gdbarch (), lma),
9434 paddress (target_gdbarch (), lma + size));
9436 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9437 paddress (target_gdbarch (), lma),
9438 paddress (target_gdbarch (), lma + size));
9440 printf_filtered ("matched.\n");
9443 printf_filtered ("MIS-MATCHED!\n");
9447 do_cleanups (old_chain);
9450 warning (_("One or more sections of the target image does not match\n\
9451 the loaded file\n"));
9452 if (args && !matched)
9453 printf_filtered (_("No loaded section named '%s'.\n"), args);
9456 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9457 into remote target. The number of bytes written to the remote
9458 target is returned, or -1 for error. */
9460 static enum target_xfer_status
9461 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9462 const char *annex, const gdb_byte *writebuf,
9463 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9464 struct packet_config *packet)
9468 struct remote_state *rs = get_remote_state ();
9469 int max_size = get_memory_write_packet_size ();
9471 if (packet->support == PACKET_DISABLE)
9472 return TARGET_XFER_E_IO;
9474 /* Insert header. */
9475 i = snprintf (rs->buf, max_size,
9476 "qXfer:%s:write:%s:%s:",
9477 object_name, annex ? annex : "",
9478 phex_nz (offset, sizeof offset));
9479 max_size -= (i + 1);
9481 /* Escape as much data as fits into rs->buf. */
9482 buf_len = remote_escape_output
9483 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9485 if (putpkt_binary (rs->buf, i + buf_len) < 0
9486 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9487 || packet_ok (rs->buf, packet) != PACKET_OK)
9488 return TARGET_XFER_E_IO;
9490 unpack_varlen_hex (rs->buf, &n);
9493 return TARGET_XFER_OK;
9496 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9497 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9498 number of bytes read is returned, or 0 for EOF, or -1 for error.
9499 The number of bytes read may be less than LEN without indicating an
9500 EOF. PACKET is checked and updated to indicate whether the remote
9501 target supports this object. */
9503 static enum target_xfer_status
9504 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9506 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9507 ULONGEST *xfered_len,
9508 struct packet_config *packet)
9510 struct remote_state *rs = get_remote_state ();
9511 LONGEST i, n, packet_len;
9513 if (packet->support == PACKET_DISABLE)
9514 return TARGET_XFER_E_IO;
9516 /* Check whether we've cached an end-of-object packet that matches
9518 if (rs->finished_object)
9520 if (strcmp (object_name, rs->finished_object) == 0
9521 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9522 && offset == rs->finished_offset)
9523 return TARGET_XFER_EOF;
9526 /* Otherwise, we're now reading something different. Discard
9528 xfree (rs->finished_object);
9529 xfree (rs->finished_annex);
9530 rs->finished_object = NULL;
9531 rs->finished_annex = NULL;
9534 /* Request only enough to fit in a single packet. The actual data
9535 may not, since we don't know how much of it will need to be escaped;
9536 the target is free to respond with slightly less data. We subtract
9537 five to account for the response type and the protocol frame. */
9538 n = min (get_remote_packet_size () - 5, len);
9539 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9540 object_name, annex ? annex : "",
9541 phex_nz (offset, sizeof offset),
9542 phex_nz (n, sizeof n));
9543 i = putpkt (rs->buf);
9545 return TARGET_XFER_E_IO;
9548 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9549 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9550 return TARGET_XFER_E_IO;
9552 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9553 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9555 /* 'm' means there is (or at least might be) more data after this
9556 batch. That does not make sense unless there's at least one byte
9557 of data in this reply. */
9558 if (rs->buf[0] == 'm' && packet_len == 1)
9559 error (_("Remote qXfer reply contained no data."));
9561 /* Got some data. */
9562 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9563 packet_len - 1, readbuf, n);
9565 /* 'l' is an EOF marker, possibly including a final block of data,
9566 or possibly empty. If we have the final block of a non-empty
9567 object, record this fact to bypass a subsequent partial read. */
9568 if (rs->buf[0] == 'l' && offset + i > 0)
9570 rs->finished_object = xstrdup (object_name);
9571 rs->finished_annex = xstrdup (annex ? annex : "");
9572 rs->finished_offset = offset + i;
9576 return TARGET_XFER_EOF;
9580 return TARGET_XFER_OK;
9584 static enum target_xfer_status
9585 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9586 const char *annex, gdb_byte *readbuf,
9587 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9588 ULONGEST *xfered_len)
9590 struct remote_state *rs;
9594 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9596 set_remote_traceframe ();
9597 set_general_thread (inferior_ptid);
9599 rs = get_remote_state ();
9601 /* Handle memory using the standard memory routines. */
9602 if (object == TARGET_OBJECT_MEMORY)
9604 /* If the remote target is connected but not running, we should
9605 pass this request down to a lower stratum (e.g. the executable
9607 if (!target_has_execution)
9608 return TARGET_XFER_EOF;
9610 if (writebuf != NULL)
9611 return remote_write_bytes (offset, writebuf, len, unit_size,
9614 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9618 /* Handle SPU memory using qxfer packets. */
9619 if (object == TARGET_OBJECT_SPU)
9622 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9623 xfered_len, &remote_protocol_packets
9624 [PACKET_qXfer_spu_read]);
9626 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9627 xfered_len, &remote_protocol_packets
9628 [PACKET_qXfer_spu_write]);
9631 /* Handle extra signal info using qxfer packets. */
9632 if (object == TARGET_OBJECT_SIGNAL_INFO)
9635 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9636 xfered_len, &remote_protocol_packets
9637 [PACKET_qXfer_siginfo_read]);
9639 return remote_write_qxfer (ops, "siginfo", annex,
9640 writebuf, offset, len, xfered_len,
9641 &remote_protocol_packets
9642 [PACKET_qXfer_siginfo_write]);
9645 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9648 return remote_read_qxfer (ops, "statictrace", annex,
9649 readbuf, offset, len, xfered_len,
9650 &remote_protocol_packets
9651 [PACKET_qXfer_statictrace_read]);
9653 return TARGET_XFER_E_IO;
9656 /* Only handle flash writes. */
9657 if (writebuf != NULL)
9663 case TARGET_OBJECT_FLASH:
9664 return remote_flash_write (ops, offset, len, xfered_len,
9668 return TARGET_XFER_E_IO;
9672 /* Map pre-existing objects onto letters. DO NOT do this for new
9673 objects!!! Instead specify new query packets. */
9676 case TARGET_OBJECT_AVR:
9680 case TARGET_OBJECT_AUXV:
9681 gdb_assert (annex == NULL);
9682 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9684 &remote_protocol_packets[PACKET_qXfer_auxv]);
9686 case TARGET_OBJECT_AVAILABLE_FEATURES:
9687 return remote_read_qxfer
9688 (ops, "features", annex, readbuf, offset, len, xfered_len,
9689 &remote_protocol_packets[PACKET_qXfer_features]);
9691 case TARGET_OBJECT_LIBRARIES:
9692 return remote_read_qxfer
9693 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9694 &remote_protocol_packets[PACKET_qXfer_libraries]);
9696 case TARGET_OBJECT_LIBRARIES_SVR4:
9697 return remote_read_qxfer
9698 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9699 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9701 case TARGET_OBJECT_MEMORY_MAP:
9702 gdb_assert (annex == NULL);
9703 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9705 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9707 case TARGET_OBJECT_OSDATA:
9708 /* Should only get here if we're connected. */
9709 gdb_assert (rs->remote_desc);
9710 return remote_read_qxfer
9711 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9712 &remote_protocol_packets[PACKET_qXfer_osdata]);
9714 case TARGET_OBJECT_THREADS:
9715 gdb_assert (annex == NULL);
9716 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9718 &remote_protocol_packets[PACKET_qXfer_threads]);
9720 case TARGET_OBJECT_TRACEFRAME_INFO:
9721 gdb_assert (annex == NULL);
9722 return remote_read_qxfer
9723 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9724 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9726 case TARGET_OBJECT_FDPIC:
9727 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9729 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9731 case TARGET_OBJECT_OPENVMS_UIB:
9732 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9734 &remote_protocol_packets[PACKET_qXfer_uib]);
9736 case TARGET_OBJECT_BTRACE:
9737 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9739 &remote_protocol_packets[PACKET_qXfer_btrace]);
9741 case TARGET_OBJECT_BTRACE_CONF:
9742 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9744 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9746 case TARGET_OBJECT_EXEC_FILE:
9747 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9749 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9752 return TARGET_XFER_E_IO;
9755 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9756 large enough let the caller deal with it. */
9757 if (len < get_remote_packet_size ())
9758 return TARGET_XFER_E_IO;
9759 len = get_remote_packet_size ();
9761 /* Except for querying the minimum buffer size, target must be open. */
9762 if (!rs->remote_desc)
9763 error (_("remote query is only available after target open"));
9765 gdb_assert (annex != NULL);
9766 gdb_assert (readbuf != NULL);
9772 /* We used one buffer char for the remote protocol q command and
9773 another for the query type. As the remote protocol encapsulation
9774 uses 4 chars plus one extra in case we are debugging
9775 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9778 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9780 /* Bad caller may have sent forbidden characters. */
9781 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9786 gdb_assert (annex[i] == '\0');
9788 i = putpkt (rs->buf);
9790 return TARGET_XFER_E_IO;
9792 getpkt (&rs->buf, &rs->buf_size, 0);
9793 strcpy ((char *) readbuf, rs->buf);
9795 *xfered_len = strlen ((char *) readbuf);
9796 return TARGET_XFER_OK;
9800 remote_search_memory (struct target_ops* ops,
9801 CORE_ADDR start_addr, ULONGEST search_space_len,
9802 const gdb_byte *pattern, ULONGEST pattern_len,
9803 CORE_ADDR *found_addrp)
9805 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9806 struct remote_state *rs = get_remote_state ();
9807 int max_size = get_memory_write_packet_size ();
9808 struct packet_config *packet =
9809 &remote_protocol_packets[PACKET_qSearch_memory];
9810 /* Number of packet bytes used to encode the pattern;
9811 this could be more than PATTERN_LEN due to escape characters. */
9812 int escaped_pattern_len;
9813 /* Amount of pattern that was encodable in the packet. */
9814 int used_pattern_len;
9817 ULONGEST found_addr;
9819 /* Don't go to the target if we don't have to.
9820 This is done before checking packet->support to avoid the possibility that
9821 a success for this edge case means the facility works in general. */
9822 if (pattern_len > search_space_len)
9824 if (pattern_len == 0)
9826 *found_addrp = start_addr;
9830 /* If we already know the packet isn't supported, fall back to the simple
9831 way of searching memory. */
9833 if (packet_config_support (packet) == PACKET_DISABLE)
9835 /* Target doesn't provided special support, fall back and use the
9836 standard support (copy memory and do the search here). */
9837 return simple_search_memory (ops, start_addr, search_space_len,
9838 pattern, pattern_len, found_addrp);
9841 /* Make sure the remote is pointing at the right process. */
9842 set_general_process ();
9844 /* Insert header. */
9845 i = snprintf (rs->buf, max_size,
9846 "qSearch:memory:%s;%s;",
9847 phex_nz (start_addr, addr_size),
9848 phex_nz (search_space_len, sizeof (search_space_len)));
9849 max_size -= (i + 1);
9851 /* Escape as much data as fits into rs->buf. */
9852 escaped_pattern_len =
9853 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
9854 &used_pattern_len, max_size);
9856 /* Bail if the pattern is too large. */
9857 if (used_pattern_len != pattern_len)
9858 error (_("Pattern is too large to transmit to remote target."));
9860 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9861 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9862 || packet_ok (rs->buf, packet) != PACKET_OK)
9864 /* The request may not have worked because the command is not
9865 supported. If so, fall back to the simple way. */
9866 if (packet->support == PACKET_DISABLE)
9868 return simple_search_memory (ops, start_addr, search_space_len,
9869 pattern, pattern_len, found_addrp);
9874 if (rs->buf[0] == '0')
9876 else if (rs->buf[0] == '1')
9879 if (rs->buf[1] != ',')
9880 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9881 unpack_varlen_hex (rs->buf + 2, &found_addr);
9882 *found_addrp = found_addr;
9885 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9891 remote_rcmd (struct target_ops *self, const char *command,
9892 struct ui_file *outbuf)
9894 struct remote_state *rs = get_remote_state ();
9897 if (!rs->remote_desc)
9898 error (_("remote rcmd is only available after target open"));
9900 /* Send a NULL command across as an empty command. */
9901 if (command == NULL)
9904 /* The query prefix. */
9905 strcpy (rs->buf, "qRcmd,");
9906 p = strchr (rs->buf, '\0');
9908 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9909 > get_remote_packet_size ())
9910 error (_("\"monitor\" command ``%s'' is too long."), command);
9912 /* Encode the actual command. */
9913 bin2hex ((const gdb_byte *) command, p, strlen (command));
9915 if (putpkt (rs->buf) < 0)
9916 error (_("Communication problem with target."));
9918 /* get/display the response */
9923 /* XXX - see also remote_get_noisy_reply(). */
9924 QUIT; /* Allow user to bail out with ^C. */
9926 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9928 /* Timeout. Continue to (try to) read responses.
9929 This is better than stopping with an error, assuming the stub
9930 is still executing the (long) monitor command.
9931 If needed, the user can interrupt gdb using C-c, obtaining
9932 an effect similar to stop on timeout. */
9937 error (_("Target does not support this command."));
9938 if (buf[0] == 'O' && buf[1] != 'K')
9940 remote_console_output (buf + 1); /* 'O' message from stub. */
9943 if (strcmp (buf, "OK") == 0)
9945 if (strlen (buf) == 3 && buf[0] == 'E'
9946 && isdigit (buf[1]) && isdigit (buf[2]))
9948 error (_("Protocol error with Rcmd"));
9950 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9952 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9954 fputc_unfiltered (c, outbuf);
9960 static VEC(mem_region_s) *
9961 remote_memory_map (struct target_ops *ops)
9963 VEC(mem_region_s) *result = NULL;
9964 char *text = target_read_stralloc (¤t_target,
9965 TARGET_OBJECT_MEMORY_MAP, NULL);
9969 struct cleanup *back_to = make_cleanup (xfree, text);
9971 result = parse_memory_map (text);
9972 do_cleanups (back_to);
9979 packet_command (char *args, int from_tty)
9981 struct remote_state *rs = get_remote_state ();
9983 if (!rs->remote_desc)
9984 error (_("command can only be used with remote target"));
9987 error (_("remote-packet command requires packet text as argument"));
9989 puts_filtered ("sending: ");
9990 print_packet (args);
9991 puts_filtered ("\n");
9994 getpkt (&rs->buf, &rs->buf_size, 0);
9995 puts_filtered ("received: ");
9996 print_packet (rs->buf);
9997 puts_filtered ("\n");
10001 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10003 static void display_thread_info (struct gdb_ext_thread_info *info);
10005 static void threadset_test_cmd (char *cmd, int tty);
10007 static void threadalive_test (char *cmd, int tty);
10009 static void threadlist_test_cmd (char *cmd, int tty);
10011 int get_and_display_threadinfo (threadref *ref);
10013 static void threadinfo_test_cmd (char *cmd, int tty);
10015 static int thread_display_step (threadref *ref, void *context);
10017 static void threadlist_update_test_cmd (char *cmd, int tty);
10019 static void init_remote_threadtests (void);
10021 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10024 threadset_test_cmd (char *cmd, int tty)
10026 int sample_thread = SAMPLE_THREAD;
10028 printf_filtered (_("Remote threadset test\n"));
10029 set_general_thread (sample_thread);
10034 threadalive_test (char *cmd, int tty)
10036 int sample_thread = SAMPLE_THREAD;
10037 int pid = ptid_get_pid (inferior_ptid);
10038 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10040 if (remote_thread_alive (ptid))
10041 printf_filtered ("PASS: Thread alive test\n");
10043 printf_filtered ("FAIL: Thread alive test\n");
10046 void output_threadid (char *title, threadref *ref);
10049 output_threadid (char *title, threadref *ref)
10053 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10055 printf_filtered ("%s %s\n", title, (&hexid[0]));
10059 threadlist_test_cmd (char *cmd, int tty)
10062 threadref nextthread;
10063 int done, result_count;
10064 threadref threadlist[3];
10066 printf_filtered ("Remote Threadlist test\n");
10067 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10068 &result_count, &threadlist[0]))
10069 printf_filtered ("FAIL: threadlist test\n");
10072 threadref *scan = threadlist;
10073 threadref *limit = scan + result_count;
10075 while (scan < limit)
10076 output_threadid (" thread ", scan++);
10081 display_thread_info (struct gdb_ext_thread_info *info)
10083 output_threadid ("Threadid: ", &info->threadid);
10084 printf_filtered ("Name: %s\n ", info->shortname);
10085 printf_filtered ("State: %s\n", info->display);
10086 printf_filtered ("other: %s\n\n", info->more_display);
10090 get_and_display_threadinfo (threadref *ref)
10094 struct gdb_ext_thread_info threadinfo;
10096 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10097 | TAG_MOREDISPLAY | TAG_DISPLAY;
10098 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10099 display_thread_info (&threadinfo);
10104 threadinfo_test_cmd (char *cmd, int tty)
10106 int athread = SAMPLE_THREAD;
10110 int_to_threadref (&thread, athread);
10111 printf_filtered ("Remote Threadinfo test\n");
10112 if (!get_and_display_threadinfo (&thread))
10113 printf_filtered ("FAIL cannot get thread info\n");
10117 thread_display_step (threadref *ref, void *context)
10119 /* output_threadid(" threadstep ",ref); *//* simple test */
10120 return get_and_display_threadinfo (ref);
10124 threadlist_update_test_cmd (char *cmd, int tty)
10126 printf_filtered ("Remote Threadlist update test\n");
10127 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10131 init_remote_threadtests (void)
10133 add_com ("tlist", class_obscure, threadlist_test_cmd,
10134 _("Fetch and print the remote list of "
10135 "thread identifiers, one pkt only"));
10136 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10137 _("Fetch and display info about one thread"));
10138 add_com ("tset", class_obscure, threadset_test_cmd,
10139 _("Test setting to a different thread"));
10140 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10141 _("Iterate through updating all remote thread info"));
10142 add_com ("talive", class_obscure, threadalive_test,
10143 _(" Remote thread alive test "));
10148 /* Convert a thread ID to a string. Returns the string in a static
10152 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10154 static char buf[64];
10155 struct remote_state *rs = get_remote_state ();
10157 if (ptid_equal (ptid, null_ptid))
10158 return normal_pid_to_str (ptid);
10159 else if (ptid_is_pid (ptid))
10161 /* Printing an inferior target id. */
10163 /* When multi-process extensions are off, there's no way in the
10164 remote protocol to know the remote process id, if there's any
10165 at all. There's one exception --- when we're connected with
10166 target extended-remote, and we manually attached to a process
10167 with "attach PID". We don't record anywhere a flag that
10168 allows us to distinguish that case from the case of
10169 connecting with extended-remote and the stub already being
10170 attached to a process, and reporting yes to qAttached, hence
10171 no smart special casing here. */
10172 if (!remote_multi_process_p (rs))
10174 xsnprintf (buf, sizeof buf, "Remote target");
10178 return normal_pid_to_str (ptid);
10182 if (ptid_equal (magic_null_ptid, ptid))
10183 xsnprintf (buf, sizeof buf, "Thread <main>");
10184 else if (rs->extended && remote_multi_process_p (rs))
10185 if (ptid_get_lwp (ptid) == 0)
10186 return normal_pid_to_str (ptid);
10188 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10189 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10191 xsnprintf (buf, sizeof buf, "Thread %ld",
10192 ptid_get_lwp (ptid));
10197 /* Get the address of the thread local variable in OBJFILE which is
10198 stored at OFFSET within the thread local storage for thread PTID. */
10201 remote_get_thread_local_address (struct target_ops *ops,
10202 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10204 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10206 struct remote_state *rs = get_remote_state ();
10208 char *endp = rs->buf + get_remote_packet_size ();
10209 enum packet_result result;
10211 strcpy (p, "qGetTLSAddr:");
10213 p = write_ptid (p, endp, ptid);
10215 p += hexnumstr (p, offset);
10217 p += hexnumstr (p, lm);
10221 getpkt (&rs->buf, &rs->buf_size, 0);
10222 result = packet_ok (rs->buf,
10223 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10224 if (result == PACKET_OK)
10228 unpack_varlen_hex (rs->buf, &result);
10231 else if (result == PACKET_UNKNOWN)
10232 throw_error (TLS_GENERIC_ERROR,
10233 _("Remote target doesn't support qGetTLSAddr packet"));
10235 throw_error (TLS_GENERIC_ERROR,
10236 _("Remote target failed to process qGetTLSAddr request"));
10239 throw_error (TLS_GENERIC_ERROR,
10240 _("TLS not supported or disabled on this target"));
10245 /* Provide thread local base, i.e. Thread Information Block address.
10246 Returns 1 if ptid is found and thread_local_base is non zero. */
10249 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10251 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10253 struct remote_state *rs = get_remote_state ();
10255 char *endp = rs->buf + get_remote_packet_size ();
10256 enum packet_result result;
10258 strcpy (p, "qGetTIBAddr:");
10260 p = write_ptid (p, endp, ptid);
10264 getpkt (&rs->buf, &rs->buf_size, 0);
10265 result = packet_ok (rs->buf,
10266 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10267 if (result == PACKET_OK)
10271 unpack_varlen_hex (rs->buf, &result);
10273 *addr = (CORE_ADDR) result;
10276 else if (result == PACKET_UNKNOWN)
10277 error (_("Remote target doesn't support qGetTIBAddr packet"));
10279 error (_("Remote target failed to process qGetTIBAddr request"));
10282 error (_("qGetTIBAddr not supported or disabled on this target"));
10287 /* Support for inferring a target description based on the current
10288 architecture and the size of a 'g' packet. While the 'g' packet
10289 can have any size (since optional registers can be left off the
10290 end), some sizes are easily recognizable given knowledge of the
10291 approximate architecture. */
10293 struct remote_g_packet_guess
10296 const struct target_desc *tdesc;
10298 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10299 DEF_VEC_O(remote_g_packet_guess_s);
10301 struct remote_g_packet_data
10303 VEC(remote_g_packet_guess_s) *guesses;
10306 static struct gdbarch_data *remote_g_packet_data_handle;
10309 remote_g_packet_data_init (struct obstack *obstack)
10311 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10315 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10316 const struct target_desc *tdesc)
10318 struct remote_g_packet_data *data
10319 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10320 struct remote_g_packet_guess new_guess, *guess;
10323 gdb_assert (tdesc != NULL);
10326 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10328 if (guess->bytes == bytes)
10329 internal_error (__FILE__, __LINE__,
10330 _("Duplicate g packet description added for size %d"),
10333 new_guess.bytes = bytes;
10334 new_guess.tdesc = tdesc;
10335 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10338 /* Return 1 if remote_read_description would do anything on this target
10339 and architecture, 0 otherwise. */
10342 remote_read_description_p (struct target_ops *target)
10344 struct remote_g_packet_data *data
10345 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10347 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10353 static const struct target_desc *
10354 remote_read_description (struct target_ops *target)
10356 struct remote_g_packet_data *data
10357 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10359 /* Do not try this during initial connection, when we do not know
10360 whether there is a running but stopped thread. */
10361 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10362 return target->beneath->to_read_description (target->beneath);
10364 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10366 struct remote_g_packet_guess *guess;
10368 int bytes = send_g_packet ();
10371 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10373 if (guess->bytes == bytes)
10374 return guess->tdesc;
10376 /* We discard the g packet. A minor optimization would be to
10377 hold on to it, and fill the register cache once we have selected
10378 an architecture, but it's too tricky to do safely. */
10381 return target->beneath->to_read_description (target->beneath);
10384 /* Remote file transfer support. This is host-initiated I/O, not
10385 target-initiated; for target-initiated, see remote-fileio.c. */
10387 /* If *LEFT is at least the length of STRING, copy STRING to
10388 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10389 decrease *LEFT. Otherwise raise an error. */
10392 remote_buffer_add_string (char **buffer, int *left, char *string)
10394 int len = strlen (string);
10397 error (_("Packet too long for target."));
10399 memcpy (*buffer, string, len);
10403 /* NUL-terminate the buffer as a convenience, if there is
10409 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10410 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10411 decrease *LEFT. Otherwise raise an error. */
10414 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10417 if (2 * len > *left)
10418 error (_("Packet too long for target."));
10420 bin2hex (bytes, *buffer, len);
10421 *buffer += 2 * len;
10424 /* NUL-terminate the buffer as a convenience, if there is
10430 /* If *LEFT is large enough, convert VALUE to hex and add it to
10431 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10432 decrease *LEFT. Otherwise raise an error. */
10435 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10437 int len = hexnumlen (value);
10440 error (_("Packet too long for target."));
10442 hexnumstr (*buffer, value);
10446 /* NUL-terminate the buffer as a convenience, if there is
10452 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10453 value, *REMOTE_ERRNO to the remote error number or zero if none
10454 was included, and *ATTACHMENT to point to the start of the annex
10455 if any. The length of the packet isn't needed here; there may
10456 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10458 Return 0 if the packet could be parsed, -1 if it could not. If
10459 -1 is returned, the other variables may not be initialized. */
10462 remote_hostio_parse_result (char *buffer, int *retcode,
10463 int *remote_errno, char **attachment)
10468 *attachment = NULL;
10470 if (buffer[0] != 'F')
10474 *retcode = strtol (&buffer[1], &p, 16);
10475 if (errno != 0 || p == &buffer[1])
10478 /* Check for ",errno". */
10482 *remote_errno = strtol (p + 1, &p2, 16);
10483 if (errno != 0 || p + 1 == p2)
10488 /* Check for ";attachment". If there is no attachment, the
10489 packet should end here. */
10492 *attachment = p + 1;
10495 else if (*p == '\0')
10501 /* Send a prepared I/O packet to the target and read its response.
10502 The prepared packet is in the global RS->BUF before this function
10503 is called, and the answer is there when we return.
10505 COMMAND_BYTES is the length of the request to send, which may include
10506 binary data. WHICH_PACKET is the packet configuration to check
10507 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10508 is set to the error number and -1 is returned. Otherwise the value
10509 returned by the function is returned.
10511 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10512 attachment is expected; an error will be reported if there's a
10513 mismatch. If one is found, *ATTACHMENT will be set to point into
10514 the packet buffer and *ATTACHMENT_LEN will be set to the
10515 attachment's length. */
10518 remote_hostio_send_command (int command_bytes, int which_packet,
10519 int *remote_errno, char **attachment,
10520 int *attachment_len)
10522 struct remote_state *rs = get_remote_state ();
10523 int ret, bytes_read;
10524 char *attachment_tmp;
10526 if (!rs->remote_desc
10527 || packet_support (which_packet) == PACKET_DISABLE)
10529 *remote_errno = FILEIO_ENOSYS;
10533 putpkt_binary (rs->buf, command_bytes);
10534 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10536 /* If it timed out, something is wrong. Don't try to parse the
10538 if (bytes_read < 0)
10540 *remote_errno = FILEIO_EINVAL;
10544 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10547 *remote_errno = FILEIO_EINVAL;
10549 case PACKET_UNKNOWN:
10550 *remote_errno = FILEIO_ENOSYS;
10556 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10559 *remote_errno = FILEIO_EINVAL;
10563 /* Make sure we saw an attachment if and only if we expected one. */
10564 if ((attachment_tmp == NULL && attachment != NULL)
10565 || (attachment_tmp != NULL && attachment == NULL))
10567 *remote_errno = FILEIO_EINVAL;
10571 /* If an attachment was found, it must point into the packet buffer;
10572 work out how many bytes there were. */
10573 if (attachment_tmp != NULL)
10575 *attachment = attachment_tmp;
10576 *attachment_len = bytes_read - (*attachment - rs->buf);
10582 /* Invalidate the readahead cache. */
10585 readahead_cache_invalidate (void)
10587 struct remote_state *rs = get_remote_state ();
10589 rs->readahead_cache.fd = -1;
10592 /* Invalidate the readahead cache if it is holding data for FD. */
10595 readahead_cache_invalidate_fd (int fd)
10597 struct remote_state *rs = get_remote_state ();
10599 if (rs->readahead_cache.fd == fd)
10600 rs->readahead_cache.fd = -1;
10603 /* Set the filesystem remote_hostio functions that take FILENAME
10604 arguments will use. Return 0 on success, or -1 if an error
10605 occurs (and set *REMOTE_ERRNO). */
10608 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10610 struct remote_state *rs = get_remote_state ();
10611 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10613 int left = get_remote_packet_size () - 1;
10617 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10620 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10623 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10625 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10626 remote_buffer_add_string (&p, &left, arg);
10628 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10629 remote_errno, NULL, NULL);
10631 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10635 rs->fs_pid = required_pid;
10640 /* Implementation of to_fileio_open. */
10643 remote_hostio_open (struct target_ops *self,
10644 struct inferior *inf, const char *filename,
10645 int flags, int mode, int warn_if_slow,
10648 struct remote_state *rs = get_remote_state ();
10650 int left = get_remote_packet_size () - 1;
10654 static int warning_issued = 0;
10656 printf_unfiltered (_("Reading %s from remote target...\n"),
10659 if (!warning_issued)
10661 warning (_("File transfers from remote targets can be slow."
10662 " Use \"set sysroot\" to access files locally"
10664 warning_issued = 1;
10668 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10671 remote_buffer_add_string (&p, &left, "vFile:open:");
10673 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10674 strlen (filename));
10675 remote_buffer_add_string (&p, &left, ",");
10677 remote_buffer_add_int (&p, &left, flags);
10678 remote_buffer_add_string (&p, &left, ",");
10680 remote_buffer_add_int (&p, &left, mode);
10682 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10683 remote_errno, NULL, NULL);
10686 /* Implementation of to_fileio_pwrite. */
10689 remote_hostio_pwrite (struct target_ops *self,
10690 int fd, const gdb_byte *write_buf, int len,
10691 ULONGEST offset, int *remote_errno)
10693 struct remote_state *rs = get_remote_state ();
10695 int left = get_remote_packet_size ();
10698 readahead_cache_invalidate_fd (fd);
10700 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10702 remote_buffer_add_int (&p, &left, fd);
10703 remote_buffer_add_string (&p, &left, ",");
10705 remote_buffer_add_int (&p, &left, offset);
10706 remote_buffer_add_string (&p, &left, ",");
10708 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10709 get_remote_packet_size () - (p - rs->buf));
10711 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10712 remote_errno, NULL, NULL);
10715 /* Helper for the implementation of to_fileio_pread. Read the file
10716 from the remote side with vFile:pread. */
10719 remote_hostio_pread_vFile (struct target_ops *self,
10720 int fd, gdb_byte *read_buf, int len,
10721 ULONGEST offset, int *remote_errno)
10723 struct remote_state *rs = get_remote_state ();
10726 int left = get_remote_packet_size ();
10727 int ret, attachment_len;
10730 remote_buffer_add_string (&p, &left, "vFile:pread:");
10732 remote_buffer_add_int (&p, &left, fd);
10733 remote_buffer_add_string (&p, &left, ",");
10735 remote_buffer_add_int (&p, &left, len);
10736 remote_buffer_add_string (&p, &left, ",");
10738 remote_buffer_add_int (&p, &left, offset);
10740 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10741 remote_errno, &attachment,
10747 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10749 if (read_len != ret)
10750 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10755 /* Serve pread from the readahead cache. Returns number of bytes
10756 read, or 0 if the request can't be served from the cache. */
10759 remote_hostio_pread_from_cache (struct remote_state *rs,
10760 int fd, gdb_byte *read_buf, size_t len,
10763 struct readahead_cache *cache = &rs->readahead_cache;
10765 if (cache->fd == fd
10766 && cache->offset <= offset
10767 && offset < cache->offset + cache->bufsize)
10769 ULONGEST max = cache->offset + cache->bufsize;
10771 if (offset + len > max)
10772 len = max - offset;
10774 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10781 /* Implementation of to_fileio_pread. */
10784 remote_hostio_pread (struct target_ops *self,
10785 int fd, gdb_byte *read_buf, int len,
10786 ULONGEST offset, int *remote_errno)
10789 struct remote_state *rs = get_remote_state ();
10790 struct readahead_cache *cache = &rs->readahead_cache;
10792 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10795 cache->hit_count++;
10798 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10799 pulongest (cache->hit_count));
10803 cache->miss_count++;
10805 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10806 pulongest (cache->miss_count));
10809 cache->offset = offset;
10810 cache->bufsize = get_remote_packet_size ();
10811 cache->buf = xrealloc (cache->buf, cache->bufsize);
10813 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10814 cache->offset, remote_errno);
10817 readahead_cache_invalidate_fd (fd);
10821 cache->bufsize = ret;
10822 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10825 /* Implementation of to_fileio_close. */
10828 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
10830 struct remote_state *rs = get_remote_state ();
10832 int left = get_remote_packet_size () - 1;
10834 readahead_cache_invalidate_fd (fd);
10836 remote_buffer_add_string (&p, &left, "vFile:close:");
10838 remote_buffer_add_int (&p, &left, fd);
10840 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10841 remote_errno, NULL, NULL);
10844 /* Implementation of to_fileio_unlink. */
10847 remote_hostio_unlink (struct target_ops *self,
10848 struct inferior *inf, const char *filename,
10851 struct remote_state *rs = get_remote_state ();
10853 int left = get_remote_packet_size () - 1;
10855 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10858 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10860 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10861 strlen (filename));
10863 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10864 remote_errno, NULL, NULL);
10867 /* Implementation of to_fileio_readlink. */
10870 remote_hostio_readlink (struct target_ops *self,
10871 struct inferior *inf, const char *filename,
10874 struct remote_state *rs = get_remote_state ();
10877 int left = get_remote_packet_size ();
10878 int len, attachment_len;
10882 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10885 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10887 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10888 strlen (filename));
10890 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10891 remote_errno, &attachment,
10897 ret = xmalloc (len + 1);
10899 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10900 (gdb_byte *) ret, len);
10901 if (read_len != len)
10902 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10908 /* Implementation of to_fileio_fstat. */
10911 remote_hostio_fstat (struct target_ops *self,
10912 int fd, struct stat *st,
10915 struct remote_state *rs = get_remote_state ();
10917 int left = get_remote_packet_size ();
10918 int attachment_len, ret;
10920 struct fio_stat fst;
10923 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10925 remote_buffer_add_int (&p, &left, fd);
10927 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10928 remote_errno, &attachment,
10932 if (*remote_errno != FILEIO_ENOSYS)
10935 /* Strictly we should return -1, ENOSYS here, but when
10936 "set sysroot remote:" was implemented in August 2008
10937 BFD's need for a stat function was sidestepped with
10938 this hack. This was not remedied until March 2015
10939 so we retain the previous behavior to avoid breaking
10942 Note that the memset is a March 2015 addition; older
10943 GDBs set st_size *and nothing else* so the structure
10944 would have garbage in all other fields. This might
10945 break something but retaining the previous behavior
10946 here would be just too wrong. */
10948 memset (st, 0, sizeof (struct stat));
10949 st->st_size = INT_MAX;
10953 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10954 (gdb_byte *) &fst, sizeof (fst));
10956 if (read_len != ret)
10957 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10959 if (read_len != sizeof (fst))
10960 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10961 read_len, (int) sizeof (fst));
10963 remote_fileio_to_host_stat (&fst, st);
10968 /* Implementation of to_filesystem_is_local. */
10971 remote_filesystem_is_local (struct target_ops *self)
10973 /* Valgrind GDB presents itself as a remote target but works
10974 on the local filesystem: it does not implement remote get
10975 and users are not expected to set a sysroot. To handle
10976 this case we treat the remote filesystem as local if the
10977 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10978 does not support vFile:open. */
10979 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
10981 enum packet_support ps = packet_support (PACKET_vFile_open);
10983 if (ps == PACKET_SUPPORT_UNKNOWN)
10985 int fd, remote_errno;
10987 /* Try opening a file to probe support. The supplied
10988 filename is irrelevant, we only care about whether
10989 the stub recognizes the packet or not. */
10990 fd = remote_hostio_open (self, NULL, "just probing",
10991 FILEIO_O_RDONLY, 0700, 0,
10995 remote_hostio_close (self, fd, &remote_errno);
10997 ps = packet_support (PACKET_vFile_open);
11000 if (ps == PACKET_DISABLE)
11002 static int warning_issued = 0;
11004 if (!warning_issued)
11006 warning (_("remote target does not support file"
11007 " transfer, attempting to access files"
11008 " from local filesystem."));
11009 warning_issued = 1;
11020 remote_fileio_errno_to_host (int errnum)
11026 case FILEIO_ENOENT:
11034 case FILEIO_EACCES:
11036 case FILEIO_EFAULT:
11040 case FILEIO_EEXIST:
11042 case FILEIO_ENODEV:
11044 case FILEIO_ENOTDIR:
11046 case FILEIO_EISDIR:
11048 case FILEIO_EINVAL:
11050 case FILEIO_ENFILE:
11052 case FILEIO_EMFILE:
11056 case FILEIO_ENOSPC:
11058 case FILEIO_ESPIPE:
11062 case FILEIO_ENOSYS:
11064 case FILEIO_ENAMETOOLONG:
11065 return ENAMETOOLONG;
11071 remote_hostio_error (int errnum)
11073 int host_error = remote_fileio_errno_to_host (errnum);
11075 if (host_error == -1)
11076 error (_("Unknown remote I/O error %d"), errnum);
11078 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11082 remote_hostio_close_cleanup (void *opaque)
11084 int fd = *(int *) opaque;
11087 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11091 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11093 struct cleanup *back_to, *close_cleanup;
11094 int retcode, fd, remote_errno, bytes, io_size;
11097 int bytes_in_buffer;
11100 struct remote_state *rs = get_remote_state ();
11102 if (!rs->remote_desc)
11103 error (_("command can only be used with remote target"));
11105 file = gdb_fopen_cloexec (local_file, "rb");
11107 perror_with_name (local_file);
11108 back_to = make_cleanup_fclose (file);
11110 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11111 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11113 0700, 0, &remote_errno);
11115 remote_hostio_error (remote_errno);
11117 /* Send up to this many bytes at once. They won't all fit in the
11118 remote packet limit, so we'll transfer slightly fewer. */
11119 io_size = get_remote_packet_size ();
11120 buffer = xmalloc (io_size);
11121 make_cleanup (xfree, buffer);
11123 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11125 bytes_in_buffer = 0;
11128 while (bytes_in_buffer || !saw_eof)
11132 bytes = fread (buffer + bytes_in_buffer, 1,
11133 io_size - bytes_in_buffer,
11138 error (_("Error reading %s."), local_file);
11141 /* EOF. Unless there is something still in the
11142 buffer from the last iteration, we are done. */
11144 if (bytes_in_buffer == 0)
11152 bytes += bytes_in_buffer;
11153 bytes_in_buffer = 0;
11155 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11157 offset, &remote_errno);
11160 remote_hostio_error (remote_errno);
11161 else if (retcode == 0)
11162 error (_("Remote write of %d bytes returned 0!"), bytes);
11163 else if (retcode < bytes)
11165 /* Short write. Save the rest of the read data for the next
11167 bytes_in_buffer = bytes - retcode;
11168 memmove (buffer, buffer + retcode, bytes_in_buffer);
11174 discard_cleanups (close_cleanup);
11175 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11176 remote_hostio_error (remote_errno);
11179 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11180 do_cleanups (back_to);
11184 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11186 struct cleanup *back_to, *close_cleanup;
11187 int fd, remote_errno, bytes, io_size;
11191 struct remote_state *rs = get_remote_state ();
11193 if (!rs->remote_desc)
11194 error (_("command can only be used with remote target"));
11196 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11197 remote_file, FILEIO_O_RDONLY, 0, 0,
11200 remote_hostio_error (remote_errno);
11202 file = gdb_fopen_cloexec (local_file, "wb");
11204 perror_with_name (local_file);
11205 back_to = make_cleanup_fclose (file);
11207 /* Send up to this many bytes at once. They won't all fit in the
11208 remote packet limit, so we'll transfer slightly fewer. */
11209 io_size = get_remote_packet_size ();
11210 buffer = xmalloc (io_size);
11211 make_cleanup (xfree, buffer);
11213 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11218 bytes = remote_hostio_pread (find_target_at (process_stratum),
11219 fd, buffer, io_size, offset, &remote_errno);
11221 /* Success, but no bytes, means end-of-file. */
11224 remote_hostio_error (remote_errno);
11228 bytes = fwrite (buffer, 1, bytes, file);
11230 perror_with_name (local_file);
11233 discard_cleanups (close_cleanup);
11234 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11235 remote_hostio_error (remote_errno);
11238 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11239 do_cleanups (back_to);
11243 remote_file_delete (const char *remote_file, int from_tty)
11245 int retcode, remote_errno;
11246 struct remote_state *rs = get_remote_state ();
11248 if (!rs->remote_desc)
11249 error (_("command can only be used with remote target"));
11251 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11252 NULL, remote_file, &remote_errno);
11254 remote_hostio_error (remote_errno);
11257 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11261 remote_put_command (char *args, int from_tty)
11263 struct cleanup *back_to;
11267 error_no_arg (_("file to put"));
11269 argv = gdb_buildargv (args);
11270 back_to = make_cleanup_freeargv (argv);
11271 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11272 error (_("Invalid parameters to remote put"));
11274 remote_file_put (argv[0], argv[1], from_tty);
11276 do_cleanups (back_to);
11280 remote_get_command (char *args, int from_tty)
11282 struct cleanup *back_to;
11286 error_no_arg (_("file to get"));
11288 argv = gdb_buildargv (args);
11289 back_to = make_cleanup_freeargv (argv);
11290 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11291 error (_("Invalid parameters to remote get"));
11293 remote_file_get (argv[0], argv[1], from_tty);
11295 do_cleanups (back_to);
11299 remote_delete_command (char *args, int from_tty)
11301 struct cleanup *back_to;
11305 error_no_arg (_("file to delete"));
11307 argv = gdb_buildargv (args);
11308 back_to = make_cleanup_freeargv (argv);
11309 if (argv[0] == NULL || argv[1] != NULL)
11310 error (_("Invalid parameters to remote delete"));
11312 remote_file_delete (argv[0], from_tty);
11314 do_cleanups (back_to);
11318 remote_command (char *args, int from_tty)
11320 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11324 remote_can_execute_reverse (struct target_ops *self)
11326 if (packet_support (PACKET_bs) == PACKET_ENABLE
11327 || packet_support (PACKET_bc) == PACKET_ENABLE)
11334 remote_supports_non_stop (struct target_ops *self)
11340 remote_supports_disable_randomization (struct target_ops *self)
11342 /* Only supported in extended mode. */
11347 remote_supports_multi_process (struct target_ops *self)
11349 struct remote_state *rs = get_remote_state ();
11351 /* Only extended-remote handles being attached to multiple
11352 processes, even though plain remote can use the multi-process
11353 thread id extensions, so that GDB knows the target process's
11355 return rs->extended && remote_multi_process_p (rs);
11359 remote_supports_cond_tracepoints (void)
11361 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11365 remote_supports_cond_breakpoints (struct target_ops *self)
11367 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11371 remote_supports_fast_tracepoints (void)
11373 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11377 remote_supports_static_tracepoints (void)
11379 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11383 remote_supports_install_in_trace (void)
11385 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11389 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11391 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11396 remote_supports_string_tracing (struct target_ops *self)
11398 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11402 remote_can_run_breakpoint_commands (struct target_ops *self)
11404 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11408 remote_trace_init (struct target_ops *self)
11411 remote_get_noisy_reply (&target_buf, &target_buf_size);
11412 if (strcmp (target_buf, "OK") != 0)
11413 error (_("Target does not support this command."));
11416 static void free_actions_list (char **actions_list);
11417 static void free_actions_list_cleanup_wrapper (void *);
11419 free_actions_list_cleanup_wrapper (void *al)
11421 free_actions_list (al);
11425 free_actions_list (char **actions_list)
11429 if (actions_list == 0)
11432 for (ndx = 0; actions_list[ndx]; ndx++)
11433 xfree (actions_list[ndx]);
11435 xfree (actions_list);
11438 /* Recursive routine to walk through command list including loops, and
11439 download packets for each command. */
11442 remote_download_command_source (int num, ULONGEST addr,
11443 struct command_line *cmds)
11445 struct remote_state *rs = get_remote_state ();
11446 struct command_line *cmd;
11448 for (cmd = cmds; cmd; cmd = cmd->next)
11450 QUIT; /* Allow user to bail out with ^C. */
11451 strcpy (rs->buf, "QTDPsrc:");
11452 encode_source_string (num, addr, "cmd", cmd->line,
11453 rs->buf + strlen (rs->buf),
11454 rs->buf_size - strlen (rs->buf));
11456 remote_get_noisy_reply (&target_buf, &target_buf_size);
11457 if (strcmp (target_buf, "OK"))
11458 warning (_("Target does not support source download."));
11460 if (cmd->control_type == while_control
11461 || cmd->control_type == while_stepping_control)
11463 remote_download_command_source (num, addr, *cmd->body_list);
11465 QUIT; /* Allow user to bail out with ^C. */
11466 strcpy (rs->buf, "QTDPsrc:");
11467 encode_source_string (num, addr, "cmd", "end",
11468 rs->buf + strlen (rs->buf),
11469 rs->buf_size - strlen (rs->buf));
11471 remote_get_noisy_reply (&target_buf, &target_buf_size);
11472 if (strcmp (target_buf, "OK"))
11473 warning (_("Target does not support source download."));
11479 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11481 #define BUF_SIZE 2048
11485 char buf[BUF_SIZE];
11486 char **tdp_actions;
11487 char **stepping_actions;
11489 struct cleanup *old_chain = NULL;
11490 struct agent_expr *aexpr;
11491 struct cleanup *aexpr_chain = NULL;
11493 struct breakpoint *b = loc->owner;
11494 struct tracepoint *t = (struct tracepoint *) b;
11496 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11497 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11499 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11502 tpaddr = loc->address;
11503 sprintf_vma (addrbuf, tpaddr);
11504 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11505 addrbuf, /* address */
11506 (b->enable_state == bp_enabled ? 'E' : 'D'),
11507 t->step_count, t->pass_count);
11508 /* Fast tracepoints are mostly handled by the target, but we can
11509 tell the target how big of an instruction block should be moved
11511 if (b->type == bp_fast_tracepoint)
11513 /* Only test for support at download time; we may not know
11514 target capabilities at definition time. */
11515 if (remote_supports_fast_tracepoints ())
11517 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11519 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11520 gdb_insn_length (loc->gdbarch, tpaddr));
11522 /* If it passed validation at definition but fails now,
11523 something is very wrong. */
11524 internal_error (__FILE__, __LINE__,
11525 _("Fast tracepoint not "
11526 "valid during download"));
11529 /* Fast tracepoints are functionally identical to regular
11530 tracepoints, so don't take lack of support as a reason to
11531 give up on the trace run. */
11532 warning (_("Target does not support fast tracepoints, "
11533 "downloading %d as regular tracepoint"), b->number);
11535 else if (b->type == bp_static_tracepoint)
11537 /* Only test for support at download time; we may not know
11538 target capabilities at definition time. */
11539 if (remote_supports_static_tracepoints ())
11541 struct static_tracepoint_marker marker;
11543 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11544 strcat (buf, ":S");
11546 error (_("Static tracepoint not valid during download"));
11549 /* Fast tracepoints are functionally identical to regular
11550 tracepoints, so don't take lack of support as a reason
11551 to give up on the trace run. */
11552 error (_("Target does not support static tracepoints"));
11554 /* If the tracepoint has a conditional, make it into an agent
11555 expression and append to the definition. */
11558 /* Only test support at download time, we may not know target
11559 capabilities at definition time. */
11560 if (remote_supports_cond_tracepoints ())
11562 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11563 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11564 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11566 pkt = buf + strlen (buf);
11567 for (ndx = 0; ndx < aexpr->len; ++ndx)
11568 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11570 do_cleanups (aexpr_chain);
11573 warning (_("Target does not support conditional tracepoints, "
11574 "ignoring tp %d cond"), b->number);
11577 if (b->commands || *default_collect)
11580 remote_get_noisy_reply (&target_buf, &target_buf_size);
11581 if (strcmp (target_buf, "OK"))
11582 error (_("Target does not support tracepoints."));
11584 /* do_single_steps (t); */
11587 for (ndx = 0; tdp_actions[ndx]; ndx++)
11589 QUIT; /* Allow user to bail out with ^C. */
11590 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11591 b->number, addrbuf, /* address */
11593 ((tdp_actions[ndx + 1] || stepping_actions)
11596 remote_get_noisy_reply (&target_buf,
11598 if (strcmp (target_buf, "OK"))
11599 error (_("Error on target while setting tracepoints."));
11602 if (stepping_actions)
11604 for (ndx = 0; stepping_actions[ndx]; ndx++)
11606 QUIT; /* Allow user to bail out with ^C. */
11607 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11608 b->number, addrbuf, /* address */
11609 ((ndx == 0) ? "S" : ""),
11610 stepping_actions[ndx],
11611 (stepping_actions[ndx + 1] ? "-" : ""));
11613 remote_get_noisy_reply (&target_buf,
11615 if (strcmp (target_buf, "OK"))
11616 error (_("Error on target while setting tracepoints."));
11620 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11622 if (b->location != NULL)
11624 strcpy (buf, "QTDPsrc:");
11625 encode_source_string (b->number, loc->address, "at",
11626 event_location_to_string (b->location),
11627 buf + strlen (buf), 2048 - strlen (buf));
11629 remote_get_noisy_reply (&target_buf, &target_buf_size);
11630 if (strcmp (target_buf, "OK"))
11631 warning (_("Target does not support source download."));
11633 if (b->cond_string)
11635 strcpy (buf, "QTDPsrc:");
11636 encode_source_string (b->number, loc->address,
11637 "cond", b->cond_string, buf + strlen (buf),
11638 2048 - strlen (buf));
11640 remote_get_noisy_reply (&target_buf, &target_buf_size);
11641 if (strcmp (target_buf, "OK"))
11642 warning (_("Target does not support source download."));
11644 remote_download_command_source (b->number, loc->address,
11645 breakpoint_commands (b));
11648 do_cleanups (old_chain);
11652 remote_can_download_tracepoint (struct target_ops *self)
11654 struct remote_state *rs = get_remote_state ();
11655 struct trace_status *ts;
11658 /* Don't try to install tracepoints until we've relocated our
11659 symbols, and fetched and merged the target's tracepoint list with
11661 if (rs->starting_up)
11664 ts = current_trace_status ();
11665 status = remote_get_trace_status (self, ts);
11667 if (status == -1 || !ts->running_known || !ts->running)
11670 /* If we are in a tracing experiment, but remote stub doesn't support
11671 installing tracepoint in trace, we have to return. */
11672 if (!remote_supports_install_in_trace ())
11680 remote_download_trace_state_variable (struct target_ops *self,
11681 struct trace_state_variable *tsv)
11683 struct remote_state *rs = get_remote_state ();
11686 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11687 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11689 p = rs->buf + strlen (rs->buf);
11690 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11691 error (_("Trace state variable name too long for tsv definition packet"));
11692 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11695 remote_get_noisy_reply (&target_buf, &target_buf_size);
11696 if (*target_buf == '\0')
11697 error (_("Target does not support this command."));
11698 if (strcmp (target_buf, "OK") != 0)
11699 error (_("Error on target while downloading trace state variable."));
11703 remote_enable_tracepoint (struct target_ops *self,
11704 struct bp_location *location)
11706 struct remote_state *rs = get_remote_state ();
11709 sprintf_vma (addr_buf, location->address);
11710 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11711 location->owner->number, addr_buf);
11713 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11714 if (*rs->buf == '\0')
11715 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11716 if (strcmp (rs->buf, "OK") != 0)
11717 error (_("Error on target while enabling tracepoint."));
11721 remote_disable_tracepoint (struct target_ops *self,
11722 struct bp_location *location)
11724 struct remote_state *rs = get_remote_state ();
11727 sprintf_vma (addr_buf, location->address);
11728 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11729 location->owner->number, addr_buf);
11731 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11732 if (*rs->buf == '\0')
11733 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11734 if (strcmp (rs->buf, "OK") != 0)
11735 error (_("Error on target while disabling tracepoint."));
11739 remote_trace_set_readonly_regions (struct target_ops *self)
11743 bfd_size_type size;
11749 return; /* No information to give. */
11751 strcpy (target_buf, "QTro");
11752 offset = strlen (target_buf);
11753 for (s = exec_bfd->sections; s; s = s->next)
11755 char tmp1[40], tmp2[40];
11758 if ((s->flags & SEC_LOAD) == 0 ||
11759 /* (s->flags & SEC_CODE) == 0 || */
11760 (s->flags & SEC_READONLY) == 0)
11764 vma = bfd_get_section_vma (abfd, s);
11765 size = bfd_get_section_size (s);
11766 sprintf_vma (tmp1, vma);
11767 sprintf_vma (tmp2, vma + size);
11768 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11769 if (offset + sec_length + 1 > target_buf_size)
11771 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
11773 Too many sections for read-only sections definition packet."));
11776 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11778 offset += sec_length;
11782 putpkt (target_buf);
11783 getpkt (&target_buf, &target_buf_size, 0);
11788 remote_trace_start (struct target_ops *self)
11790 putpkt ("QTStart");
11791 remote_get_noisy_reply (&target_buf, &target_buf_size);
11792 if (*target_buf == '\0')
11793 error (_("Target does not support this command."));
11794 if (strcmp (target_buf, "OK") != 0)
11795 error (_("Bogus reply from target: %s"), target_buf);
11799 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11801 /* Initialize it just to avoid a GCC false warning. */
11803 /* FIXME we need to get register block size some other way. */
11804 extern int trace_regblock_size;
11805 enum packet_result result;
11807 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11810 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11812 putpkt ("qTStatus");
11816 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11818 CATCH (ex, RETURN_MASK_ERROR)
11820 if (ex.error != TARGET_CLOSE_ERROR)
11822 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11825 throw_exception (ex);
11829 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11831 /* If the remote target doesn't do tracing, flag it. */
11832 if (result == PACKET_UNKNOWN)
11835 /* We're working with a live target. */
11836 ts->filename = NULL;
11839 error (_("Bogus trace status reply from target: %s"), target_buf);
11841 /* Function 'parse_trace_status' sets default value of each field of
11842 'ts' at first, so we don't have to do it here. */
11843 parse_trace_status (p, ts);
11845 return ts->running;
11849 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
11850 struct uploaded_tp *utp)
11852 struct remote_state *rs = get_remote_state ();
11854 struct bp_location *loc;
11855 struct tracepoint *tp = (struct tracepoint *) bp;
11856 size_t size = get_remote_packet_size ();
11860 tp->base.hit_count = 0;
11861 tp->traceframe_usage = 0;
11862 for (loc = tp->base.loc; loc; loc = loc->next)
11864 /* If the tracepoint was never downloaded, don't go asking for
11866 if (tp->number_on_target == 0)
11868 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11869 phex_nz (loc->address, 0));
11871 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11872 if (reply && *reply)
11875 parse_tracepoint_status (reply + 1, bp, utp);
11881 utp->hit_count = 0;
11882 utp->traceframe_usage = 0;
11883 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11884 phex_nz (utp->addr, 0));
11886 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11887 if (reply && *reply)
11890 parse_tracepoint_status (reply + 1, bp, utp);
11896 remote_trace_stop (struct target_ops *self)
11899 remote_get_noisy_reply (&target_buf, &target_buf_size);
11900 if (*target_buf == '\0')
11901 error (_("Target does not support this command."));
11902 if (strcmp (target_buf, "OK") != 0)
11903 error (_("Bogus reply from target: %s"), target_buf);
11907 remote_trace_find (struct target_ops *self,
11908 enum trace_find_type type, int num,
11909 CORE_ADDR addr1, CORE_ADDR addr2,
11912 struct remote_state *rs = get_remote_state ();
11913 char *endbuf = rs->buf + get_remote_packet_size ();
11915 int target_frameno = -1, target_tracept = -1;
11917 /* Lookups other than by absolute frame number depend on the current
11918 trace selected, so make sure it is correct on the remote end
11920 if (type != tfind_number)
11921 set_remote_traceframe ();
11924 strcpy (p, "QTFrame:");
11925 p = strchr (p, '\0');
11929 xsnprintf (p, endbuf - p, "%x", num);
11932 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11935 xsnprintf (p, endbuf - p, "tdp:%x", num);
11938 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11939 phex_nz (addr2, 0));
11941 case tfind_outside:
11942 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11943 phex_nz (addr2, 0));
11946 error (_("Unknown trace find type %d"), type);
11950 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11951 if (*reply == '\0')
11952 error (_("Target does not support this command."));
11954 while (reply && *reply)
11959 target_frameno = (int) strtol (p, &reply, 16);
11961 error (_("Unable to parse trace frame number"));
11962 /* Don't update our remote traceframe number cache on failure
11963 to select a remote traceframe. */
11964 if (target_frameno == -1)
11969 target_tracept = (int) strtol (p, &reply, 16);
11971 error (_("Unable to parse tracepoint number"));
11973 case 'O': /* "OK"? */
11974 if (reply[1] == 'K' && reply[2] == '\0')
11977 error (_("Bogus reply from target: %s"), reply);
11980 error (_("Bogus reply from target: %s"), reply);
11983 *tpp = target_tracept;
11985 rs->remote_traceframe_number = target_frameno;
11986 return target_frameno;
11990 remote_get_trace_state_variable_value (struct target_ops *self,
11991 int tsvnum, LONGEST *val)
11993 struct remote_state *rs = get_remote_state ();
11997 set_remote_traceframe ();
11999 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12001 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12002 if (reply && *reply)
12006 unpack_varlen_hex (reply + 1, &uval);
12007 *val = (LONGEST) uval;
12015 remote_save_trace_data (struct target_ops *self, const char *filename)
12017 struct remote_state *rs = get_remote_state ();
12021 strcpy (p, "QTSave:");
12023 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12024 error (_("Remote file name too long for trace save packet"));
12025 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12028 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12029 if (*reply == '\0')
12030 error (_("Target does not support this command."));
12031 if (strcmp (reply, "OK") != 0)
12032 error (_("Bogus reply from target: %s"), reply);
12036 /* This is basically a memory transfer, but needs to be its own packet
12037 because we don't know how the target actually organizes its trace
12038 memory, plus we want to be able to ask for as much as possible, but
12039 not be unhappy if we don't get as much as we ask for. */
12042 remote_get_raw_trace_data (struct target_ops *self,
12043 gdb_byte *buf, ULONGEST offset, LONGEST len)
12045 struct remote_state *rs = get_remote_state ();
12051 strcpy (p, "qTBuffer:");
12053 p += hexnumstr (p, offset);
12055 p += hexnumstr (p, len);
12059 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12060 if (reply && *reply)
12062 /* 'l' by itself means we're at the end of the buffer and
12063 there is nothing more to get. */
12067 /* Convert the reply into binary. Limit the number of bytes to
12068 convert according to our passed-in buffer size, rather than
12069 what was returned in the packet; if the target is
12070 unexpectedly generous and gives us a bigger reply than we
12071 asked for, we don't want to crash. */
12072 rslt = hex2bin (target_buf, buf, len);
12076 /* Something went wrong, flag as an error. */
12081 remote_set_disconnected_tracing (struct target_ops *self, int val)
12083 struct remote_state *rs = get_remote_state ();
12085 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12089 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12091 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12092 if (*reply == '\0')
12093 error (_("Target does not support this command."));
12094 if (strcmp (reply, "OK") != 0)
12095 error (_("Bogus reply from target: %s"), reply);
12098 warning (_("Target does not support disconnected tracing."));
12102 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12104 struct thread_info *info = find_thread_ptid (ptid);
12106 if (info && info->priv)
12107 return info->priv->core;
12112 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12114 struct remote_state *rs = get_remote_state ();
12117 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%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 static struct traceframe_info *
12127 remote_traceframe_info (struct target_ops *self)
12131 text = target_read_stralloc (¤t_target,
12132 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12135 struct traceframe_info *info;
12136 struct cleanup *back_to = make_cleanup (xfree, text);
12138 info = parse_traceframe_info (text);
12139 do_cleanups (back_to);
12146 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12147 instruction on which a fast tracepoint may be placed. Returns -1
12148 if the packet is not supported, and 0 if the minimum instruction
12149 length is unknown. */
12152 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12154 struct remote_state *rs = get_remote_state ();
12157 /* If we're not debugging a process yet, the IPA can't be
12159 if (!target_has_execution)
12162 /* Make sure the remote is pointing at the right process. */
12163 set_general_process ();
12165 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12167 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12168 if (*reply == '\0')
12172 ULONGEST min_insn_len;
12174 unpack_varlen_hex (reply, &min_insn_len);
12176 return (int) min_insn_len;
12181 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12183 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12185 struct remote_state *rs = get_remote_state ();
12186 char *buf = rs->buf;
12187 char *endbuf = rs->buf + get_remote_packet_size ();
12188 enum packet_result result;
12190 gdb_assert (val >= 0 || val == -1);
12191 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12192 /* Send -1 as literal "-1" to avoid host size dependency. */
12196 buf += hexnumstr (buf, (ULONGEST) -val);
12199 buf += hexnumstr (buf, (ULONGEST) val);
12202 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12203 result = packet_ok (rs->buf,
12204 &remote_protocol_packets[PACKET_QTBuffer_size]);
12206 if (result != PACKET_OK)
12207 warning (_("Bogus reply from target: %s"), rs->buf);
12212 remote_set_trace_notes (struct target_ops *self,
12213 const char *user, const char *notes,
12214 const char *stop_notes)
12216 struct remote_state *rs = get_remote_state ();
12218 char *buf = rs->buf;
12219 char *endbuf = rs->buf + get_remote_packet_size ();
12222 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12225 buf += xsnprintf (buf, endbuf - buf, "user:");
12226 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12232 buf += xsnprintf (buf, endbuf - buf, "notes:");
12233 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12239 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12240 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12244 /* Ensure the buffer is terminated. */
12248 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12249 if (*reply == '\0')
12252 if (strcmp (reply, "OK") != 0)
12253 error (_("Bogus reply from target: %s"), reply);
12259 remote_use_agent (struct target_ops *self, int use)
12261 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12263 struct remote_state *rs = get_remote_state ();
12265 /* If the stub supports QAgent. */
12266 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12268 getpkt (&rs->buf, &rs->buf_size, 0);
12270 if (strcmp (rs->buf, "OK") == 0)
12281 remote_can_use_agent (struct target_ops *self)
12283 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12286 struct btrace_target_info
12288 /* The ptid of the traced thread. */
12291 /* The obtained branch trace configuration. */
12292 struct btrace_config conf;
12295 /* Reset our idea of our target's btrace configuration. */
12298 remote_btrace_reset (void)
12300 struct remote_state *rs = get_remote_state ();
12302 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12305 /* Check whether the target supports branch tracing. */
12308 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12310 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12312 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12317 case BTRACE_FORMAT_NONE:
12320 case BTRACE_FORMAT_BTS:
12321 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12323 case BTRACE_FORMAT_PT:
12324 /* The trace is decoded on the host. Even if our target supports it,
12325 we still need to have libipt to decode the trace. */
12326 #if defined (HAVE_LIBIPT)
12327 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12328 #else /* !defined (HAVE_LIBIPT) */
12330 #endif /* !defined (HAVE_LIBIPT) */
12333 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12336 /* Synchronize the configuration with the target. */
12339 btrace_sync_conf (const struct btrace_config *conf)
12341 struct packet_config *packet;
12342 struct remote_state *rs;
12343 char *buf, *pos, *endbuf;
12345 rs = get_remote_state ();
12347 endbuf = buf + get_remote_packet_size ();
12349 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12350 if (packet_config_support (packet) == PACKET_ENABLE
12351 && conf->bts.size != rs->btrace_config.bts.size)
12354 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12358 getpkt (&buf, &rs->buf_size, 0);
12360 if (packet_ok (buf, packet) == PACKET_ERROR)
12362 if (buf[0] == 'E' && buf[1] == '.')
12363 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12365 error (_("Failed to configure the BTS buffer size."));
12368 rs->btrace_config.bts.size = conf->bts.size;
12371 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12372 if (packet_config_support (packet) == PACKET_ENABLE
12373 && conf->pt.size != rs->btrace_config.pt.size)
12376 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12380 getpkt (&buf, &rs->buf_size, 0);
12382 if (packet_ok (buf, packet) == PACKET_ERROR)
12384 if (buf[0] == 'E' && buf[1] == '.')
12385 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12387 error (_("Failed to configure the trace buffer size."));
12390 rs->btrace_config.pt.size = conf->pt.size;
12394 /* Read the current thread's btrace configuration from the target and
12395 store it into CONF. */
12398 btrace_read_config (struct btrace_config *conf)
12402 xml = target_read_stralloc (¤t_target,
12403 TARGET_OBJECT_BTRACE_CONF, "");
12406 struct cleanup *cleanup;
12408 cleanup = make_cleanup (xfree, xml);
12409 parse_xml_btrace_conf (conf, xml);
12410 do_cleanups (cleanup);
12414 /* Enable branch tracing. */
12416 static struct btrace_target_info *
12417 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12418 const struct btrace_config *conf)
12420 struct btrace_target_info *tinfo = NULL;
12421 struct packet_config *packet = NULL;
12422 struct remote_state *rs = get_remote_state ();
12423 char *buf = rs->buf;
12424 char *endbuf = rs->buf + get_remote_packet_size ();
12426 switch (conf->format)
12428 case BTRACE_FORMAT_BTS:
12429 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12432 case BTRACE_FORMAT_PT:
12433 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12437 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12438 error (_("Target does not support branch tracing."));
12440 btrace_sync_conf (conf);
12442 set_general_thread (ptid);
12444 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12446 getpkt (&rs->buf, &rs->buf_size, 0);
12448 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12450 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12451 error (_("Could not enable branch tracing for %s: %s"),
12452 target_pid_to_str (ptid), rs->buf + 2);
12454 error (_("Could not enable branch tracing for %s."),
12455 target_pid_to_str (ptid));
12458 tinfo = XCNEW (struct btrace_target_info);
12459 tinfo->ptid = ptid;
12461 /* If we fail to read the configuration, we lose some information, but the
12462 tracing itself is not impacted. */
12465 btrace_read_config (&tinfo->conf);
12467 CATCH (err, RETURN_MASK_ERROR)
12469 if (err.message != NULL)
12470 warning ("%s", err.message);
12477 /* Disable branch tracing. */
12480 remote_disable_btrace (struct target_ops *self,
12481 struct btrace_target_info *tinfo)
12483 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12484 struct remote_state *rs = get_remote_state ();
12485 char *buf = rs->buf;
12486 char *endbuf = rs->buf + get_remote_packet_size ();
12488 if (packet_config_support (packet) != PACKET_ENABLE)
12489 error (_("Target does not support branch tracing."));
12491 set_general_thread (tinfo->ptid);
12493 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12495 getpkt (&rs->buf, &rs->buf_size, 0);
12497 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12499 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12500 error (_("Could not disable branch tracing for %s: %s"),
12501 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12503 error (_("Could not disable branch tracing for %s."),
12504 target_pid_to_str (tinfo->ptid));
12510 /* Teardown branch tracing. */
12513 remote_teardown_btrace (struct target_ops *self,
12514 struct btrace_target_info *tinfo)
12516 /* We must not talk to the target during teardown. */
12520 /* Read the branch trace. */
12522 static enum btrace_error
12523 remote_read_btrace (struct target_ops *self,
12524 struct btrace_data *btrace,
12525 struct btrace_target_info *tinfo,
12526 enum btrace_read_type type)
12528 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12529 struct remote_state *rs = get_remote_state ();
12530 struct cleanup *cleanup;
12534 if (packet_config_support (packet) != PACKET_ENABLE)
12535 error (_("Target does not support branch tracing."));
12537 #if !defined(HAVE_LIBEXPAT)
12538 error (_("Cannot process branch tracing result. XML parsing not supported."));
12543 case BTRACE_READ_ALL:
12546 case BTRACE_READ_NEW:
12549 case BTRACE_READ_DELTA:
12553 internal_error (__FILE__, __LINE__,
12554 _("Bad branch tracing read type: %u."),
12555 (unsigned int) type);
12558 xml = target_read_stralloc (¤t_target,
12559 TARGET_OBJECT_BTRACE, annex);
12561 return BTRACE_ERR_UNKNOWN;
12563 cleanup = make_cleanup (xfree, xml);
12564 parse_xml_btrace (btrace, xml);
12565 do_cleanups (cleanup);
12567 return BTRACE_ERR_NONE;
12570 static const struct btrace_config *
12571 remote_btrace_conf (struct target_ops *self,
12572 const struct btrace_target_info *tinfo)
12574 return &tinfo->conf;
12578 remote_augmented_libraries_svr4_read (struct target_ops *self)
12580 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12584 /* Implementation of to_load. */
12587 remote_load (struct target_ops *self, const char *name, int from_tty)
12589 generic_load (name, from_tty);
12592 /* Accepts an integer PID; returns a string representing a file that
12593 can be opened on the remote side to get the symbols for the child
12594 process. Returns NULL if the operation is not supported. */
12597 remote_pid_to_exec_file (struct target_ops *self, int pid)
12599 static char *filename = NULL;
12600 struct inferior *inf;
12601 char *annex = NULL;
12603 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12606 if (filename != NULL)
12609 inf = find_inferior_pid (pid);
12611 internal_error (__FILE__, __LINE__,
12612 _("not currently attached to process %d"), pid);
12614 if (!inf->fake_pid_p)
12616 const int annex_size = 9;
12618 annex = alloca (annex_size);
12619 xsnprintf (annex, annex_size, "%x", pid);
12622 filename = target_read_stralloc (¤t_target,
12623 TARGET_OBJECT_EXEC_FILE, annex);
12629 init_remote_ops (void)
12631 remote_ops.to_shortname = "remote";
12632 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12633 remote_ops.to_doc =
12634 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12635 Specify the serial device it is connected to\n\
12636 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12637 remote_ops.to_open = remote_open;
12638 remote_ops.to_close = remote_close;
12639 remote_ops.to_detach = remote_detach;
12640 remote_ops.to_disconnect = remote_disconnect;
12641 remote_ops.to_resume = remote_resume;
12642 remote_ops.to_wait = remote_wait;
12643 remote_ops.to_fetch_registers = remote_fetch_registers;
12644 remote_ops.to_store_registers = remote_store_registers;
12645 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12646 remote_ops.to_files_info = remote_files_info;
12647 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12648 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12649 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12650 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12651 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12652 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12653 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12654 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12655 remote_ops.to_watchpoint_addr_within_range =
12656 remote_watchpoint_addr_within_range;
12657 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12658 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12659 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12660 remote_ops.to_region_ok_for_hw_watchpoint
12661 = remote_region_ok_for_hw_watchpoint;
12662 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12663 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12664 remote_ops.to_kill = remote_kill;
12665 remote_ops.to_load = remote_load;
12666 remote_ops.to_mourn_inferior = remote_mourn;
12667 remote_ops.to_pass_signals = remote_pass_signals;
12668 remote_ops.to_program_signals = remote_program_signals;
12669 remote_ops.to_thread_alive = remote_thread_alive;
12670 remote_ops.to_update_thread_list = remote_update_thread_list;
12671 remote_ops.to_pid_to_str = remote_pid_to_str;
12672 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12673 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12674 remote_ops.to_stop = remote_stop;
12675 remote_ops.to_interrupt = remote_interrupt;
12676 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12677 remote_ops.to_xfer_partial = remote_xfer_partial;
12678 remote_ops.to_rcmd = remote_rcmd;
12679 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12680 remote_ops.to_log_command = serial_log_command;
12681 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12682 remote_ops.to_stratum = process_stratum;
12683 remote_ops.to_has_all_memory = default_child_has_all_memory;
12684 remote_ops.to_has_memory = default_child_has_memory;
12685 remote_ops.to_has_stack = default_child_has_stack;
12686 remote_ops.to_has_registers = default_child_has_registers;
12687 remote_ops.to_has_execution = default_child_has_execution;
12688 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12689 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12690 remote_ops.to_magic = OPS_MAGIC;
12691 remote_ops.to_memory_map = remote_memory_map;
12692 remote_ops.to_flash_erase = remote_flash_erase;
12693 remote_ops.to_flash_done = remote_flash_done;
12694 remote_ops.to_read_description = remote_read_description;
12695 remote_ops.to_search_memory = remote_search_memory;
12696 remote_ops.to_can_async_p = remote_can_async_p;
12697 remote_ops.to_is_async_p = remote_is_async_p;
12698 remote_ops.to_async = remote_async;
12699 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12700 remote_ops.to_terminal_ours = remote_terminal_ours;
12701 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12702 remote_ops.to_supports_multi_process = remote_supports_multi_process;
12703 remote_ops.to_supports_disable_randomization
12704 = remote_supports_disable_randomization;
12705 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12706 remote_ops.to_fileio_open = remote_hostio_open;
12707 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12708 remote_ops.to_fileio_pread = remote_hostio_pread;
12709 remote_ops.to_fileio_fstat = remote_hostio_fstat;
12710 remote_ops.to_fileio_close = remote_hostio_close;
12711 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12712 remote_ops.to_fileio_readlink = remote_hostio_readlink;
12713 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12714 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12715 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12716 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12717 remote_ops.to_trace_init = remote_trace_init;
12718 remote_ops.to_download_tracepoint = remote_download_tracepoint;
12719 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12720 remote_ops.to_download_trace_state_variable
12721 = remote_download_trace_state_variable;
12722 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12723 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12724 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12725 remote_ops.to_trace_start = remote_trace_start;
12726 remote_ops.to_get_trace_status = remote_get_trace_status;
12727 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12728 remote_ops.to_trace_stop = remote_trace_stop;
12729 remote_ops.to_trace_find = remote_trace_find;
12730 remote_ops.to_get_trace_state_variable_value
12731 = remote_get_trace_state_variable_value;
12732 remote_ops.to_save_trace_data = remote_save_trace_data;
12733 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
12734 remote_ops.to_upload_trace_state_variables
12735 = remote_upload_trace_state_variables;
12736 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
12737 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
12738 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12739 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
12740 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
12741 remote_ops.to_set_trace_notes = remote_set_trace_notes;
12742 remote_ops.to_core_of_thread = remote_core_of_thread;
12743 remote_ops.to_verify_memory = remote_verify_memory;
12744 remote_ops.to_get_tib_address = remote_get_tib_address;
12745 remote_ops.to_set_permissions = remote_set_permissions;
12746 remote_ops.to_static_tracepoint_marker_at
12747 = remote_static_tracepoint_marker_at;
12748 remote_ops.to_static_tracepoint_markers_by_strid
12749 = remote_static_tracepoint_markers_by_strid;
12750 remote_ops.to_traceframe_info = remote_traceframe_info;
12751 remote_ops.to_use_agent = remote_use_agent;
12752 remote_ops.to_can_use_agent = remote_can_use_agent;
12753 remote_ops.to_supports_btrace = remote_supports_btrace;
12754 remote_ops.to_enable_btrace = remote_enable_btrace;
12755 remote_ops.to_disable_btrace = remote_disable_btrace;
12756 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12757 remote_ops.to_read_btrace = remote_read_btrace;
12758 remote_ops.to_btrace_conf = remote_btrace_conf;
12759 remote_ops.to_augmented_libraries_svr4_read =
12760 remote_augmented_libraries_svr4_read;
12763 /* Set up the extended remote vector by making a copy of the standard
12764 remote vector and adding to it. */
12767 init_extended_remote_ops (void)
12769 extended_remote_ops = remote_ops;
12771 extended_remote_ops.to_shortname = "extended-remote";
12772 extended_remote_ops.to_longname =
12773 "Extended remote serial target in gdb-specific protocol";
12774 extended_remote_ops.to_doc =
12775 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12776 Specify the serial device it is connected to (e.g. /dev/ttya).";
12777 extended_remote_ops.to_open = extended_remote_open;
12778 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12779 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
12780 extended_remote_ops.to_detach = extended_remote_detach;
12781 extended_remote_ops.to_attach = extended_remote_attach;
12782 extended_remote_ops.to_post_attach = extended_remote_post_attach;
12783 extended_remote_ops.to_kill = extended_remote_kill;
12784 extended_remote_ops.to_supports_disable_randomization
12785 = extended_remote_supports_disable_randomization;
12786 extended_remote_ops.to_follow_fork = remote_follow_fork;
12787 extended_remote_ops.to_follow_exec = remote_follow_exec;
12788 extended_remote_ops.to_insert_fork_catchpoint
12789 = remote_insert_fork_catchpoint;
12790 extended_remote_ops.to_remove_fork_catchpoint
12791 = remote_remove_fork_catchpoint;
12792 extended_remote_ops.to_insert_vfork_catchpoint
12793 = remote_insert_vfork_catchpoint;
12794 extended_remote_ops.to_remove_vfork_catchpoint
12795 = remote_remove_vfork_catchpoint;
12799 remote_can_async_p (struct target_ops *ops)
12801 struct remote_state *rs = get_remote_state ();
12803 if (!target_async_permitted)
12804 /* We only enable async when the user specifically asks for it. */
12807 /* We're async whenever the serial device is. */
12808 return serial_can_async_p (rs->remote_desc);
12812 remote_is_async_p (struct target_ops *ops)
12814 struct remote_state *rs = get_remote_state ();
12816 if (!target_async_permitted)
12817 /* We only enable async when the user specifically asks for it. */
12820 /* We're async whenever the serial device is. */
12821 return serial_is_async_p (rs->remote_desc);
12824 /* Pass the SERIAL event on and up to the client. One day this code
12825 will be able to delay notifying the client of an event until the
12826 point where an entire packet has been received. */
12828 static serial_event_ftype remote_async_serial_handler;
12831 remote_async_serial_handler (struct serial *scb, void *context)
12833 struct remote_state *rs = context;
12835 /* Don't propogate error information up to the client. Instead let
12836 the client find out about the error by querying the target. */
12837 inferior_event_handler (INF_REG_EVENT, NULL);
12841 remote_async_inferior_event_handler (gdb_client_data data)
12843 inferior_event_handler (INF_REG_EVENT, NULL);
12847 remote_async (struct target_ops *ops, int enable)
12849 struct remote_state *rs = get_remote_state ();
12853 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
12855 /* If there are pending events in the stop reply queue tell the
12856 event loop to process them. */
12857 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12858 mark_async_event_handler (remote_async_inferior_event_token);
12862 serial_async (rs->remote_desc, NULL, NULL);
12863 clear_async_event_handler (remote_async_inferior_event_token);
12868 set_remote_cmd (char *args, int from_tty)
12870 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
12874 show_remote_cmd (char *args, int from_tty)
12876 /* We can't just use cmd_show_list here, because we want to skip
12877 the redundant "show remote Z-packet" and the legacy aliases. */
12878 struct cleanup *showlist_chain;
12879 struct cmd_list_element *list = remote_show_cmdlist;
12880 struct ui_out *uiout = current_uiout;
12882 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12883 for (; list != NULL; list = list->next)
12884 if (strcmp (list->name, "Z-packet") == 0)
12886 else if (list->type == not_set_cmd)
12887 /* Alias commands are exactly like the original, except they
12888 don't have the normal type. */
12892 struct cleanup *option_chain
12893 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
12895 ui_out_field_string (uiout, "name", list->name);
12896 ui_out_text (uiout, ": ");
12897 if (list->type == show_cmd)
12898 do_show_command ((char *) NULL, from_tty, list);
12900 cmd_func (list, NULL, from_tty);
12901 /* Close the tuple. */
12902 do_cleanups (option_chain);
12905 /* Close the tuple. */
12906 do_cleanups (showlist_chain);
12910 /* Function to be called whenever a new objfile (shlib) is detected. */
12912 remote_new_objfile (struct objfile *objfile)
12914 struct remote_state *rs = get_remote_state ();
12916 if (rs->remote_desc != 0) /* Have a remote connection. */
12917 remote_check_symbols ();
12920 /* Pull all the tracepoints defined on the target and create local
12921 data structures representing them. We don't want to create real
12922 tracepoints yet, we don't want to mess up the user's existing
12926 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
12928 struct remote_state *rs = get_remote_state ();
12931 /* Ask for a first packet of tracepoint definition. */
12933 getpkt (&rs->buf, &rs->buf_size, 0);
12935 while (*p && *p != 'l')
12937 parse_tracepoint_definition (p, utpp);
12938 /* Ask for another packet of tracepoint definition. */
12940 getpkt (&rs->buf, &rs->buf_size, 0);
12947 remote_upload_trace_state_variables (struct target_ops *self,
12948 struct uploaded_tsv **utsvp)
12950 struct remote_state *rs = get_remote_state ();
12953 /* Ask for a first packet of variable definition. */
12955 getpkt (&rs->buf, &rs->buf_size, 0);
12957 while (*p && *p != 'l')
12959 parse_tsv_definition (p, utsvp);
12960 /* Ask for another packet of variable definition. */
12962 getpkt (&rs->buf, &rs->buf_size, 0);
12968 /* The "set/show range-stepping" show hook. */
12971 show_range_stepping (struct ui_file *file, int from_tty,
12972 struct cmd_list_element *c,
12975 fprintf_filtered (file,
12976 _("Debugger's willingness to use range stepping "
12977 "is %s.\n"), value);
12980 /* The "set/show range-stepping" set hook. */
12983 set_range_stepping (char *ignore_args, int from_tty,
12984 struct cmd_list_element *c)
12986 struct remote_state *rs = get_remote_state ();
12988 /* Whene enabling, check whether range stepping is actually
12989 supported by the target, and warn if not. */
12990 if (use_range_stepping)
12992 if (rs->remote_desc != NULL)
12994 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12995 remote_vcont_probe (rs);
12997 if (packet_support (PACKET_vCont) == PACKET_ENABLE
12998 && rs->supports_vCont.r)
13002 warning (_("Range stepping is not supported by the current target"));
13007 _initialize_remote (void)
13009 struct remote_state *rs;
13010 struct cmd_list_element *cmd;
13011 const char *cmd_name;
13013 /* architecture specific data */
13014 remote_gdbarch_data_handle =
13015 gdbarch_data_register_post_init (init_remote_state);
13016 remote_g_packet_data_handle =
13017 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13020 = register_program_space_data_with_cleanup (NULL,
13021 remote_pspace_data_cleanup);
13023 /* Initialize the per-target state. At the moment there is only one
13024 of these, not one per target. Only one target is active at a
13026 remote_state = new_remote_state ();
13028 init_remote_ops ();
13029 add_target (&remote_ops);
13031 init_extended_remote_ops ();
13032 add_target (&extended_remote_ops);
13034 /* Hook into new objfile notification. */
13035 observer_attach_new_objfile (remote_new_objfile);
13036 /* We're no longer interested in notification events of an inferior
13038 observer_attach_inferior_exit (discard_pending_stop_replies);
13040 /* Set up signal handlers. */
13041 async_sigint_remote_token =
13042 create_async_signal_handler (async_remote_interrupt, NULL);
13043 async_sigint_remote_twice_token =
13044 create_async_signal_handler (async_remote_interrupt_twice, NULL);
13047 init_remote_threadtests ();
13050 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13051 /* set/show remote ... */
13053 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13054 Remote protocol specific variables\n\
13055 Configure various remote-protocol specific variables such as\n\
13056 the packets being used"),
13057 &remote_set_cmdlist, "set remote ",
13058 0 /* allow-unknown */, &setlist);
13059 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13060 Remote protocol specific variables\n\
13061 Configure various remote-protocol specific variables such as\n\
13062 the packets being used"),
13063 &remote_show_cmdlist, "show remote ",
13064 0 /* allow-unknown */, &showlist);
13066 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13067 Compare section data on target to the exec file.\n\
13068 Argument is a single section name (default: all loaded sections).\n\
13069 To compare only read-only loaded sections, specify the -r option."),
13072 add_cmd ("packet", class_maintenance, packet_command, _("\
13073 Send an arbitrary packet to a remote target.\n\
13074 maintenance packet TEXT\n\
13075 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13076 this command sends the string TEXT to the inferior, and displays the\n\
13077 response packet. GDB supplies the initial `$' character, and the\n\
13078 terminating `#' character and checksum."),
13081 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13082 Set whether to send break if interrupted."), _("\
13083 Show whether to send break if interrupted."), _("\
13084 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13085 set_remotebreak, show_remotebreak,
13086 &setlist, &showlist);
13087 cmd_name = "remotebreak";
13088 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13089 deprecate_cmd (cmd, "set remote interrupt-sequence");
13090 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13091 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13092 deprecate_cmd (cmd, "show remote interrupt-sequence");
13094 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13095 interrupt_sequence_modes, &interrupt_sequence_mode,
13097 Set interrupt sequence to remote target."), _("\
13098 Show interrupt sequence to remote target."), _("\
13099 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13100 NULL, show_interrupt_sequence,
13101 &remote_set_cmdlist,
13102 &remote_show_cmdlist);
13104 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13105 &interrupt_on_connect, _("\
13106 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13107 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13108 If set, interrupt sequence is sent to remote target."),
13110 &remote_set_cmdlist, &remote_show_cmdlist);
13112 /* Install commands for configuring memory read/write packets. */
13114 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13115 Set the maximum number of bytes per memory write packet (deprecated)."),
13117 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13118 Show the maximum number of bytes per memory write packet (deprecated)."),
13120 add_cmd ("memory-write-packet-size", no_class,
13121 set_memory_write_packet_size, _("\
13122 Set the maximum number of bytes per memory-write packet.\n\
13123 Specify the number of bytes in a packet or 0 (zero) for the\n\
13124 default packet size. The actual limit is further reduced\n\
13125 dependent on the target. Specify ``fixed'' to disable the\n\
13126 further restriction and ``limit'' to enable that restriction."),
13127 &remote_set_cmdlist);
13128 add_cmd ("memory-read-packet-size", no_class,
13129 set_memory_read_packet_size, _("\
13130 Set the maximum number of bytes per memory-read packet.\n\
13131 Specify the number of bytes in a packet or 0 (zero) for the\n\
13132 default packet size. The actual limit is further reduced\n\
13133 dependent on the target. Specify ``fixed'' to disable the\n\
13134 further restriction and ``limit'' to enable that restriction."),
13135 &remote_set_cmdlist);
13136 add_cmd ("memory-write-packet-size", no_class,
13137 show_memory_write_packet_size,
13138 _("Show the maximum number of bytes per memory-write packet."),
13139 &remote_show_cmdlist);
13140 add_cmd ("memory-read-packet-size", no_class,
13141 show_memory_read_packet_size,
13142 _("Show the maximum number of bytes per memory-read packet."),
13143 &remote_show_cmdlist);
13145 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13146 &remote_hw_watchpoint_limit, _("\
13147 Set the maximum number of target hardware watchpoints."), _("\
13148 Show the maximum number of target hardware watchpoints."), _("\
13149 Specify a negative limit for unlimited."),
13150 NULL, NULL, /* FIXME: i18n: The maximum
13151 number of target hardware
13152 watchpoints is %s. */
13153 &remote_set_cmdlist, &remote_show_cmdlist);
13154 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13155 &remote_hw_watchpoint_length_limit, _("\
13156 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13157 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13158 Specify a negative limit for unlimited."),
13159 NULL, NULL, /* FIXME: i18n: The maximum
13160 length (in bytes) of a target
13161 hardware watchpoint is %s. */
13162 &remote_set_cmdlist, &remote_show_cmdlist);
13163 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13164 &remote_hw_breakpoint_limit, _("\
13165 Set the maximum number of target hardware breakpoints."), _("\
13166 Show the maximum number of target hardware breakpoints."), _("\
13167 Specify a negative limit for unlimited."),
13168 NULL, NULL, /* FIXME: i18n: The maximum
13169 number of target hardware
13170 breakpoints is %s. */
13171 &remote_set_cmdlist, &remote_show_cmdlist);
13173 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13174 &remote_address_size, _("\
13175 Set the maximum size of the address (in bits) in a memory packet."), _("\
13176 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13178 NULL, /* FIXME: i18n: */
13179 &setlist, &showlist);
13181 init_all_packet_configs ();
13183 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13184 "X", "binary-download", 1);
13186 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13187 "vCont", "verbose-resume", 0);
13189 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13190 "QPassSignals", "pass-signals", 0);
13192 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13193 "QProgramSignals", "program-signals", 0);
13195 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13196 "qSymbol", "symbol-lookup", 0);
13198 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13199 "P", "set-register", 1);
13201 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13202 "p", "fetch-register", 1);
13204 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13205 "Z0", "software-breakpoint", 0);
13207 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13208 "Z1", "hardware-breakpoint", 0);
13210 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13211 "Z2", "write-watchpoint", 0);
13213 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13214 "Z3", "read-watchpoint", 0);
13216 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13217 "Z4", "access-watchpoint", 0);
13219 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13220 "qXfer:auxv:read", "read-aux-vector", 0);
13222 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13223 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13225 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13226 "qXfer:features:read", "target-features", 0);
13228 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13229 "qXfer:libraries:read", "library-info", 0);
13231 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13232 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13234 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13235 "qXfer:memory-map:read", "memory-map", 0);
13237 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13238 "qXfer:spu:read", "read-spu-object", 0);
13240 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13241 "qXfer:spu:write", "write-spu-object", 0);
13243 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13244 "qXfer:osdata:read", "osdata", 0);
13246 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13247 "qXfer:threads:read", "threads", 0);
13249 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13250 "qXfer:siginfo:read", "read-siginfo-object", 0);
13252 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13253 "qXfer:siginfo:write", "write-siginfo-object", 0);
13255 add_packet_config_cmd
13256 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13257 "qXfer:traceframe-info:read", "traceframe-info", 0);
13259 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13260 "qXfer:uib:read", "unwind-info-block", 0);
13262 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13263 "qGetTLSAddr", "get-thread-local-storage-address",
13266 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13267 "qGetTIBAddr", "get-thread-information-block-address",
13270 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13271 "bc", "reverse-continue", 0);
13273 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13274 "bs", "reverse-step", 0);
13276 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13277 "qSupported", "supported-packets", 0);
13279 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13280 "qSearch:memory", "search-memory", 0);
13282 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13283 "qTStatus", "trace-status", 0);
13285 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13286 "vFile:setfs", "hostio-setfs", 0);
13288 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13289 "vFile:open", "hostio-open", 0);
13291 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13292 "vFile:pread", "hostio-pread", 0);
13294 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13295 "vFile:pwrite", "hostio-pwrite", 0);
13297 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13298 "vFile:close", "hostio-close", 0);
13300 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13301 "vFile:unlink", "hostio-unlink", 0);
13303 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13304 "vFile:readlink", "hostio-readlink", 0);
13306 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13307 "vFile:fstat", "hostio-fstat", 0);
13309 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13310 "vAttach", "attach", 0);
13312 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13315 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13316 "QStartNoAckMode", "noack", 0);
13318 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13319 "vKill", "kill", 0);
13321 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13322 "qAttached", "query-attached", 0);
13324 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13325 "ConditionalTracepoints",
13326 "conditional-tracepoints", 0);
13328 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13329 "ConditionalBreakpoints",
13330 "conditional-breakpoints", 0);
13332 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13333 "BreakpointCommands",
13334 "breakpoint-commands", 0);
13336 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13337 "FastTracepoints", "fast-tracepoints", 0);
13339 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13340 "TracepointSource", "TracepointSource", 0);
13342 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13343 "QAllow", "allow", 0);
13345 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13346 "StaticTracepoints", "static-tracepoints", 0);
13348 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13349 "InstallInTrace", "install-in-trace", 0);
13351 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13352 "qXfer:statictrace:read", "read-sdata-object", 0);
13354 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13355 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13357 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13358 "QDisableRandomization", "disable-randomization", 0);
13360 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13361 "QAgent", "agent", 0);
13363 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13364 "QTBuffer:size", "trace-buffer-size", 0);
13366 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13367 "Qbtrace:off", "disable-btrace", 0);
13369 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13370 "Qbtrace:bts", "enable-btrace-bts", 0);
13372 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13373 "Qbtrace:pt", "enable-btrace-pt", 0);
13375 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13376 "qXfer:btrace", "read-btrace", 0);
13378 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13379 "qXfer:btrace-conf", "read-btrace-conf", 0);
13381 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13382 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13384 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13385 "multiprocess-feature", "multiprocess-feature", 0);
13387 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13388 "swbreak-feature", "swbreak-feature", 0);
13390 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13391 "hwbreak-feature", "hwbreak-feature", 0);
13393 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13394 "fork-event-feature", "fork-event-feature", 0);
13396 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13397 "vfork-event-feature", "vfork-event-feature", 0);
13399 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13400 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13402 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13403 "exec-event-feature", "exec-event-feature", 0);
13405 /* Assert that we've registered "set remote foo-packet" commands
13406 for all packet configs. */
13410 for (i = 0; i < PACKET_MAX; i++)
13412 /* Ideally all configs would have a command associated. Some
13413 still don't though. */
13418 case PACKET_QNonStop:
13419 case PACKET_EnableDisableTracepoints_feature:
13420 case PACKET_tracenz_feature:
13421 case PACKET_DisconnectedTracing_feature:
13422 case PACKET_augmented_libraries_svr4_read_feature:
13424 /* Additions to this list need to be well justified:
13425 pre-existing packets are OK; new packets are not. */
13433 /* This catches both forgetting to add a config command, and
13434 forgetting to remove a packet from the exception list. */
13435 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13439 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13440 Z sub-packet has its own set and show commands, but users may
13441 have sets to this variable in their .gdbinit files (or in their
13443 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13444 &remote_Z_packet_detect, _("\
13445 Set use of remote protocol `Z' packets"), _("\
13446 Show use of remote protocol `Z' packets "), _("\
13447 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13449 set_remote_protocol_Z_packet_cmd,
13450 show_remote_protocol_Z_packet_cmd,
13451 /* FIXME: i18n: Use of remote protocol
13452 `Z' packets is %s. */
13453 &remote_set_cmdlist, &remote_show_cmdlist);
13455 add_prefix_cmd ("remote", class_files, remote_command, _("\
13456 Manipulate files on the remote system\n\
13457 Transfer files to and from the remote target system."),
13458 &remote_cmdlist, "remote ",
13459 0 /* allow-unknown */, &cmdlist);
13461 add_cmd ("put", class_files, remote_put_command,
13462 _("Copy a local file to the remote system."),
13465 add_cmd ("get", class_files, remote_get_command,
13466 _("Copy a remote file to the local system."),
13469 add_cmd ("delete", class_files, remote_delete_command,
13470 _("Delete a remote file."),
13473 add_setshow_string_noescape_cmd ("exec-file", class_files,
13474 &remote_exec_file_var, _("\
13475 Set the remote pathname for \"run\""), _("\
13476 Show the remote pathname for \"run\""), NULL,
13477 set_remote_exec_file,
13478 show_remote_exec_file,
13479 &remote_set_cmdlist,
13480 &remote_show_cmdlist);
13482 add_setshow_boolean_cmd ("range-stepping", class_run,
13483 &use_range_stepping, _("\
13484 Enable or disable range stepping."), _("\
13485 Show whether target-assisted range stepping is enabled."), _("\
13486 If on, and the target supports it, when stepping a source line, GDB\n\
13487 tells the target to step the corresponding range of addresses itself instead\n\
13488 of issuing multiple single-steps. This speeds up source level\n\
13489 stepping. If off, GDB always issues single-steps, even if range\n\
13490 stepping is supported by the target. The default is on."),
13491 set_range_stepping,
13492 show_range_stepping,
13496 /* Eventually initialize fileio. See fileio.c */
13497 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13499 /* Take advantage of the fact that the TID field is not used, to tag
13500 special ptids with it set to != 0. */
13501 magic_null_ptid = ptid_build (42000, -1, 1);
13502 not_sent_ptid = ptid_build (42000, -2, 1);
13503 any_thread_ptid = ptid_build (42000, 0, 1);
13505 target_buf_size = 2048;
13506 target_buf = xmalloc (target_buf_size);