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 remote_thread_events (struct target_ops *ops, int enable);
144 static void sync_remote_interrupt_twice (int signo);
146 static void interrupt_query (void);
148 static void set_general_thread (struct ptid ptid);
149 static void set_continue_thread (struct ptid ptid);
151 static void get_offsets (void);
153 static void skip_frame (void);
155 static long read_frame (char **buf_p, long *sizeof_buf);
157 static int hexnumlen (ULONGEST num);
159 static void init_remote_ops (void);
161 static void init_extended_remote_ops (void);
163 static void remote_stop (struct target_ops *self, ptid_t);
165 static int stubhex (int ch);
167 static int hexnumstr (char *, ULONGEST);
169 static int hexnumnstr (char *, ULONGEST, int);
171 static CORE_ADDR remote_address_masked (CORE_ADDR);
173 static void print_packet (const char *);
175 static void compare_sections_command (char *, int);
177 static void packet_command (char *, int);
179 static int stub_unpack_int (char *buff, int fieldlength);
181 static ptid_t remote_current_thread (ptid_t oldptid);
183 static int putpkt_binary (const char *buf, int cnt);
185 static void check_binary_download (CORE_ADDR addr);
187 struct packet_config;
189 static void show_packet_config_cmd (struct packet_config *config);
191 static void show_remote_protocol_packet_cmd (struct ui_file *file,
193 struct cmd_list_element *c,
196 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197 static ptid_t read_ptid (char *buf, char **obuf);
199 static void remote_set_permissions (struct target_ops *self);
201 static int remote_get_trace_status (struct target_ops *self,
202 struct trace_status *ts);
204 static int remote_upload_tracepoints (struct target_ops *self,
205 struct uploaded_tp **utpp);
207 static int remote_upload_trace_state_variables (struct target_ops *self,
208 struct uploaded_tsv **utsvp);
210 static void remote_query_supported (void);
212 static void remote_check_symbols (void);
214 void _initialize_remote (void);
217 static void stop_reply_xfree (struct stop_reply *);
218 static void remote_parse_stop_reply (char *, struct stop_reply *);
219 static void push_stop_reply (struct stop_reply *);
220 static void discard_pending_stop_replies_in_queue (struct remote_state *);
221 static int peek_stop_reply (ptid_t ptid);
223 struct threads_listing_context;
224 static void remove_new_fork_children (struct threads_listing_context *);
226 static void remote_async_inferior_event_handler (gdb_client_data);
228 static void remote_terminal_ours (struct target_ops *self);
230 static int remote_read_description_p (struct target_ops *target);
232 static void remote_console_output (char *msg);
234 static int remote_supports_cond_breakpoints (struct target_ops *self);
236 static int remote_can_run_breakpoint_commands (struct target_ops *self);
238 static void remote_btrace_reset (void);
240 static int stop_reply_queue_length (void);
242 static void readahead_cache_invalidate (void);
246 static struct cmd_list_element *remote_cmdlist;
248 /* For "set remote" and "show remote". */
250 static struct cmd_list_element *remote_set_cmdlist;
251 static struct cmd_list_element *remote_show_cmdlist;
253 /* Stub vCont actions support.
255 Each field is a boolean flag indicating whether the stub reports
256 support for the corresponding action. */
258 struct vCont_action_support
273 /* Controls whether GDB is willing to use range stepping. */
275 static int use_range_stepping = 1;
277 #define OPAQUETHREADBYTES 8
279 /* a 64 bit opaque identifier */
280 typedef unsigned char threadref[OPAQUETHREADBYTES];
282 /* About this many threadisds fit in a packet. */
284 #define MAXTHREADLISTRESULTS 32
286 /* Data for the vFile:pread readahead cache. */
288 struct readahead_cache
290 /* The file descriptor for the file that is being cached. -1 if the
294 /* The offset into the file that the cache buffer corresponds
298 /* The buffer holding the cache contents. */
300 /* The buffer's size. We try to read as much as fits into a packet
304 /* Cache hit and miss counters. */
309 /* Description of the remote protocol state for the currently
310 connected target. This is per-target state, and independent of the
311 selected architecture. */
315 /* A buffer to use for incoming packets, and its current size. The
316 buffer is grown dynamically for larger incoming packets.
317 Outgoing packets may also be constructed in this buffer.
318 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
324 /* True if we're going through initial connection setup (finding out
325 about the remote side's threads, relocating symbols, etc.). */
328 /* If we negotiated packet size explicitly (and thus can bypass
329 heuristics for the largest packet size that will not overflow
330 a buffer in the stub), this will be set to that packet size.
331 Otherwise zero, meaning to use the guessed size. */
332 long explicit_packet_size;
334 /* remote_wait is normally called when the target is running and
335 waits for a stop reply packet. But sometimes we need to call it
336 when the target is already stopped. We can send a "?" packet
337 and have remote_wait read the response. Or, if we already have
338 the response, we can stash it in BUF and tell remote_wait to
339 skip calling getpkt. This flag is set when BUF contains a
340 stop reply packet and the target is not waiting. */
341 int cached_wait_status;
343 /* True, if in no ack mode. That is, neither GDB nor the stub will
344 expect acks from each other. The connection is assumed to be
348 /* True if we're connected in extended remote mode. */
351 /* True if we resumed the target and we're waiting for the target to
352 stop. In the mean time, we can't start another command/query.
353 The remote server wouldn't be ready to process it, so we'd
354 timeout waiting for a reply that would never come and eventually
355 we'd close the connection. This can happen in asynchronous mode
356 because we allow GDB commands while the target is running. */
357 int waiting_for_stop_reply;
359 /* The status of the stub support for the various vCont actions. */
360 struct vCont_action_support supports_vCont;
362 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363 responded to that. */
366 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
367 remote_open knows that we don't have a file open when the program
369 struct serial *remote_desc;
371 /* These are the threads which we last sent to the remote system. The
372 TID member will be -1 for all or -2 for not sent yet. */
373 ptid_t general_thread;
374 ptid_t continue_thread;
376 /* This is the traceframe which we last selected on the remote system.
377 It will be -1 if no traceframe is selected. */
378 int remote_traceframe_number;
380 char *last_pass_packet;
382 /* The last QProgramSignals packet sent to the target. We bypass
383 sending a new program signals list down to the target if the new
384 packet is exactly the same as the last we sent. IOW, we only let
385 the target know about program signals list changes. */
386 char *last_program_signals_packet;
388 enum gdb_signal last_sent_signal;
392 char *finished_object;
393 char *finished_annex;
394 ULONGEST finished_offset;
396 /* Should we try the 'ThreadInfo' query packet?
398 This variable (NOT available to the user: auto-detect only!)
399 determines whether GDB will use the new, simpler "ThreadInfo"
400 query or the older, more complex syntax for thread queries.
401 This is an auto-detect variable (set to true at each connect,
402 and set to false when the target fails to recognize it). */
403 int use_threadinfo_query;
404 int use_threadextra_query;
406 threadref echo_nextthread;
407 threadref nextthread;
408 threadref resultthreadlist[MAXTHREADLISTRESULTS];
410 /* The state of remote notification. */
411 struct remote_notif_state *notif_state;
413 /* The branch trace configuration. */
414 struct btrace_config btrace_config;
416 /* The argument to the last "vFile:setfs:" packet we sent, used
417 to avoid sending repeated unnecessary "vFile:setfs:" packets.
418 Initialized to -1 to indicate that no "vFile:setfs:" packet
419 has yet been sent. */
422 /* A readahead cache for vFile:pread. Often, reading a binary
423 involves a sequence of small reads. E.g., when parsing an ELF
424 file. A readahead cache helps mostly the case of remote
425 debugging on a connection with higher latency, due to the
426 request/reply nature of the RSP. We only cache data for a single
427 file descriptor at a time. */
428 struct readahead_cache readahead_cache;
431 /* Private data that we'll store in (struct thread_info)->private. */
432 struct private_thread_info
438 /* Whether the target stopped for a breakpoint/watchpoint. */
439 enum target_stop_reason stop_reason;
441 /* This is set to the data address of the access causing the target
442 to stop for a watchpoint. */
443 CORE_ADDR watch_data_address;
447 free_private_thread_info (struct private_thread_info *info)
454 /* This data could be associated with a target, but we do not always
455 have access to the current target when we need it, so for now it is
456 static. This will be fine for as long as only one target is in use
458 static struct remote_state *remote_state;
460 static struct remote_state *
461 get_remote_state_raw (void)
466 /* Allocate a new struct remote_state with xmalloc, initialize it, and
469 static struct remote_state *
470 new_remote_state (void)
472 struct remote_state *result = XCNEW (struct remote_state);
474 /* The default buffer size is unimportant; it will be expanded
475 whenever a larger buffer is needed. */
476 result->buf_size = 400;
477 result->buf = (char *) xmalloc (result->buf_size);
478 result->remote_traceframe_number = -1;
479 result->last_sent_signal = GDB_SIGNAL_0;
485 /* Description of the remote protocol for a given architecture. */
489 long offset; /* Offset into G packet. */
490 long regnum; /* GDB's internal register number. */
491 LONGEST pnum; /* Remote protocol register number. */
492 int in_g_packet; /* Always part of G packet. */
493 /* long size in bytes; == register_size (target_gdbarch (), regnum);
495 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
499 struct remote_arch_state
501 /* Description of the remote protocol registers. */
502 long sizeof_g_packet;
504 /* Description of the remote protocol registers indexed by REGNUM
505 (making an array gdbarch_num_regs in size). */
506 struct packet_reg *regs;
508 /* This is the size (in chars) of the first response to the ``g''
509 packet. It is used as a heuristic when determining the maximum
510 size of memory-read and memory-write packets. A target will
511 typically only reserve a buffer large enough to hold the ``g''
512 packet. The size does not include packet overhead (headers and
514 long actual_register_packet_size;
516 /* This is the maximum size (in chars) of a non read/write packet.
517 It is also used as a cap on the size of read/write packets. */
518 long remote_packet_size;
521 /* Utility: generate error from an incoming stub packet. */
523 trace_error (char *buf)
526 return; /* not an error msg */
529 case '1': /* malformed packet error */
530 if (*++buf == '0') /* general case: */
531 error (_("remote.c: error in outgoing packet."));
533 error (_("remote.c: error in outgoing packet at field #%ld."),
534 strtol (buf, NULL, 16));
536 error (_("Target returns error code '%s'."), buf);
540 /* Utility: wait for reply from stub, while accepting "O" packets. */
542 remote_get_noisy_reply (char **buf_p,
545 do /* Loop on reply from remote stub. */
549 QUIT; /* Allow user to bail out with ^C. */
550 getpkt (buf_p, sizeof_buf, 0);
554 else if (startswith (buf, "qRelocInsn:"))
557 CORE_ADDR from, to, org_to;
559 int adjusted_size = 0;
562 p = buf + strlen ("qRelocInsn:");
563 pp = unpack_varlen_hex (p, &ul);
565 error (_("invalid qRelocInsn packet: %s"), buf);
569 unpack_varlen_hex (p, &ul);
576 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
579 CATCH (ex, RETURN_MASK_ALL)
581 if (ex.error == MEMORY_ERROR)
583 /* Propagate memory errors silently back to the
584 target. The stub may have limited the range of
585 addresses we can write to, for example. */
589 /* Something unexpectedly bad happened. Be verbose
590 so we can tell what, and propagate the error back
591 to the stub, so it doesn't get stuck waiting for
593 exception_fprintf (gdb_stderr, ex,
594 _("warning: relocating instruction: "));
602 adjusted_size = to - org_to;
604 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
608 else if (buf[0] == 'O' && buf[1] != 'K')
609 remote_console_output (buf + 1); /* 'O' message from stub */
611 return buf; /* Here's the actual reply. */
616 /* Handle for retreving the remote protocol data from gdbarch. */
617 static struct gdbarch_data *remote_gdbarch_data_handle;
619 static struct remote_arch_state *
620 get_remote_arch_state (void)
622 gdb_assert (target_gdbarch () != NULL);
623 return ((struct remote_arch_state *)
624 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
627 /* Fetch the global remote target state. */
629 static struct remote_state *
630 get_remote_state (void)
632 /* Make sure that the remote architecture state has been
633 initialized, because doing so might reallocate rs->buf. Any
634 function which calls getpkt also needs to be mindful of changes
635 to rs->buf, but this call limits the number of places which run
637 get_remote_arch_state ();
639 return get_remote_state_raw ();
642 /* Cleanup routine for the remote module's pspace data. */
645 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
647 char *remote_exec_file = (char *) arg;
649 xfree (remote_exec_file);
652 /* Fetch the remote exec-file from the current program space. */
655 get_remote_exec_file (void)
657 char *remote_exec_file;
660 = (char *) program_space_data (current_program_space,
662 if (remote_exec_file == NULL)
665 return remote_exec_file;
668 /* Set the remote exec file for PSPACE. */
671 set_pspace_remote_exec_file (struct program_space *pspace,
672 char *remote_exec_file)
674 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
677 set_program_space_data (pspace, remote_pspace_data,
678 xstrdup (remote_exec_file));
681 /* The "set/show remote exec-file" set command hook. */
684 set_remote_exec_file (char *ignored, int from_tty,
685 struct cmd_list_element *c)
687 gdb_assert (remote_exec_file_var != NULL);
688 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
691 /* The "set/show remote exec-file" show command hook. */
694 show_remote_exec_file (struct ui_file *file, int from_tty,
695 struct cmd_list_element *cmd, const char *value)
697 fprintf_filtered (file, "%s\n", remote_exec_file_var);
701 compare_pnums (const void *lhs_, const void *rhs_)
703 const struct packet_reg * const *lhs
704 = (const struct packet_reg * const *) lhs_;
705 const struct packet_reg * const *rhs
706 = (const struct packet_reg * const *) rhs_;
708 if ((*lhs)->pnum < (*rhs)->pnum)
710 else if ((*lhs)->pnum == (*rhs)->pnum)
717 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
719 int regnum, num_remote_regs, offset;
720 struct packet_reg **remote_regs;
722 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
724 struct packet_reg *r = ®s[regnum];
726 if (register_size (gdbarch, regnum) == 0)
727 /* Do not try to fetch zero-sized (placeholder) registers. */
730 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
735 /* Define the g/G packet format as the contents of each register
736 with a remote protocol number, in order of ascending protocol
739 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
740 for (num_remote_regs = 0, regnum = 0;
741 regnum < gdbarch_num_regs (gdbarch);
743 if (regs[regnum].pnum != -1)
744 remote_regs[num_remote_regs++] = ®s[regnum];
746 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
749 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
751 remote_regs[regnum]->in_g_packet = 1;
752 remote_regs[regnum]->offset = offset;
753 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
759 /* Given the architecture described by GDBARCH, return the remote
760 protocol register's number and the register's offset in the g/G
761 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
762 If the target does not have a mapping for REGNUM, return false,
763 otherwise, return true. */
766 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
767 int *pnum, int *poffset)
770 struct packet_reg *regs;
771 struct cleanup *old_chain;
773 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
775 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
776 old_chain = make_cleanup (xfree, regs);
778 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
780 *pnum = regs[regnum].pnum;
781 *poffset = regs[regnum].offset;
783 do_cleanups (old_chain);
789 init_remote_state (struct gdbarch *gdbarch)
791 struct remote_state *rs = get_remote_state_raw ();
792 struct remote_arch_state *rsa;
794 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
796 /* Use the architecture to build a regnum<->pnum table, which will be
797 1:1 unless a feature set specifies otherwise. */
798 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
799 gdbarch_num_regs (gdbarch),
802 /* Record the maximum possible size of the g packet - it may turn out
804 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
806 /* Default maximum number of characters in a packet body. Many
807 remote stubs have a hardwired buffer size of 400 bytes
808 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
809 as the maximum packet-size to ensure that the packet and an extra
810 NUL character can always fit in the buffer. This stops GDB
811 trashing stubs that try to squeeze an extra NUL into what is
812 already a full buffer (As of 1999-12-04 that was most stubs). */
813 rsa->remote_packet_size = 400 - 1;
815 /* This one is filled in when a ``g'' packet is received. */
816 rsa->actual_register_packet_size = 0;
818 /* Should rsa->sizeof_g_packet needs more space than the
819 default, adjust the size accordingly. Remember that each byte is
820 encoded as two characters. 32 is the overhead for the packet
821 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
822 (``$NN:G...#NN'') is a better guess, the below has been padded a
824 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
825 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
827 /* Make sure that the packet buffer is plenty big enough for
828 this architecture. */
829 if (rs->buf_size < rsa->remote_packet_size)
831 rs->buf_size = 2 * rsa->remote_packet_size;
832 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
838 /* Return the current allowed size of a remote packet. This is
839 inferred from the current architecture, and should be used to
840 limit the length of outgoing packets. */
842 get_remote_packet_size (void)
844 struct remote_state *rs = get_remote_state ();
845 struct remote_arch_state *rsa = get_remote_arch_state ();
847 if (rs->explicit_packet_size)
848 return rs->explicit_packet_size;
850 return rsa->remote_packet_size;
853 static struct packet_reg *
854 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
856 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
860 struct packet_reg *r = &rsa->regs[regnum];
862 gdb_assert (r->regnum == regnum);
867 static struct packet_reg *
868 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
872 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
874 struct packet_reg *r = &rsa->regs[i];
882 static struct target_ops remote_ops;
884 static struct target_ops extended_remote_ops;
886 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
887 ``forever'' still use the normal timeout mechanism. This is
888 currently used by the ASYNC code to guarentee that target reads
889 during the initial connect always time-out. Once getpkt has been
890 modified to return a timeout indication and, in turn
891 remote_wait()/wait_for_inferior() have gained a timeout parameter
893 static int wait_forever_enabled_p = 1;
895 /* Allow the user to specify what sequence to send to the remote
896 when he requests a program interruption: Although ^C is usually
897 what remote systems expect (this is the default, here), it is
898 sometimes preferable to send a break. On other systems such
899 as the Linux kernel, a break followed by g, which is Magic SysRq g
900 is required in order to interrupt the execution. */
901 const char interrupt_sequence_control_c[] = "Ctrl-C";
902 const char interrupt_sequence_break[] = "BREAK";
903 const char interrupt_sequence_break_g[] = "BREAK-g";
904 static const char *const interrupt_sequence_modes[] =
906 interrupt_sequence_control_c,
907 interrupt_sequence_break,
908 interrupt_sequence_break_g,
911 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
914 show_interrupt_sequence (struct ui_file *file, int from_tty,
915 struct cmd_list_element *c,
918 if (interrupt_sequence_mode == interrupt_sequence_control_c)
919 fprintf_filtered (file,
920 _("Send the ASCII ETX character (Ctrl-c) "
921 "to the remote target to interrupt the "
922 "execution of the program.\n"));
923 else if (interrupt_sequence_mode == interrupt_sequence_break)
924 fprintf_filtered (file,
925 _("send a break signal to the remote target "
926 "to interrupt the execution of the program.\n"));
927 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
928 fprintf_filtered (file,
929 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
930 "the remote target to interrupt the execution "
931 "of Linux kernel.\n"));
933 internal_error (__FILE__, __LINE__,
934 _("Invalid value for interrupt_sequence_mode: %s."),
935 interrupt_sequence_mode);
938 /* This boolean variable specifies whether interrupt_sequence is sent
939 to the remote target when gdb connects to it.
940 This is mostly needed when you debug the Linux kernel: The Linux kernel
941 expects BREAK g which is Magic SysRq g for connecting gdb. */
942 static int interrupt_on_connect = 0;
944 /* This variable is used to implement the "set/show remotebreak" commands.
945 Since these commands are now deprecated in favor of "set/show remote
946 interrupt-sequence", it no longer has any effect on the code. */
947 static int remote_break;
950 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
953 interrupt_sequence_mode = interrupt_sequence_break;
955 interrupt_sequence_mode = interrupt_sequence_control_c;
959 show_remotebreak (struct ui_file *file, int from_tty,
960 struct cmd_list_element *c,
965 /* This variable sets the number of bits in an address that are to be
966 sent in a memory ("M" or "m") packet. Normally, after stripping
967 leading zeros, the entire address would be sent. This variable
968 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
969 initial implementation of remote.c restricted the address sent in
970 memory packets to ``host::sizeof long'' bytes - (typically 32
971 bits). Consequently, for 64 bit targets, the upper 32 bits of an
972 address was never sent. Since fixing this bug may cause a break in
973 some remote targets this variable is principly provided to
974 facilitate backward compatibility. */
976 static unsigned int remote_address_size;
978 /* Temporary to track who currently owns the terminal. See
979 remote_terminal_* for more details. */
981 static int remote_async_terminal_ours_p;
984 /* User configurable variables for the number of characters in a
985 memory read/write packet. MIN (rsa->remote_packet_size,
986 rsa->sizeof_g_packet) is the default. Some targets need smaller
987 values (fifo overruns, et.al.) and some users need larger values
988 (speed up transfers). The variables ``preferred_*'' (the user
989 request), ``current_*'' (what was actually set) and ``forced_*''
990 (Positive - a soft limit, negative - a hard limit). */
992 struct memory_packet_config
999 /* The default max memory-write-packet-size. The 16k is historical.
1000 (It came from older GDB's using alloca for buffers and the
1001 knowledge (folklore?) that some hosts don't cope very well with
1002 large alloca calls.) */
1003 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1005 /* The minimum remote packet size for memory transfers. Ensures we
1006 can write at least one byte. */
1007 #define MIN_MEMORY_PACKET_SIZE 20
1009 /* Compute the current size of a read/write packet. Since this makes
1010 use of ``actual_register_packet_size'' the computation is dynamic. */
1013 get_memory_packet_size (struct memory_packet_config *config)
1015 struct remote_state *rs = get_remote_state ();
1016 struct remote_arch_state *rsa = get_remote_arch_state ();
1019 if (config->fixed_p)
1021 if (config->size <= 0)
1022 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1024 what_they_get = config->size;
1028 what_they_get = get_remote_packet_size ();
1029 /* Limit the packet to the size specified by the user. */
1030 if (config->size > 0
1031 && what_they_get > config->size)
1032 what_they_get = config->size;
1034 /* Limit it to the size of the targets ``g'' response unless we have
1035 permission from the stub to use a larger packet size. */
1036 if (rs->explicit_packet_size == 0
1037 && rsa->actual_register_packet_size > 0
1038 && what_they_get > rsa->actual_register_packet_size)
1039 what_they_get = rsa->actual_register_packet_size;
1041 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1042 what_they_get = MIN_MEMORY_PACKET_SIZE;
1044 /* Make sure there is room in the global buffer for this packet
1045 (including its trailing NUL byte). */
1046 if (rs->buf_size < what_they_get + 1)
1048 rs->buf_size = 2 * what_they_get;
1049 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1052 return what_they_get;
1055 /* Update the size of a read/write packet. If they user wants
1056 something really big then do a sanity check. */
1059 set_memory_packet_size (char *args, struct memory_packet_config *config)
1061 int fixed_p = config->fixed_p;
1062 long size = config->size;
1065 error (_("Argument required (integer, `fixed' or `limited')."));
1066 else if (strcmp (args, "hard") == 0
1067 || strcmp (args, "fixed") == 0)
1069 else if (strcmp (args, "soft") == 0
1070 || strcmp (args, "limit") == 0)
1076 size = strtoul (args, &end, 0);
1078 error (_("Invalid %s (bad syntax)."), config->name);
1080 /* Instead of explicitly capping the size of a packet to or
1081 disallowing it, the user is allowed to set the size to
1082 something arbitrarily large. */
1085 /* So that the query shows the correct value. */
1087 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1090 if (fixed_p && !config->fixed_p)
1092 if (! query (_("The target may not be able to correctly handle a %s\n"
1093 "of %ld bytes. Change the packet size? "),
1094 config->name, size))
1095 error (_("Packet size not changed."));
1097 /* Update the config. */
1098 config->fixed_p = fixed_p;
1099 config->size = size;
1103 show_memory_packet_size (struct memory_packet_config *config)
1105 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1106 if (config->fixed_p)
1107 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1108 get_memory_packet_size (config));
1110 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1111 get_memory_packet_size (config));
1114 static struct memory_packet_config memory_write_packet_config =
1116 "memory-write-packet-size",
1120 set_memory_write_packet_size (char *args, int from_tty)
1122 set_memory_packet_size (args, &memory_write_packet_config);
1126 show_memory_write_packet_size (char *args, int from_tty)
1128 show_memory_packet_size (&memory_write_packet_config);
1132 get_memory_write_packet_size (void)
1134 return get_memory_packet_size (&memory_write_packet_config);
1137 static struct memory_packet_config memory_read_packet_config =
1139 "memory-read-packet-size",
1143 set_memory_read_packet_size (char *args, int from_tty)
1145 set_memory_packet_size (args, &memory_read_packet_config);
1149 show_memory_read_packet_size (char *args, int from_tty)
1151 show_memory_packet_size (&memory_read_packet_config);
1155 get_memory_read_packet_size (void)
1157 long size = get_memory_packet_size (&memory_read_packet_config);
1159 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1160 extra buffer size argument before the memory read size can be
1161 increased beyond this. */
1162 if (size > get_remote_packet_size ())
1163 size = get_remote_packet_size ();
1168 /* Generic configuration support for packets the stub optionally
1169 supports. Allows the user to specify the use of the packet as well
1170 as allowing GDB to auto-detect support in the remote stub. */
1174 PACKET_SUPPORT_UNKNOWN = 0,
1179 struct packet_config
1184 /* If auto, GDB auto-detects support for this packet or feature,
1185 either through qSupported, or by trying the packet and looking
1186 at the response. If true, GDB assumes the target supports this
1187 packet. If false, the packet is disabled. Configs that don't
1188 have an associated command always have this set to auto. */
1189 enum auto_boolean detect;
1191 /* Does the target support this packet? */
1192 enum packet_support support;
1195 /* Analyze a packet's return value and update the packet config
1205 static enum packet_support packet_config_support (struct packet_config *config);
1206 static enum packet_support packet_support (int packet);
1209 show_packet_config_cmd (struct packet_config *config)
1211 char *support = "internal-error";
1213 switch (packet_config_support (config))
1216 support = "enabled";
1218 case PACKET_DISABLE:
1219 support = "disabled";
1221 case PACKET_SUPPORT_UNKNOWN:
1222 support = "unknown";
1225 switch (config->detect)
1227 case AUTO_BOOLEAN_AUTO:
1228 printf_filtered (_("Support for the `%s' packet "
1229 "is auto-detected, currently %s.\n"),
1230 config->name, support);
1232 case AUTO_BOOLEAN_TRUE:
1233 case AUTO_BOOLEAN_FALSE:
1234 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1235 config->name, support);
1241 add_packet_config_cmd (struct packet_config *config, const char *name,
1242 const char *title, int legacy)
1248 config->name = name;
1249 config->title = title;
1250 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1252 show_doc = xstrprintf ("Show current use of remote "
1253 "protocol `%s' (%s) packet",
1255 /* set/show TITLE-packet {auto,on,off} */
1256 cmd_name = xstrprintf ("%s-packet", title);
1257 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1258 &config->detect, set_doc,
1259 show_doc, NULL, /* help_doc */
1261 show_remote_protocol_packet_cmd,
1262 &remote_set_cmdlist, &remote_show_cmdlist);
1263 /* The command code copies the documentation strings. */
1266 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1271 legacy_name = xstrprintf ("%s-packet", name);
1272 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1273 &remote_set_cmdlist);
1274 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1275 &remote_show_cmdlist);
1279 static enum packet_result
1280 packet_check_result (const char *buf)
1284 /* The stub recognized the packet request. Check that the
1285 operation succeeded. */
1287 && isxdigit (buf[1]) && isxdigit (buf[2])
1289 /* "Enn" - definitly an error. */
1290 return PACKET_ERROR;
1292 /* Always treat "E." as an error. This will be used for
1293 more verbose error messages, such as E.memtypes. */
1294 if (buf[0] == 'E' && buf[1] == '.')
1295 return PACKET_ERROR;
1297 /* The packet may or may not be OK. Just assume it is. */
1301 /* The stub does not support the packet. */
1302 return PACKET_UNKNOWN;
1305 static enum packet_result
1306 packet_ok (const char *buf, struct packet_config *config)
1308 enum packet_result result;
1310 if (config->detect != AUTO_BOOLEAN_TRUE
1311 && config->support == PACKET_DISABLE)
1312 internal_error (__FILE__, __LINE__,
1313 _("packet_ok: attempt to use a disabled packet"));
1315 result = packet_check_result (buf);
1320 /* The stub recognized the packet request. */
1321 if (config->support == PACKET_SUPPORT_UNKNOWN)
1324 fprintf_unfiltered (gdb_stdlog,
1325 "Packet %s (%s) is supported\n",
1326 config->name, config->title);
1327 config->support = PACKET_ENABLE;
1330 case PACKET_UNKNOWN:
1331 /* The stub does not support the packet. */
1332 if (config->detect == AUTO_BOOLEAN_AUTO
1333 && config->support == PACKET_ENABLE)
1335 /* If the stub previously indicated that the packet was
1336 supported then there is a protocol error. */
1337 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1338 config->name, config->title);
1340 else if (config->detect == AUTO_BOOLEAN_TRUE)
1342 /* The user set it wrong. */
1343 error (_("Enabled packet %s (%s) not recognized by stub"),
1344 config->name, config->title);
1348 fprintf_unfiltered (gdb_stdlog,
1349 "Packet %s (%s) is NOT supported\n",
1350 config->name, config->title);
1351 config->support = PACKET_DISABLE;
1372 PACKET_vFile_pwrite,
1374 PACKET_vFile_unlink,
1375 PACKET_vFile_readlink,
1378 PACKET_qXfer_features,
1379 PACKET_qXfer_exec_file,
1380 PACKET_qXfer_libraries,
1381 PACKET_qXfer_libraries_svr4,
1382 PACKET_qXfer_memory_map,
1383 PACKET_qXfer_spu_read,
1384 PACKET_qXfer_spu_write,
1385 PACKET_qXfer_osdata,
1386 PACKET_qXfer_threads,
1387 PACKET_qXfer_statictrace_read,
1388 PACKET_qXfer_traceframe_info,
1394 PACKET_QPassSignals,
1395 PACKET_QProgramSignals,
1397 PACKET_qSearch_memory,
1400 PACKET_QStartNoAckMode,
1402 PACKET_qXfer_siginfo_read,
1403 PACKET_qXfer_siginfo_write,
1406 /* Support for conditional tracepoints. */
1407 PACKET_ConditionalTracepoints,
1409 /* Support for target-side breakpoint conditions. */
1410 PACKET_ConditionalBreakpoints,
1412 /* Support for target-side breakpoint commands. */
1413 PACKET_BreakpointCommands,
1415 /* Support for fast tracepoints. */
1416 PACKET_FastTracepoints,
1418 /* Support for static tracepoints. */
1419 PACKET_StaticTracepoints,
1421 /* Support for installing tracepoints while a trace experiment is
1423 PACKET_InstallInTrace,
1427 PACKET_TracepointSource,
1430 PACKET_QDisableRandomization,
1432 PACKET_QTBuffer_size,
1436 PACKET_qXfer_btrace,
1438 /* Support for the QNonStop packet. */
1441 /* Support for the QThreadEvents packet. */
1442 PACKET_QThreadEvents,
1444 /* Support for multi-process extensions. */
1445 PACKET_multiprocess_feature,
1447 /* Support for enabling and disabling tracepoints while a trace
1448 experiment is running. */
1449 PACKET_EnableDisableTracepoints_feature,
1451 /* Support for collecting strings using the tracenz bytecode. */
1452 PACKET_tracenz_feature,
1454 /* Support for continuing to run a trace experiment while GDB is
1456 PACKET_DisconnectedTracing_feature,
1458 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1459 PACKET_augmented_libraries_svr4_read_feature,
1461 /* Support for the qXfer:btrace-conf:read packet. */
1462 PACKET_qXfer_btrace_conf,
1464 /* Support for the Qbtrace-conf:bts:size packet. */
1465 PACKET_Qbtrace_conf_bts_size,
1467 /* Support for swbreak+ feature. */
1468 PACKET_swbreak_feature,
1470 /* Support for hwbreak+ feature. */
1471 PACKET_hwbreak_feature,
1473 /* Support for fork events. */
1474 PACKET_fork_event_feature,
1476 /* Support for vfork events. */
1477 PACKET_vfork_event_feature,
1479 /* Support for the Qbtrace-conf:pt:size packet. */
1480 PACKET_Qbtrace_conf_pt_size,
1482 /* Support for exec events. */
1483 PACKET_exec_event_feature,
1485 /* Support for query supported vCont actions. */
1486 PACKET_vContSupported,
1488 /* Support remote CTRL-C. */
1494 static struct packet_config remote_protocol_packets[PACKET_MAX];
1496 /* Returns the packet's corresponding "set remote foo-packet" command
1497 state. See struct packet_config for more details. */
1499 static enum auto_boolean
1500 packet_set_cmd_state (int packet)
1502 return remote_protocol_packets[packet].detect;
1505 /* Returns whether a given packet or feature is supported. This takes
1506 into account the state of the corresponding "set remote foo-packet"
1507 command, which may be used to bypass auto-detection. */
1509 static enum packet_support
1510 packet_config_support (struct packet_config *config)
1512 switch (config->detect)
1514 case AUTO_BOOLEAN_TRUE:
1515 return PACKET_ENABLE;
1516 case AUTO_BOOLEAN_FALSE:
1517 return PACKET_DISABLE;
1518 case AUTO_BOOLEAN_AUTO:
1519 return config->support;
1521 gdb_assert_not_reached (_("bad switch"));
1525 /* Same as packet_config_support, but takes the packet's enum value as
1528 static enum packet_support
1529 packet_support (int packet)
1531 struct packet_config *config = &remote_protocol_packets[packet];
1533 return packet_config_support (config);
1537 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1538 struct cmd_list_element *c,
1541 struct packet_config *packet;
1543 for (packet = remote_protocol_packets;
1544 packet < &remote_protocol_packets[PACKET_MAX];
1547 if (&packet->detect == c->var)
1549 show_packet_config_cmd (packet);
1553 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1557 /* Should we try one of the 'Z' requests? */
1561 Z_PACKET_SOFTWARE_BP,
1562 Z_PACKET_HARDWARE_BP,
1569 /* For compatibility with older distributions. Provide a ``set remote
1570 Z-packet ...'' command that updates all the Z packet types. */
1572 static enum auto_boolean remote_Z_packet_detect;
1575 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1576 struct cmd_list_element *c)
1580 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1581 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1585 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1586 struct cmd_list_element *c,
1591 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1593 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1597 /* Returns true if the multi-process extensions are in effect. */
1600 remote_multi_process_p (struct remote_state *rs)
1602 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1605 /* Returns true if fork events are supported. */
1608 remote_fork_event_p (struct remote_state *rs)
1610 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1613 /* Returns true if vfork events are supported. */
1616 remote_vfork_event_p (struct remote_state *rs)
1618 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1621 /* Returns true if exec events are supported. */
1624 remote_exec_event_p (struct remote_state *rs)
1626 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1629 /* Insert fork catchpoint target routine. If fork events are enabled
1630 then return success, nothing more to do. */
1633 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1635 struct remote_state *rs = get_remote_state ();
1637 return !remote_fork_event_p (rs);
1640 /* Remove fork catchpoint target routine. Nothing to do, just
1644 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1649 /* Insert vfork catchpoint target routine. If vfork events are enabled
1650 then return success, nothing more to do. */
1653 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1655 struct remote_state *rs = get_remote_state ();
1657 return !remote_vfork_event_p (rs);
1660 /* Remove vfork catchpoint target routine. Nothing to do, just
1664 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1669 /* Insert exec catchpoint target routine. If exec events are
1670 enabled, just return success. */
1673 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1675 struct remote_state *rs = get_remote_state ();
1677 return !remote_exec_event_p (rs);
1680 /* Remove exec catchpoint target routine. Nothing to do, just
1684 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1689 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1690 static struct async_signal_handler *async_sigint_remote_twice_token;
1691 static struct async_signal_handler *async_sigint_remote_token;
1694 /* Asynchronous signal handle registered as event loop source for
1695 when we have pending events ready to be passed to the core. */
1697 static struct async_event_handler *remote_async_inferior_event_token;
1701 static ptid_t magic_null_ptid;
1702 static ptid_t not_sent_ptid;
1703 static ptid_t any_thread_ptid;
1705 /* Find out if the stub attached to PID (and hence GDB should offer to
1706 detach instead of killing it when bailing out). */
1709 remote_query_attached (int pid)
1711 struct remote_state *rs = get_remote_state ();
1712 size_t size = get_remote_packet_size ();
1714 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1717 if (remote_multi_process_p (rs))
1718 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1720 xsnprintf (rs->buf, size, "qAttached");
1723 getpkt (&rs->buf, &rs->buf_size, 0);
1725 switch (packet_ok (rs->buf,
1726 &remote_protocol_packets[PACKET_qAttached]))
1729 if (strcmp (rs->buf, "1") == 0)
1733 warning (_("Remote failure reply: %s"), rs->buf);
1735 case PACKET_UNKNOWN:
1742 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1743 has been invented by GDB, instead of reported by the target. Since
1744 we can be connected to a remote system before before knowing about
1745 any inferior, mark the target with execution when we find the first
1746 inferior. If ATTACHED is 1, then we had just attached to this
1747 inferior. If it is 0, then we just created this inferior. If it
1748 is -1, then try querying the remote stub to find out if it had
1749 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1750 attempt to open this inferior's executable as the main executable
1751 if no main executable is open already. */
1753 static struct inferior *
1754 remote_add_inferior (int fake_pid_p, int pid, int attached,
1757 struct inferior *inf;
1759 /* Check whether this process we're learning about is to be
1760 considered attached, or if is to be considered to have been
1761 spawned by the stub. */
1763 attached = remote_query_attached (pid);
1765 if (gdbarch_has_global_solist (target_gdbarch ()))
1767 /* If the target shares code across all inferiors, then every
1768 attach adds a new inferior. */
1769 inf = add_inferior (pid);
1771 /* ... and every inferior is bound to the same program space.
1772 However, each inferior may still have its own address
1774 inf->aspace = maybe_new_address_space ();
1775 inf->pspace = current_program_space;
1779 /* In the traditional debugging scenario, there's a 1-1 match
1780 between program/address spaces. We simply bind the inferior
1781 to the program space's address space. */
1782 inf = current_inferior ();
1783 inferior_appeared (inf, pid);
1786 inf->attach_flag = attached;
1787 inf->fake_pid_p = fake_pid_p;
1789 /* If no main executable is currently open then attempt to
1790 open the file that was executed to create this inferior. */
1791 if (try_open_exec && get_exec_file (0) == NULL)
1792 exec_file_locate_attach (pid, 1);
1797 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1798 according to RUNNING. */
1801 remote_add_thread (ptid_t ptid, int running)
1803 struct remote_state *rs = get_remote_state ();
1805 /* GDB historically didn't pull threads in the initial connection
1806 setup. If the remote target doesn't even have a concept of
1807 threads (e.g., a bare-metal target), even if internally we
1808 consider that a single-threaded target, mentioning a new thread
1809 might be confusing to the user. Be silent then, preserving the
1810 age old behavior. */
1811 if (rs->starting_up)
1812 add_thread_silent (ptid);
1816 set_executing (ptid, running);
1817 set_running (ptid, running);
1820 /* Come here when we learn about a thread id from the remote target.
1821 It may be the first time we hear about such thread, so take the
1822 opportunity to add it to GDB's thread list. In case this is the
1823 first time we're noticing its corresponding inferior, add it to
1824 GDB's inferior list as well. */
1827 remote_notice_new_inferior (ptid_t currthread, int running)
1829 /* If this is a new thread, add it to GDB's thread list.
1830 If we leave it up to WFI to do this, bad things will happen. */
1832 if (in_thread_list (currthread) && is_exited (currthread))
1834 /* We're seeing an event on a thread id we knew had exited.
1835 This has to be a new thread reusing the old id. Add it. */
1836 remote_add_thread (currthread, running);
1840 if (!in_thread_list (currthread))
1842 struct inferior *inf = NULL;
1843 int pid = ptid_get_pid (currthread);
1845 if (ptid_is_pid (inferior_ptid)
1846 && pid == ptid_get_pid (inferior_ptid))
1848 /* inferior_ptid has no thread member yet. This can happen
1849 with the vAttach -> remote_wait,"TAAthread:" path if the
1850 stub doesn't support qC. This is the first stop reported
1851 after an attach, so this is the main thread. Update the
1852 ptid in the thread list. */
1853 if (in_thread_list (pid_to_ptid (pid)))
1854 thread_change_ptid (inferior_ptid, currthread);
1857 remote_add_thread (currthread, running);
1858 inferior_ptid = currthread;
1863 if (ptid_equal (magic_null_ptid, inferior_ptid))
1865 /* inferior_ptid is not set yet. This can happen with the
1866 vRun -> remote_wait,"TAAthread:" path if the stub
1867 doesn't support qC. This is the first stop reported
1868 after an attach, so this is the main thread. Update the
1869 ptid in the thread list. */
1870 thread_change_ptid (inferior_ptid, currthread);
1874 /* When connecting to a target remote, or to a target
1875 extended-remote which already was debugging an inferior, we
1876 may not know about it yet. Add it before adding its child
1877 thread, so notifications are emitted in a sensible order. */
1878 if (!in_inferior_list (ptid_get_pid (currthread)))
1880 struct remote_state *rs = get_remote_state ();
1881 int fake_pid_p = !remote_multi_process_p (rs);
1883 inf = remote_add_inferior (fake_pid_p,
1884 ptid_get_pid (currthread), -1, 1);
1887 /* This is really a new thread. Add it. */
1888 remote_add_thread (currthread, running);
1890 /* If we found a new inferior, let the common code do whatever
1891 it needs to with it (e.g., read shared libraries, insert
1892 breakpoints), unless we're just setting up an all-stop
1896 struct remote_state *rs = get_remote_state ();
1898 if (!rs->starting_up)
1899 notice_new_inferior (currthread, running, 0);
1904 /* Return the private thread data, creating it if necessary. */
1906 static struct private_thread_info *
1907 demand_private_info (ptid_t ptid)
1909 struct thread_info *info = find_thread_ptid (ptid);
1915 info->priv = XNEW (struct private_thread_info);
1916 info->private_dtor = free_private_thread_info;
1917 info->priv->core = -1;
1918 info->priv->extra = 0;
1924 /* Call this function as a result of
1925 1) A halt indication (T packet) containing a thread id
1926 2) A direct query of currthread
1927 3) Successful execution of set thread */
1930 record_currthread (struct remote_state *rs, ptid_t currthread)
1932 rs->general_thread = currthread;
1935 /* If 'QPassSignals' is supported, tell the remote stub what signals
1936 it can simply pass through to the inferior without reporting. */
1939 remote_pass_signals (struct target_ops *self,
1940 int numsigs, unsigned char *pass_signals)
1942 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1944 char *pass_packet, *p;
1946 struct remote_state *rs = get_remote_state ();
1948 gdb_assert (numsigs < 256);
1949 for (i = 0; i < numsigs; i++)
1951 if (pass_signals[i])
1954 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1955 strcpy (pass_packet, "QPassSignals:");
1956 p = pass_packet + strlen (pass_packet);
1957 for (i = 0; i < numsigs; i++)
1959 if (pass_signals[i])
1962 *p++ = tohex (i >> 4);
1963 *p++ = tohex (i & 15);
1972 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1974 putpkt (pass_packet);
1975 getpkt (&rs->buf, &rs->buf_size, 0);
1976 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1977 if (rs->last_pass_packet)
1978 xfree (rs->last_pass_packet);
1979 rs->last_pass_packet = pass_packet;
1982 xfree (pass_packet);
1986 /* If 'QProgramSignals' is supported, tell the remote stub what
1987 signals it should pass through to the inferior when detaching. */
1990 remote_program_signals (struct target_ops *self,
1991 int numsigs, unsigned char *signals)
1993 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1997 struct remote_state *rs = get_remote_state ();
1999 gdb_assert (numsigs < 256);
2000 for (i = 0; i < numsigs; i++)
2005 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2006 strcpy (packet, "QProgramSignals:");
2007 p = packet + strlen (packet);
2008 for (i = 0; i < numsigs; i++)
2010 if (signal_pass_state (i))
2013 *p++ = tohex (i >> 4);
2014 *p++ = tohex (i & 15);
2023 if (!rs->last_program_signals_packet
2024 || strcmp (rs->last_program_signals_packet, packet) != 0)
2027 getpkt (&rs->buf, &rs->buf_size, 0);
2028 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2029 xfree (rs->last_program_signals_packet);
2030 rs->last_program_signals_packet = packet;
2037 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2038 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2039 thread. If GEN is set, set the general thread, if not, then set
2040 the step/continue thread. */
2042 set_thread (struct ptid ptid, int gen)
2044 struct remote_state *rs = get_remote_state ();
2045 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2046 char *buf = rs->buf;
2047 char *endbuf = rs->buf + get_remote_packet_size ();
2049 if (ptid_equal (state, ptid))
2053 *buf++ = gen ? 'g' : 'c';
2054 if (ptid_equal (ptid, magic_null_ptid))
2055 xsnprintf (buf, endbuf - buf, "0");
2056 else if (ptid_equal (ptid, any_thread_ptid))
2057 xsnprintf (buf, endbuf - buf, "0");
2058 else if (ptid_equal (ptid, minus_one_ptid))
2059 xsnprintf (buf, endbuf - buf, "-1");
2061 write_ptid (buf, endbuf, ptid);
2063 getpkt (&rs->buf, &rs->buf_size, 0);
2065 rs->general_thread = ptid;
2067 rs->continue_thread = ptid;
2071 set_general_thread (struct ptid ptid)
2073 set_thread (ptid, 1);
2077 set_continue_thread (struct ptid ptid)
2079 set_thread (ptid, 0);
2082 /* Change the remote current process. Which thread within the process
2083 ends up selected isn't important, as long as it is the same process
2084 as what INFERIOR_PTID points to.
2086 This comes from that fact that there is no explicit notion of
2087 "selected process" in the protocol. The selected process for
2088 general operations is the process the selected general thread
2092 set_general_process (void)
2094 struct remote_state *rs = get_remote_state ();
2096 /* If the remote can't handle multiple processes, don't bother. */
2097 if (!rs->extended || !remote_multi_process_p (rs))
2100 /* We only need to change the remote current thread if it's pointing
2101 at some other process. */
2102 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2103 set_general_thread (inferior_ptid);
2107 /* Return nonzero if this is the main thread that we made up ourselves
2108 to model non-threaded targets as single-threaded. */
2111 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2113 struct remote_state *rs = get_remote_state ();
2116 if (ptid_equal (ptid, magic_null_ptid))
2117 /* The main thread is always alive. */
2120 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2121 /* The main thread is always alive. This can happen after a
2122 vAttach, if the remote side doesn't support
2129 /* Return nonzero if the thread PTID is still alive on the remote
2133 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2135 struct remote_state *rs = get_remote_state ();
2138 /* Check if this is a thread that we made up ourselves to model
2139 non-threaded targets as single-threaded. */
2140 if (remote_thread_always_alive (ops, ptid))
2144 endp = rs->buf + get_remote_packet_size ();
2147 write_ptid (p, endp, ptid);
2150 getpkt (&rs->buf, &rs->buf_size, 0);
2151 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2154 /* Return a pointer to a thread name if we know it and NULL otherwise.
2155 The thread_info object owns the memory for the name. */
2158 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2160 if (info->priv != NULL)
2161 return info->priv->name;
2166 /* About these extended threadlist and threadinfo packets. They are
2167 variable length packets but, the fields within them are often fixed
2168 length. They are redundent enough to send over UDP as is the
2169 remote protocol in general. There is a matching unit test module
2172 /* WARNING: This threadref data structure comes from the remote O.S.,
2173 libstub protocol encoding, and remote.c. It is not particularly
2176 /* Right now, the internal structure is int. We want it to be bigger.
2177 Plan to fix this. */
2179 typedef int gdb_threadref; /* Internal GDB thread reference. */
2181 /* gdb_ext_thread_info is an internal GDB data structure which is
2182 equivalent to the reply of the remote threadinfo packet. */
2184 struct gdb_ext_thread_info
2186 threadref threadid; /* External form of thread reference. */
2187 int active; /* Has state interesting to GDB?
2189 char display[256]; /* Brief state display, name,
2190 blocked/suspended. */
2191 char shortname[32]; /* To be used to name threads. */
2192 char more_display[256]; /* Long info, statistics, queue depth,
2196 /* The volume of remote transfers can be limited by submitting
2197 a mask containing bits specifying the desired information.
2198 Use a union of these values as the 'selection' parameter to
2199 get_thread_info. FIXME: Make these TAG names more thread specific. */
2201 #define TAG_THREADID 1
2202 #define TAG_EXISTS 2
2203 #define TAG_DISPLAY 4
2204 #define TAG_THREADNAME 8
2205 #define TAG_MOREDISPLAY 16
2207 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2209 static char *unpack_nibble (char *buf, int *val);
2211 static char *unpack_byte (char *buf, int *value);
2213 static char *pack_int (char *buf, int value);
2215 static char *unpack_int (char *buf, int *value);
2217 static char *unpack_string (char *src, char *dest, int length);
2219 static char *pack_threadid (char *pkt, threadref *id);
2221 static char *unpack_threadid (char *inbuf, threadref *id);
2223 void int_to_threadref (threadref *id, int value);
2225 static int threadref_to_int (threadref *ref);
2227 static void copy_threadref (threadref *dest, threadref *src);
2229 static int threadmatch (threadref *dest, threadref *src);
2231 static char *pack_threadinfo_request (char *pkt, int mode,
2234 static int remote_unpack_thread_info_response (char *pkt,
2235 threadref *expectedref,
2236 struct gdb_ext_thread_info
2240 static int remote_get_threadinfo (threadref *threadid,
2241 int fieldset, /*TAG mask */
2242 struct gdb_ext_thread_info *info);
2244 static char *pack_threadlist_request (char *pkt, int startflag,
2246 threadref *nextthread);
2248 static int parse_threadlist_response (char *pkt,
2250 threadref *original_echo,
2251 threadref *resultlist,
2254 static int remote_get_threadlist (int startflag,
2255 threadref *nextthread,
2259 threadref *threadlist);
2261 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2263 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2264 void *context, int looplimit);
2266 static int remote_newthread_step (threadref *ref, void *context);
2269 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2270 buffer we're allowed to write to. Returns
2271 BUF+CHARACTERS_WRITTEN. */
2274 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2277 struct remote_state *rs = get_remote_state ();
2279 if (remote_multi_process_p (rs))
2281 pid = ptid_get_pid (ptid);
2283 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2285 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2287 tid = ptid_get_lwp (ptid);
2289 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2291 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2296 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2297 passed the last parsed char. Returns null_ptid on error. */
2300 read_ptid (char *buf, char **obuf)
2304 ULONGEST pid = 0, tid = 0;
2308 /* Multi-process ptid. */
2309 pp = unpack_varlen_hex (p + 1, &pid);
2311 error (_("invalid remote ptid: %s"), p);
2314 pp = unpack_varlen_hex (p + 1, &tid);
2317 return ptid_build (pid, tid, 0);
2320 /* No multi-process. Just a tid. */
2321 pp = unpack_varlen_hex (p, &tid);
2323 /* Return null_ptid when no thread id is found. */
2331 /* Since the stub is not sending a process id, then default to
2332 what's in inferior_ptid, unless it's null at this point. If so,
2333 then since there's no way to know the pid of the reported
2334 threads, use the magic number. */
2335 if (ptid_equal (inferior_ptid, null_ptid))
2336 pid = ptid_get_pid (magic_null_ptid);
2338 pid = ptid_get_pid (inferior_ptid);
2342 return ptid_build (pid, tid, 0);
2348 if (ch >= 'a' && ch <= 'f')
2349 return ch - 'a' + 10;
2350 if (ch >= '0' && ch <= '9')
2352 if (ch >= 'A' && ch <= 'F')
2353 return ch - 'A' + 10;
2358 stub_unpack_int (char *buff, int fieldlength)
2365 nibble = stubhex (*buff++);
2369 retval = retval << 4;
2375 unpack_nibble (char *buf, int *val)
2377 *val = fromhex (*buf++);
2382 unpack_byte (char *buf, int *value)
2384 *value = stub_unpack_int (buf, 2);
2389 pack_int (char *buf, int value)
2391 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2392 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2393 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2394 buf = pack_hex_byte (buf, (value & 0xff));
2399 unpack_int (char *buf, int *value)
2401 *value = stub_unpack_int (buf, 8);
2405 #if 0 /* Currently unused, uncomment when needed. */
2406 static char *pack_string (char *pkt, char *string);
2409 pack_string (char *pkt, char *string)
2414 len = strlen (string);
2416 len = 200; /* Bigger than most GDB packets, junk??? */
2417 pkt = pack_hex_byte (pkt, len);
2421 if ((ch == '\0') || (ch == '#'))
2422 ch = '*'; /* Protect encapsulation. */
2427 #endif /* 0 (unused) */
2430 unpack_string (char *src, char *dest, int length)
2439 pack_threadid (char *pkt, threadref *id)
2442 unsigned char *altid;
2444 altid = (unsigned char *) id;
2445 limit = pkt + BUF_THREAD_ID_SIZE;
2447 pkt = pack_hex_byte (pkt, *altid++);
2453 unpack_threadid (char *inbuf, threadref *id)
2456 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2459 altref = (char *) id;
2461 while (inbuf < limit)
2463 x = stubhex (*inbuf++);
2464 y = stubhex (*inbuf++);
2465 *altref++ = (x << 4) | y;
2470 /* Externally, threadrefs are 64 bits but internally, they are still
2471 ints. This is due to a mismatch of specifications. We would like
2472 to use 64bit thread references internally. This is an adapter
2476 int_to_threadref (threadref *id, int value)
2478 unsigned char *scan;
2480 scan = (unsigned char *) id;
2486 *scan++ = (value >> 24) & 0xff;
2487 *scan++ = (value >> 16) & 0xff;
2488 *scan++ = (value >> 8) & 0xff;
2489 *scan++ = (value & 0xff);
2493 threadref_to_int (threadref *ref)
2496 unsigned char *scan;
2502 value = (value << 8) | ((*scan++) & 0xff);
2507 copy_threadref (threadref *dest, threadref *src)
2510 unsigned char *csrc, *cdest;
2512 csrc = (unsigned char *) src;
2513 cdest = (unsigned char *) dest;
2520 threadmatch (threadref *dest, threadref *src)
2522 /* Things are broken right now, so just assume we got a match. */
2524 unsigned char *srcp, *destp;
2526 srcp = (char *) src;
2527 destp = (char *) dest;
2531 result &= (*srcp++ == *destp++) ? 1 : 0;
2538 threadid:1, # always request threadid
2545 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2548 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2550 *pkt++ = 'q'; /* Info Query */
2551 *pkt++ = 'P'; /* process or thread info */
2552 pkt = pack_int (pkt, mode); /* mode */
2553 pkt = pack_threadid (pkt, id); /* threadid */
2554 *pkt = '\0'; /* terminate */
2558 /* These values tag the fields in a thread info response packet. */
2559 /* Tagging the fields allows us to request specific fields and to
2560 add more fields as time goes by. */
2562 #define TAG_THREADID 1 /* Echo the thread identifier. */
2563 #define TAG_EXISTS 2 /* Is this process defined enough to
2564 fetch registers and its stack? */
2565 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2566 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2567 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2571 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2572 struct gdb_ext_thread_info *info)
2574 struct remote_state *rs = get_remote_state ();
2578 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2581 /* info->threadid = 0; FIXME: implement zero_threadref. */
2583 info->display[0] = '\0';
2584 info->shortname[0] = '\0';
2585 info->more_display[0] = '\0';
2587 /* Assume the characters indicating the packet type have been
2589 pkt = unpack_int (pkt, &mask); /* arg mask */
2590 pkt = unpack_threadid (pkt, &ref);
2593 warning (_("Incomplete response to threadinfo request."));
2594 if (!threadmatch (&ref, expectedref))
2595 { /* This is an answer to a different request. */
2596 warning (_("ERROR RMT Thread info mismatch."));
2599 copy_threadref (&info->threadid, &ref);
2601 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2603 /* Packets are terminated with nulls. */
2604 while ((pkt < limit) && mask && *pkt)
2606 pkt = unpack_int (pkt, &tag); /* tag */
2607 pkt = unpack_byte (pkt, &length); /* length */
2608 if (!(tag & mask)) /* Tags out of synch with mask. */
2610 warning (_("ERROR RMT: threadinfo tag mismatch."));
2614 if (tag == TAG_THREADID)
2618 warning (_("ERROR RMT: length of threadid is not 16."));
2622 pkt = unpack_threadid (pkt, &ref);
2623 mask = mask & ~TAG_THREADID;
2626 if (tag == TAG_EXISTS)
2628 info->active = stub_unpack_int (pkt, length);
2630 mask = mask & ~(TAG_EXISTS);
2633 warning (_("ERROR RMT: 'exists' length too long."));
2639 if (tag == TAG_THREADNAME)
2641 pkt = unpack_string (pkt, &info->shortname[0], length);
2642 mask = mask & ~TAG_THREADNAME;
2645 if (tag == TAG_DISPLAY)
2647 pkt = unpack_string (pkt, &info->display[0], length);
2648 mask = mask & ~TAG_DISPLAY;
2651 if (tag == TAG_MOREDISPLAY)
2653 pkt = unpack_string (pkt, &info->more_display[0], length);
2654 mask = mask & ~TAG_MOREDISPLAY;
2657 warning (_("ERROR RMT: unknown thread info tag."));
2658 break; /* Not a tag we know about. */
2664 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2665 struct gdb_ext_thread_info *info)
2667 struct remote_state *rs = get_remote_state ();
2670 pack_threadinfo_request (rs->buf, fieldset, threadid);
2672 getpkt (&rs->buf, &rs->buf_size, 0);
2674 if (rs->buf[0] == '\0')
2677 result = remote_unpack_thread_info_response (rs->buf + 2,
2682 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2685 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2686 threadref *nextthread)
2688 *pkt++ = 'q'; /* info query packet */
2689 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2690 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2691 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2692 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2697 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2700 parse_threadlist_response (char *pkt, int result_limit,
2701 threadref *original_echo, threadref *resultlist,
2704 struct remote_state *rs = get_remote_state ();
2706 int count, resultcount, done;
2709 /* Assume the 'q' and 'M chars have been stripped. */
2710 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2711 /* done parse past here */
2712 pkt = unpack_byte (pkt, &count); /* count field */
2713 pkt = unpack_nibble (pkt, &done);
2714 /* The first threadid is the argument threadid. */
2715 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2716 while ((count-- > 0) && (pkt < limit))
2718 pkt = unpack_threadid (pkt, resultlist++);
2719 if (resultcount++ >= result_limit)
2727 /* Fetch the next batch of threads from the remote. Returns -1 if the
2728 qL packet is not supported, 0 on error and 1 on success. */
2731 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2732 int *done, int *result_count, threadref *threadlist)
2734 struct remote_state *rs = get_remote_state ();
2737 /* Trancate result limit to be smaller than the packet size. */
2738 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2739 >= get_remote_packet_size ())
2740 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2742 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2744 getpkt (&rs->buf, &rs->buf_size, 0);
2745 if (*rs->buf == '\0')
2747 /* Packet not supported. */
2752 parse_threadlist_response (rs->buf + 2, result_limit,
2753 &rs->echo_nextthread, threadlist, done);
2755 if (!threadmatch (&rs->echo_nextthread, nextthread))
2757 /* FIXME: This is a good reason to drop the packet. */
2758 /* Possably, there is a duplicate response. */
2760 retransmit immediatly - race conditions
2761 retransmit after timeout - yes
2763 wait for packet, then exit
2765 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2766 return 0; /* I choose simply exiting. */
2768 if (*result_count <= 0)
2772 warning (_("RMT ERROR : failed to get remote thread list."));
2775 return result; /* break; */
2777 if (*result_count > result_limit)
2780 warning (_("RMT ERROR: threadlist response longer than requested."));
2786 /* Fetch the list of remote threads, with the qL packet, and call
2787 STEPFUNCTION for each thread found. Stops iterating and returns 1
2788 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2789 STEPFUNCTION returns false. If the packet is not supported,
2793 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2796 struct remote_state *rs = get_remote_state ();
2797 int done, i, result_count;
2805 if (loopcount++ > looplimit)
2808 warning (_("Remote fetch threadlist -infinite loop-."));
2811 result = remote_get_threadlist (startflag, &rs->nextthread,
2812 MAXTHREADLISTRESULTS,
2813 &done, &result_count,
2814 rs->resultthreadlist);
2817 /* Clear for later iterations. */
2819 /* Setup to resume next batch of thread references, set nextthread. */
2820 if (result_count >= 1)
2821 copy_threadref (&rs->nextthread,
2822 &rs->resultthreadlist[result_count - 1]);
2824 while (result_count--)
2826 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2836 /* A thread found on the remote target. */
2838 typedef struct thread_item
2840 /* The thread's PTID. */
2843 /* The thread's extra info. May be NULL. */
2846 /* The thread's name. May be NULL. */
2849 /* The core the thread was running on. -1 if not known. */
2852 DEF_VEC_O(thread_item_t);
2854 /* Context passed around to the various methods listing remote
2855 threads. As new threads are found, they're added to the ITEMS
2858 struct threads_listing_context
2860 /* The threads found on the remote target. */
2861 VEC (thread_item_t) *items;
2864 /* Discard the contents of the constructed thread listing context. */
2867 clear_threads_listing_context (void *p)
2869 struct threads_listing_context *context
2870 = (struct threads_listing_context *) p;
2872 struct thread_item *item;
2874 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2876 xfree (item->extra);
2880 VEC_free (thread_item_t, context->items);
2883 /* Remove the thread specified as the related_pid field of WS
2884 from the CONTEXT list. */
2887 threads_listing_context_remove (struct target_waitstatus *ws,
2888 struct threads_listing_context *context)
2890 struct thread_item *item;
2892 ptid_t child_ptid = ws->value.related_pid;
2894 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2896 if (ptid_equal (item->ptid, child_ptid))
2898 VEC_ordered_remove (thread_item_t, context->items, i);
2905 remote_newthread_step (threadref *ref, void *data)
2907 struct threads_listing_context *context
2908 = (struct threads_listing_context *) data;
2909 struct thread_item item;
2910 int pid = ptid_get_pid (inferior_ptid);
2912 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2916 VEC_safe_push (thread_item_t, context->items, &item);
2918 return 1; /* continue iterator */
2921 #define CRAZY_MAX_THREADS 1000
2924 remote_current_thread (ptid_t oldpid)
2926 struct remote_state *rs = get_remote_state ();
2929 getpkt (&rs->buf, &rs->buf_size, 0);
2930 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2935 result = read_ptid (&rs->buf[2], &obuf);
2936 if (*obuf != '\0' && remote_debug)
2937 fprintf_unfiltered (gdb_stdlog,
2938 "warning: garbage in qC reply\n");
2946 /* List remote threads using the deprecated qL packet. */
2949 remote_get_threads_with_ql (struct target_ops *ops,
2950 struct threads_listing_context *context)
2952 if (remote_threadlist_iterator (remote_newthread_step, context,
2953 CRAZY_MAX_THREADS) >= 0)
2959 #if defined(HAVE_LIBEXPAT)
2962 start_thread (struct gdb_xml_parser *parser,
2963 const struct gdb_xml_element *element,
2964 void *user_data, VEC(gdb_xml_value_s) *attributes)
2966 struct threads_listing_context *data
2967 = (struct threads_listing_context *) user_data;
2969 struct thread_item item;
2971 struct gdb_xml_value *attr;
2973 id = (char *) xml_find_attribute (attributes, "id")->value;
2974 item.ptid = read_ptid (id, NULL);
2976 attr = xml_find_attribute (attributes, "core");
2978 item.core = *(ULONGEST *) attr->value;
2982 attr = xml_find_attribute (attributes, "name");
2983 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
2987 VEC_safe_push (thread_item_t, data->items, &item);
2991 end_thread (struct gdb_xml_parser *parser,
2992 const struct gdb_xml_element *element,
2993 void *user_data, const char *body_text)
2995 struct threads_listing_context *data
2996 = (struct threads_listing_context *) user_data;
2998 if (body_text && *body_text)
2999 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3002 const struct gdb_xml_attribute thread_attributes[] = {
3003 { "id", GDB_XML_AF_NONE, NULL, NULL },
3004 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3005 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3006 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3009 const struct gdb_xml_element thread_children[] = {
3010 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3013 const struct gdb_xml_element threads_children[] = {
3014 { "thread", thread_attributes, thread_children,
3015 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3016 start_thread, end_thread },
3017 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3020 const struct gdb_xml_element threads_elements[] = {
3021 { "threads", NULL, threads_children,
3022 GDB_XML_EF_NONE, NULL, NULL },
3023 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3028 /* List remote threads using qXfer:threads:read. */
3031 remote_get_threads_with_qxfer (struct target_ops *ops,
3032 struct threads_listing_context *context)
3034 #if defined(HAVE_LIBEXPAT)
3035 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3037 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3038 struct cleanup *back_to = make_cleanup (xfree, xml);
3040 if (xml != NULL && *xml != '\0')
3042 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3043 threads_elements, xml, context);
3046 do_cleanups (back_to);
3054 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3057 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3058 struct threads_listing_context *context)
3060 struct remote_state *rs = get_remote_state ();
3062 if (rs->use_threadinfo_query)
3066 putpkt ("qfThreadInfo");
3067 getpkt (&rs->buf, &rs->buf_size, 0);
3069 if (bufp[0] != '\0') /* q packet recognized */
3071 while (*bufp++ == 'm') /* reply contains one or more TID */
3075 struct thread_item item;
3077 item.ptid = read_ptid (bufp, &bufp);
3081 VEC_safe_push (thread_item_t, context->items, &item);
3083 while (*bufp++ == ','); /* comma-separated list */
3084 putpkt ("qsThreadInfo");
3085 getpkt (&rs->buf, &rs->buf_size, 0);
3092 /* Packet not recognized. */
3093 rs->use_threadinfo_query = 0;
3100 /* Implement the to_update_thread_list function for the remote
3104 remote_update_thread_list (struct target_ops *ops)
3106 struct remote_state *rs = get_remote_state ();
3107 struct threads_listing_context context;
3108 struct cleanup *old_chain;
3111 context.items = NULL;
3112 old_chain = make_cleanup (clear_threads_listing_context, &context);
3114 /* We have a few different mechanisms to fetch the thread list. Try
3115 them all, starting with the most preferred one first, falling
3116 back to older methods. */
3117 if (remote_get_threads_with_qxfer (ops, &context)
3118 || remote_get_threads_with_qthreadinfo (ops, &context)
3119 || remote_get_threads_with_ql (ops, &context))
3122 struct thread_item *item;
3123 struct thread_info *tp, *tmp;
3127 if (VEC_empty (thread_item_t, context.items)
3128 && remote_thread_always_alive (ops, inferior_ptid))
3130 /* Some targets don't really support threads, but still
3131 reply an (empty) thread list in response to the thread
3132 listing packets, instead of replying "packet not
3133 supported". Exit early so we don't delete the main
3135 do_cleanups (old_chain);
3139 /* CONTEXT now holds the current thread list on the remote
3140 target end. Delete GDB-side threads no longer found on the
3142 ALL_THREADS_SAFE (tp, tmp)
3145 VEC_iterate (thread_item_t, context.items, i, item);
3148 if (ptid_equal (item->ptid, tp->ptid))
3152 if (i == VEC_length (thread_item_t, context.items))
3155 delete_thread (tp->ptid);
3159 /* Remove any unreported fork child threads from CONTEXT so
3160 that we don't interfere with follow fork, which is where
3161 creation of such threads is handled. */
3162 remove_new_fork_children (&context);
3164 /* And now add threads we don't know about yet to our list. */
3166 VEC_iterate (thread_item_t, context.items, i, item);
3169 if (!ptid_equal (item->ptid, null_ptid))
3171 struct private_thread_info *info;
3172 /* In non-stop mode, we assume new found threads are
3173 running until proven otherwise with a stop reply. In
3174 all-stop, we can only get here if all threads are
3176 int running = target_is_non_stop_p () ? 1 : 0;
3178 remote_notice_new_inferior (item->ptid, running);
3180 info = demand_private_info (item->ptid);
3181 info->core = item->core;
3182 info->extra = item->extra;
3184 info->name = item->name;
3192 /* If no thread listing method is supported, then query whether
3193 each known thread is alive, one by one, with the T packet.
3194 If the target doesn't support threads at all, then this is a
3195 no-op. See remote_thread_alive. */
3199 do_cleanups (old_chain);
3203 * Collect a descriptive string about the given thread.
3204 * The target may say anything it wants to about the thread
3205 * (typically info about its blocked / runnable state, name, etc.).
3206 * This string will appear in the info threads display.
3208 * Optional: targets are not required to implement this function.
3212 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3214 struct remote_state *rs = get_remote_state ();
3218 struct gdb_ext_thread_info threadinfo;
3219 static char display_buf[100]; /* arbitrary... */
3220 int n = 0; /* position in display_buf */
3222 if (rs->remote_desc == 0) /* paranoia */
3223 internal_error (__FILE__, __LINE__,
3224 _("remote_threads_extra_info"));
3226 if (ptid_equal (tp->ptid, magic_null_ptid)
3227 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3228 /* This is the main thread which was added by GDB. The remote
3229 server doesn't know about it. */
3232 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3234 struct thread_info *info = find_thread_ptid (tp->ptid);
3236 if (info && info->priv)
3237 return info->priv->extra;
3242 if (rs->use_threadextra_query)
3245 char *endb = rs->buf + get_remote_packet_size ();
3247 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3249 write_ptid (b, endb, tp->ptid);
3252 getpkt (&rs->buf, &rs->buf_size, 0);
3253 if (rs->buf[0] != 0)
3255 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3256 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3257 display_buf [result] = '\0';
3262 /* If the above query fails, fall back to the old method. */
3263 rs->use_threadextra_query = 0;
3264 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3265 | TAG_MOREDISPLAY | TAG_DISPLAY;
3266 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3267 if (remote_get_threadinfo (&id, set, &threadinfo))
3268 if (threadinfo.active)
3270 if (*threadinfo.shortname)
3271 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3272 " Name: %s,", threadinfo.shortname);
3273 if (*threadinfo.display)
3274 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3275 " State: %s,", threadinfo.display);
3276 if (*threadinfo.more_display)
3277 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3278 " Priority: %s", threadinfo.more_display);
3282 /* For purely cosmetic reasons, clear up trailing commas. */
3283 if (',' == display_buf[n-1])
3284 display_buf[n-1] = ' ';
3293 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3294 struct static_tracepoint_marker *marker)
3296 struct remote_state *rs = get_remote_state ();
3299 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3301 p += hexnumstr (p, addr);
3303 getpkt (&rs->buf, &rs->buf_size, 0);
3307 error (_("Remote failure reply: %s"), p);
3311 parse_static_tracepoint_marker_definition (p, &p, marker);
3318 static VEC(static_tracepoint_marker_p) *
3319 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3322 struct remote_state *rs = get_remote_state ();
3323 VEC(static_tracepoint_marker_p) *markers = NULL;
3324 struct static_tracepoint_marker *marker = NULL;
3325 struct cleanup *old_chain;
3328 /* Ask for a first packet of static tracepoint marker
3331 getpkt (&rs->buf, &rs->buf_size, 0);
3334 error (_("Remote failure reply: %s"), p);
3336 old_chain = make_cleanup (free_current_marker, &marker);
3341 marker = XCNEW (struct static_tracepoint_marker);
3345 parse_static_tracepoint_marker_definition (p, &p, marker);
3347 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3349 VEC_safe_push (static_tracepoint_marker_p,
3355 release_static_tracepoint_marker (marker);
3356 memset (marker, 0, sizeof (*marker));
3359 while (*p++ == ','); /* comma-separated list */
3360 /* Ask for another packet of static tracepoint definition. */
3362 getpkt (&rs->buf, &rs->buf_size, 0);
3366 do_cleanups (old_chain);
3371 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3374 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3376 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3380 /* Restart the remote side; this is an extended protocol operation. */
3383 extended_remote_restart (void)
3385 struct remote_state *rs = get_remote_state ();
3387 /* Send the restart command; for reasons I don't understand the
3388 remote side really expects a number after the "R". */
3389 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3392 remote_fileio_reset ();
3395 /* Clean up connection to a remote debugger. */
3398 remote_close (struct target_ops *self)
3400 struct remote_state *rs = get_remote_state ();
3402 if (rs->remote_desc == NULL)
3403 return; /* already closed */
3405 /* Make sure we leave stdin registered in the event loop, and we
3406 don't leave the async SIGINT signal handler installed. */
3407 remote_terminal_ours (self);
3409 serial_close (rs->remote_desc);
3410 rs->remote_desc = NULL;
3412 /* We don't have a connection to the remote stub anymore. Get rid
3413 of all the inferiors and their threads we were controlling.
3414 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3415 will be unable to find the thread corresponding to (pid, 0, 0). */
3416 inferior_ptid = null_ptid;
3417 discard_all_inferiors ();
3419 /* We are closing the remote target, so we should discard
3420 everything of this target. */
3421 discard_pending_stop_replies_in_queue (rs);
3423 if (remote_async_inferior_event_token)
3424 delete_async_event_handler (&remote_async_inferior_event_token);
3426 remote_notif_state_xfree (rs->notif_state);
3428 trace_reset_local_state ();
3431 /* Query the remote side for the text, data and bss offsets. */
3436 struct remote_state *rs = get_remote_state ();
3439 int lose, num_segments = 0, do_sections, do_segments;
3440 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3441 struct section_offsets *offs;
3442 struct symfile_segment_data *data;
3444 if (symfile_objfile == NULL)
3447 putpkt ("qOffsets");
3448 getpkt (&rs->buf, &rs->buf_size, 0);
3451 if (buf[0] == '\000')
3452 return; /* Return silently. Stub doesn't support
3456 warning (_("Remote failure reply: %s"), buf);
3460 /* Pick up each field in turn. This used to be done with scanf, but
3461 scanf will make trouble if CORE_ADDR size doesn't match
3462 conversion directives correctly. The following code will work
3463 with any size of CORE_ADDR. */
3464 text_addr = data_addr = bss_addr = 0;
3468 if (startswith (ptr, "Text="))
3471 /* Don't use strtol, could lose on big values. */
3472 while (*ptr && *ptr != ';')
3473 text_addr = (text_addr << 4) + fromhex (*ptr++);
3475 if (startswith (ptr, ";Data="))
3478 while (*ptr && *ptr != ';')
3479 data_addr = (data_addr << 4) + fromhex (*ptr++);
3484 if (!lose && startswith (ptr, ";Bss="))
3487 while (*ptr && *ptr != ';')
3488 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3490 if (bss_addr != data_addr)
3491 warning (_("Target reported unsupported offsets: %s"), buf);
3496 else if (startswith (ptr, "TextSeg="))
3499 /* Don't use strtol, could lose on big values. */
3500 while (*ptr && *ptr != ';')
3501 text_addr = (text_addr << 4) + fromhex (*ptr++);
3504 if (startswith (ptr, ";DataSeg="))
3507 while (*ptr && *ptr != ';')
3508 data_addr = (data_addr << 4) + fromhex (*ptr++);
3516 error (_("Malformed response to offset query, %s"), buf);
3517 else if (*ptr != '\0')
3518 warning (_("Target reported unsupported offsets: %s"), buf);
3520 offs = ((struct section_offsets *)
3521 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3522 memcpy (offs, symfile_objfile->section_offsets,
3523 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3525 data = get_symfile_segment_data (symfile_objfile->obfd);
3526 do_segments = (data != NULL);
3527 do_sections = num_segments == 0;
3529 if (num_segments > 0)
3531 segments[0] = text_addr;
3532 segments[1] = data_addr;
3534 /* If we have two segments, we can still try to relocate everything
3535 by assuming that the .text and .data offsets apply to the whole
3536 text and data segments. Convert the offsets given in the packet
3537 to base addresses for symfile_map_offsets_to_segments. */
3538 else if (data && data->num_segments == 2)
3540 segments[0] = data->segment_bases[0] + text_addr;
3541 segments[1] = data->segment_bases[1] + data_addr;
3544 /* If the object file has only one segment, assume that it is text
3545 rather than data; main programs with no writable data are rare,
3546 but programs with no code are useless. Of course the code might
3547 have ended up in the data segment... to detect that we would need
3548 the permissions here. */
3549 else if (data && data->num_segments == 1)
3551 segments[0] = data->segment_bases[0] + text_addr;
3554 /* There's no way to relocate by segment. */
3560 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3561 offs, num_segments, segments);
3563 if (ret == 0 && !do_sections)
3564 error (_("Can not handle qOffsets TextSeg "
3565 "response with this symbol file"));
3572 free_symfile_segment_data (data);
3576 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3578 /* This is a temporary kludge to force data and bss to use the
3579 same offsets because that's what nlmconv does now. The real
3580 solution requires changes to the stub and remote.c that I
3581 don't have time to do right now. */
3583 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3584 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3587 objfile_relocate (symfile_objfile, offs);
3590 /* Send interrupt_sequence to remote target. */
3592 send_interrupt_sequence (void)
3594 struct remote_state *rs = get_remote_state ();
3596 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3597 remote_serial_write ("\x03", 1);
3598 else if (interrupt_sequence_mode == interrupt_sequence_break)
3599 serial_send_break (rs->remote_desc);
3600 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3602 serial_send_break (rs->remote_desc);
3603 remote_serial_write ("g", 1);
3606 internal_error (__FILE__, __LINE__,
3607 _("Invalid value for interrupt_sequence_mode: %s."),
3608 interrupt_sequence_mode);
3612 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3613 and extract the PTID. Returns NULL_PTID if not found. */
3616 stop_reply_extract_thread (char *stop_reply)
3618 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3622 /* Txx r:val ; r:val (...) */
3625 /* Look for "register" named "thread". */
3630 p1 = strchr (p, ':');
3634 if (strncmp (p, "thread", p1 - p) == 0)
3635 return read_ptid (++p1, &p);
3637 p1 = strchr (p, ';');
3649 /* Determine the remote side's current thread. If we have a stop
3650 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3651 "thread" register we can extract the current thread from. If not,
3652 ask the remote which is the current thread with qC. The former
3653 method avoids a roundtrip. */
3656 get_current_thread (char *wait_status)
3658 ptid_t ptid = null_ptid;
3660 /* Note we don't use remote_parse_stop_reply as that makes use of
3661 the target architecture, which we haven't yet fully determined at
3663 if (wait_status != NULL)
3664 ptid = stop_reply_extract_thread (wait_status);
3665 if (ptid_equal (ptid, null_ptid))
3666 ptid = remote_current_thread (inferior_ptid);
3671 /* Query the remote target for which is the current thread/process,
3672 add it to our tables, and update INFERIOR_PTID. The caller is
3673 responsible for setting the state such that the remote end is ready
3674 to return the current thread.
3676 This function is called after handling the '?' or 'vRun' packets,
3677 whose response is a stop reply from which we can also try
3678 extracting the thread. If the target doesn't support the explicit
3679 qC query, we infer the current thread from that stop reply, passed
3680 in in WAIT_STATUS, which may be NULL. */
3683 add_current_inferior_and_thread (char *wait_status)
3685 struct remote_state *rs = get_remote_state ();
3689 inferior_ptid = null_ptid;
3691 /* Now, if we have thread information, update inferior_ptid. */
3692 ptid = get_current_thread (wait_status);
3694 if (!ptid_equal (ptid, null_ptid))
3696 if (!remote_multi_process_p (rs))
3699 inferior_ptid = ptid;
3703 /* Without this, some commands which require an active target
3704 (such as kill) won't work. This variable serves (at least)
3705 double duty as both the pid of the target process (if it has
3706 such), and as a flag indicating that a target is active. */
3707 inferior_ptid = magic_null_ptid;
3711 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3713 /* Add the main thread. */
3714 add_thread_silent (inferior_ptid);
3717 /* Print info about a thread that was found already stopped on
3721 print_one_stopped_thread (struct thread_info *thread)
3723 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3725 switch_to_thread (thread->ptid);
3726 stop_pc = get_frame_pc (get_current_frame ());
3727 set_current_sal_from_frame (get_current_frame ());
3729 thread->suspend.waitstatus_pending_p = 0;
3731 if (ws->kind == TARGET_WAITKIND_STOPPED)
3733 enum gdb_signal sig = ws->value.sig;
3735 if (signal_print_state (sig))
3736 observer_notify_signal_received (sig);
3738 observer_notify_normal_stop (NULL, 1);
3741 /* Process all initial stop replies the remote side sent in response
3742 to the ? packet. These indicate threads that were already stopped
3743 on initial connection. We mark these threads as stopped and print
3744 their current frame before giving the user the prompt. */
3747 process_initial_stop_replies (int from_tty)
3749 int pending_stop_replies = stop_reply_queue_length ();
3750 struct inferior *inf;
3751 struct thread_info *thread;
3752 struct thread_info *selected = NULL;
3753 struct thread_info *lowest_stopped = NULL;
3754 struct thread_info *first = NULL;
3756 /* Consume the initial pending events. */
3757 while (pending_stop_replies-- > 0)
3759 ptid_t waiton_ptid = minus_one_ptid;
3761 struct target_waitstatus ws;
3762 int ignore_event = 0;
3763 struct thread_info *thread;
3765 memset (&ws, 0, sizeof (ws));
3766 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3768 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3772 case TARGET_WAITKIND_IGNORE:
3773 case TARGET_WAITKIND_NO_RESUMED:
3774 case TARGET_WAITKIND_SIGNALLED:
3775 case TARGET_WAITKIND_EXITED:
3776 /* We shouldn't see these, but if we do, just ignore. */
3778 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3782 case TARGET_WAITKIND_EXECD:
3783 xfree (ws.value.execd_pathname);
3792 thread = find_thread_ptid (event_ptid);
3794 if (ws.kind == TARGET_WAITKIND_STOPPED)
3796 enum gdb_signal sig = ws.value.sig;
3798 /* Stubs traditionally report SIGTRAP as initial signal,
3799 instead of signal 0. Suppress it. */
3800 if (sig == GDB_SIGNAL_TRAP)
3802 thread->suspend.stop_signal = sig;
3806 thread->suspend.waitstatus = ws;
3808 if (ws.kind != TARGET_WAITKIND_STOPPED
3809 || ws.value.sig != GDB_SIGNAL_0)
3810 thread->suspend.waitstatus_pending_p = 1;
3812 set_executing (event_ptid, 0);
3813 set_running (event_ptid, 0);
3816 /* "Notice" the new inferiors before anything related to
3817 registers/memory. */
3823 inf->needs_setup = 1;
3827 thread = any_live_thread_of_process (inf->pid);
3828 notice_new_inferior (thread->ptid,
3829 thread->state == THREAD_RUNNING,
3834 /* If all-stop on top of non-stop, pause all threads. Note this
3835 records the threads' stop pc, so must be done after "noticing"
3839 stop_all_threads ();
3841 /* If all threads of an inferior were already stopped, we
3842 haven't setup the inferior yet. */
3848 if (inf->needs_setup)
3850 thread = any_live_thread_of_process (inf->pid);
3851 switch_to_thread_no_regs (thread);
3857 /* Now go over all threads that are stopped, and print their current
3858 frame. If all-stop, then if there's a signalled thread, pick
3860 ALL_NON_EXITED_THREADS (thread)
3862 struct target_waitstatus *ws;
3868 set_running (thread->ptid, 0);
3869 else if (thread->state != THREAD_STOPPED)
3872 ws = &thread->suspend.waitstatus;
3874 if (selected == NULL
3875 && thread->suspend.waitstatus_pending_p)
3878 if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3879 lowest_stopped = thread;
3882 print_one_stopped_thread (thread);
3885 /* In all-stop, we only print the status of one thread, and leave
3886 others with their status pending. */
3891 thread = lowest_stopped;
3895 print_one_stopped_thread (thread);
3898 /* For "info program". */
3899 thread = inferior_thread ();
3900 if (thread->state == THREAD_STOPPED)
3901 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3905 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3907 struct remote_state *rs = get_remote_state ();
3908 struct packet_config *noack_config;
3909 char *wait_status = NULL;
3911 immediate_quit++; /* Allow user to interrupt it. */
3914 if (interrupt_on_connect)
3915 send_interrupt_sequence ();
3917 /* Ack any packet which the remote side has already sent. */
3918 serial_write (rs->remote_desc, "+", 1);
3920 /* Signal other parts that we're going through the initial setup,
3921 and so things may not be stable yet. */
3922 rs->starting_up = 1;
3924 /* The first packet we send to the target is the optional "supported
3925 packets" request. If the target can answer this, it will tell us
3926 which later probes to skip. */
3927 remote_query_supported ();
3929 /* If the stub wants to get a QAllow, compose one and send it. */
3930 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3931 remote_set_permissions (target);
3933 /* Next, we possibly activate noack mode.
3935 If the QStartNoAckMode packet configuration is set to AUTO,
3936 enable noack mode if the stub reported a wish for it with
3939 If set to TRUE, then enable noack mode even if the stub didn't
3940 report it in qSupported. If the stub doesn't reply OK, the
3941 session ends with an error.
3943 If FALSE, then don't activate noack mode, regardless of what the
3944 stub claimed should be the default with qSupported. */
3946 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3947 if (packet_config_support (noack_config) != PACKET_DISABLE)
3949 putpkt ("QStartNoAckMode");
3950 getpkt (&rs->buf, &rs->buf_size, 0);
3951 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3957 /* Tell the remote that we are using the extended protocol. */
3959 getpkt (&rs->buf, &rs->buf_size, 0);
3962 /* Let the target know which signals it is allowed to pass down to
3964 update_signals_program_target ();
3966 /* Next, if the target can specify a description, read it. We do
3967 this before anything involving memory or registers. */
3968 target_find_description ();
3970 /* Next, now that we know something about the target, update the
3971 address spaces in the program spaces. */
3972 update_address_spaces ();
3974 /* On OSs where the list of libraries is global to all
3975 processes, we fetch them early. */
3976 if (gdbarch_has_global_solist (target_gdbarch ()))
3977 solib_add (NULL, from_tty, target, auto_solib_add);
3979 if (target_is_non_stop_p ())
3981 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3982 error (_("Non-stop mode requested, but remote "
3983 "does not support non-stop"));
3985 putpkt ("QNonStop:1");
3986 getpkt (&rs->buf, &rs->buf_size, 0);
3988 if (strcmp (rs->buf, "OK") != 0)
3989 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3991 /* Find about threads and processes the stub is already
3992 controlling. We default to adding them in the running state.
3993 The '?' query below will then tell us about which threads are
3995 remote_update_thread_list (target);
3997 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3999 /* Don't assume that the stub can operate in all-stop mode.
4000 Request it explicitly. */
4001 putpkt ("QNonStop:0");
4002 getpkt (&rs->buf, &rs->buf_size, 0);
4004 if (strcmp (rs->buf, "OK") != 0)
4005 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4008 /* Upload TSVs regardless of whether the target is running or not. The
4009 remote stub, such as GDBserver, may have some predefined or builtin
4010 TSVs, even if the target is not running. */
4011 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4013 struct uploaded_tsv *uploaded_tsvs = NULL;
4015 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4016 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4019 /* Check whether the target is running now. */
4021 getpkt (&rs->buf, &rs->buf_size, 0);
4023 if (!target_is_non_stop_p ())
4027 struct inferior *inf;
4029 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4032 error (_("The target is not running (try extended-remote?)"));
4034 /* We're connected, but not running. Drop out before we
4035 call start_remote. */
4036 rs->starting_up = 0;
4041 /* Save the reply for later. */
4042 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4043 strcpy (wait_status, rs->buf);
4046 /* Fetch thread list. */
4047 target_update_thread_list ();
4049 /* Let the stub know that we want it to return the thread. */
4050 set_continue_thread (minus_one_ptid);
4052 if (thread_count () == 0)
4054 /* Target has no concept of threads at all. GDB treats
4055 non-threaded target as single-threaded; add a main
4057 add_current_inferior_and_thread (wait_status);
4061 /* We have thread information; select the thread the target
4062 says should be current. If we're reconnecting to a
4063 multi-threaded program, this will ideally be the thread
4064 that last reported an event before GDB disconnected. */
4065 inferior_ptid = get_current_thread (wait_status);
4066 if (ptid_equal (inferior_ptid, null_ptid))
4068 /* Odd... The target was able to list threads, but not
4069 tell us which thread was current (no "thread"
4070 register in T stop reply?). Just pick the first
4071 thread in the thread list then. */
4074 fprintf_unfiltered (gdb_stdlog,
4075 "warning: couldn't determine remote "
4076 "current thread; picking first in list.\n");
4078 inferior_ptid = thread_list->ptid;
4082 /* init_wait_for_inferior should be called before get_offsets in order
4083 to manage `inserted' flag in bp loc in a correct state.
4084 breakpoint_init_inferior, called from init_wait_for_inferior, set
4085 `inserted' flag to 0, while before breakpoint_re_set, called from
4086 start_remote, set `inserted' flag to 1. In the initialization of
4087 inferior, breakpoint_init_inferior should be called first, and then
4088 breakpoint_re_set can be called. If this order is broken, state of
4089 `inserted' flag is wrong, and cause some problems on breakpoint
4091 init_wait_for_inferior ();
4093 get_offsets (); /* Get text, data & bss offsets. */
4095 /* If we could not find a description using qXfer, and we know
4096 how to do it some other way, try again. This is not
4097 supported for non-stop; it could be, but it is tricky if
4098 there are no stopped threads when we connect. */
4099 if (remote_read_description_p (target)
4100 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4102 target_clear_description ();
4103 target_find_description ();
4106 /* Use the previously fetched status. */
4107 gdb_assert (wait_status != NULL);
4108 strcpy (rs->buf, wait_status);
4109 rs->cached_wait_status = 1;
4112 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4116 /* Clear WFI global state. Do this before finding about new
4117 threads and inferiors, and setting the current inferior.
4118 Otherwise we would clear the proceed status of the current
4119 inferior when we want its stop_soon state to be preserved
4120 (see notice_new_inferior). */
4121 init_wait_for_inferior ();
4123 /* In non-stop, we will either get an "OK", meaning that there
4124 are no stopped threads at this time; or, a regular stop
4125 reply. In the latter case, there may be more than one thread
4126 stopped --- we pull them all out using the vStopped
4128 if (strcmp (rs->buf, "OK") != 0)
4130 struct notif_client *notif = ¬if_client_stop;
4132 /* remote_notif_get_pending_replies acks this one, and gets
4134 rs->notif_state->pending_event[notif_client_stop.id]
4135 = remote_notif_parse (notif, rs->buf);
4136 remote_notif_get_pending_events (notif);
4139 if (thread_count () == 0)
4142 error (_("The target is not running (try extended-remote?)"));
4144 /* We're connected, but not running. Drop out before we
4145 call start_remote. */
4146 rs->starting_up = 0;
4150 /* In non-stop mode, any cached wait status will be stored in
4151 the stop reply queue. */
4152 gdb_assert (wait_status == NULL);
4154 /* Report all signals during attach/startup. */
4155 remote_pass_signals (target, 0, NULL);
4157 /* If there are already stopped threads, mark them stopped and
4158 report their stops before giving the prompt to the user. */
4159 process_initial_stop_replies (from_tty);
4161 if (target_can_async_p ())
4165 /* If we connected to a live target, do some additional setup. */
4166 if (target_has_execution)
4168 if (symfile_objfile) /* No use without a symbol-file. */
4169 remote_check_symbols ();
4172 /* Possibly the target has been engaged in a trace run started
4173 previously; find out where things are at. */
4174 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4176 struct uploaded_tp *uploaded_tps = NULL;
4178 if (current_trace_status ()->running)
4179 printf_filtered (_("Trace is already running on the target.\n"));
4181 remote_upload_tracepoints (target, &uploaded_tps);
4183 merge_uploaded_tracepoints (&uploaded_tps);
4186 /* The thread and inferior lists are now synchronized with the
4187 target, our symbols have been relocated, and we're merged the
4188 target's tracepoints with ours. We're done with basic start
4190 rs->starting_up = 0;
4192 /* Maybe breakpoints are global and need to be inserted now. */
4193 if (breakpoints_should_be_inserted_now ())
4194 insert_breakpoints ();
4197 /* Open a connection to a remote debugger.
4198 NAME is the filename used for communication. */
4201 remote_open (const char *name, int from_tty)
4203 remote_open_1 (name, from_tty, &remote_ops, 0);
4206 /* Open a connection to a remote debugger using the extended
4207 remote gdb protocol. NAME is the filename used for communication. */
4210 extended_remote_open (const char *name, int from_tty)
4212 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4215 /* Reset all packets back to "unknown support". Called when opening a
4216 new connection to a remote target. */
4219 reset_all_packet_configs_support (void)
4223 for (i = 0; i < PACKET_MAX; i++)
4224 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4227 /* Initialize all packet configs. */
4230 init_all_packet_configs (void)
4234 for (i = 0; i < PACKET_MAX; i++)
4236 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4237 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4241 /* Symbol look-up. */
4244 remote_check_symbols (void)
4246 struct remote_state *rs = get_remote_state ();
4247 char *msg, *reply, *tmp;
4248 struct bound_minimal_symbol sym;
4250 struct cleanup *old_chain;
4252 /* The remote side has no concept of inferiors that aren't running
4253 yet, it only knows about running processes. If we're connected
4254 but our current inferior is not running, we should not invite the
4255 remote target to request symbol lookups related to its
4256 (unrelated) current process. */
4257 if (!target_has_execution)
4260 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4263 /* Make sure the remote is pointing at the right process. Note
4264 there's no way to select "no process". */
4265 set_general_process ();
4267 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4268 because we need both at the same time. */
4269 msg = (char *) xmalloc (get_remote_packet_size ());
4270 old_chain = make_cleanup (xfree, msg);
4272 /* Invite target to request symbol lookups. */
4274 putpkt ("qSymbol::");
4275 getpkt (&rs->buf, &rs->buf_size, 0);
4276 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4279 while (startswith (reply, "qSymbol:"))
4281 struct bound_minimal_symbol sym;
4284 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4286 sym = lookup_minimal_symbol (msg, NULL, NULL);
4287 if (sym.minsym == NULL)
4288 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4291 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4292 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4294 /* If this is a function address, return the start of code
4295 instead of any data function descriptor. */
4296 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4300 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4301 phex_nz (sym_addr, addr_size), &reply[8]);
4305 getpkt (&rs->buf, &rs->buf_size, 0);
4309 do_cleanups (old_chain);
4312 static struct serial *
4313 remote_serial_open (const char *name)
4315 static int udp_warning = 0;
4317 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4318 of in ser-tcp.c, because it is the remote protocol assuming that the
4319 serial connection is reliable and not the serial connection promising
4321 if (!udp_warning && startswith (name, "udp:"))
4323 warning (_("The remote protocol may be unreliable over UDP.\n"
4324 "Some events may be lost, rendering further debugging "
4329 return serial_open (name);
4332 /* Inform the target of our permission settings. The permission flags
4333 work without this, but if the target knows the settings, it can do
4334 a couple things. First, it can add its own check, to catch cases
4335 that somehow manage to get by the permissions checks in target
4336 methods. Second, if the target is wired to disallow particular
4337 settings (for instance, a system in the field that is not set up to
4338 be able to stop at a breakpoint), it can object to any unavailable
4342 remote_set_permissions (struct target_ops *self)
4344 struct remote_state *rs = get_remote_state ();
4346 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4347 "WriteReg:%x;WriteMem:%x;"
4348 "InsertBreak:%x;InsertTrace:%x;"
4349 "InsertFastTrace:%x;Stop:%x",
4350 may_write_registers, may_write_memory,
4351 may_insert_breakpoints, may_insert_tracepoints,
4352 may_insert_fast_tracepoints, may_stop);
4354 getpkt (&rs->buf, &rs->buf_size, 0);
4356 /* If the target didn't like the packet, warn the user. Do not try
4357 to undo the user's settings, that would just be maddening. */
4358 if (strcmp (rs->buf, "OK") != 0)
4359 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4362 /* This type describes each known response to the qSupported
4364 struct protocol_feature
4366 /* The name of this protocol feature. */
4369 /* The default for this protocol feature. */
4370 enum packet_support default_support;
4372 /* The function to call when this feature is reported, or after
4373 qSupported processing if the feature is not supported.
4374 The first argument points to this structure. The second
4375 argument indicates whether the packet requested support be
4376 enabled, disabled, or probed (or the default, if this function
4377 is being called at the end of processing and this feature was
4378 not reported). The third argument may be NULL; if not NULL, it
4379 is a NUL-terminated string taken from the packet following
4380 this feature's name and an equals sign. */
4381 void (*func) (const struct protocol_feature *, enum packet_support,
4384 /* The corresponding packet for this feature. Only used if
4385 FUNC is remote_supported_packet. */
4390 remote_supported_packet (const struct protocol_feature *feature,
4391 enum packet_support support,
4392 const char *argument)
4396 warning (_("Remote qSupported response supplied an unexpected value for"
4397 " \"%s\"."), feature->name);
4401 remote_protocol_packets[feature->packet].support = support;
4405 remote_packet_size (const struct protocol_feature *feature,
4406 enum packet_support support, const char *value)
4408 struct remote_state *rs = get_remote_state ();
4413 if (support != PACKET_ENABLE)
4416 if (value == NULL || *value == '\0')
4418 warning (_("Remote target reported \"%s\" without a size."),
4424 packet_size = strtol (value, &value_end, 16);
4425 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4427 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4428 feature->name, value);
4432 /* Record the new maximum packet size. */
4433 rs->explicit_packet_size = packet_size;
4436 static const struct protocol_feature remote_protocol_features[] = {
4437 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4438 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4439 PACKET_qXfer_auxv },
4440 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4441 PACKET_qXfer_exec_file },
4442 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4443 PACKET_qXfer_features },
4444 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4445 PACKET_qXfer_libraries },
4446 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4447 PACKET_qXfer_libraries_svr4 },
4448 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4449 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4450 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4451 PACKET_qXfer_memory_map },
4452 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4453 PACKET_qXfer_spu_read },
4454 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4455 PACKET_qXfer_spu_write },
4456 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4457 PACKET_qXfer_osdata },
4458 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4459 PACKET_qXfer_threads },
4460 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4461 PACKET_qXfer_traceframe_info },
4462 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4463 PACKET_QPassSignals },
4464 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4465 PACKET_QProgramSignals },
4466 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4467 PACKET_QStartNoAckMode },
4468 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4469 PACKET_multiprocess_feature },
4470 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4471 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4472 PACKET_qXfer_siginfo_read },
4473 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4474 PACKET_qXfer_siginfo_write },
4475 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4476 PACKET_ConditionalTracepoints },
4477 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4478 PACKET_ConditionalBreakpoints },
4479 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4480 PACKET_BreakpointCommands },
4481 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4482 PACKET_FastTracepoints },
4483 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4484 PACKET_StaticTracepoints },
4485 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4486 PACKET_InstallInTrace},
4487 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4488 PACKET_DisconnectedTracing_feature },
4489 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4491 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4493 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4494 PACKET_TracepointSource },
4495 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4497 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4498 PACKET_EnableDisableTracepoints_feature },
4499 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4500 PACKET_qXfer_fdpic },
4501 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4503 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4504 PACKET_QDisableRandomization },
4505 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4506 { "QTBuffer:size", PACKET_DISABLE,
4507 remote_supported_packet, PACKET_QTBuffer_size},
4508 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4509 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4510 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4511 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4512 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4513 PACKET_qXfer_btrace },
4514 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4515 PACKET_qXfer_btrace_conf },
4516 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4517 PACKET_Qbtrace_conf_bts_size },
4518 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4519 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4520 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4521 PACKET_fork_event_feature },
4522 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4523 PACKET_vfork_event_feature },
4524 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4525 PACKET_exec_event_feature },
4526 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4527 PACKET_Qbtrace_conf_pt_size },
4528 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4529 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4532 static char *remote_support_xml;
4534 /* Register string appended to "xmlRegisters=" in qSupported query. */
4537 register_remote_support_xml (const char *xml)
4539 #if defined(HAVE_LIBEXPAT)
4540 if (remote_support_xml == NULL)
4541 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4544 char *copy = xstrdup (remote_support_xml + 13);
4545 char *p = strtok (copy, ",");
4549 if (strcmp (p, xml) == 0)
4556 while ((p = strtok (NULL, ",")) != NULL);
4559 remote_support_xml = reconcat (remote_support_xml,
4560 remote_support_xml, ",", xml,
4567 remote_query_supported_append (char *msg, const char *append)
4570 return reconcat (msg, msg, ";", append, (char *) NULL);
4572 return xstrdup (append);
4576 remote_query_supported (void)
4578 struct remote_state *rs = get_remote_state ();
4581 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4583 /* The packet support flags are handled differently for this packet
4584 than for most others. We treat an error, a disabled packet, and
4585 an empty response identically: any features which must be reported
4586 to be used will be automatically disabled. An empty buffer
4587 accomplishes this, since that is also the representation for a list
4588 containing no features. */
4591 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4594 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4596 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4597 q = remote_query_supported_append (q, "multiprocess+");
4599 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4600 q = remote_query_supported_append (q, "swbreak+");
4601 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4602 q = remote_query_supported_append (q, "hwbreak+");
4604 q = remote_query_supported_append (q, "qRelocInsn+");
4608 if (packet_set_cmd_state (PACKET_fork_event_feature)
4609 != AUTO_BOOLEAN_FALSE)
4610 q = remote_query_supported_append (q, "fork-events+");
4611 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4612 != AUTO_BOOLEAN_FALSE)
4613 q = remote_query_supported_append (q, "vfork-events+");
4614 if (packet_set_cmd_state (PACKET_exec_event_feature)
4615 != AUTO_BOOLEAN_FALSE)
4616 q = remote_query_supported_append (q, "exec-events+");
4619 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4620 q = remote_query_supported_append (q, "vContSupported+");
4622 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4623 q = remote_query_supported_append (q, "QThreadEvents+");
4625 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4626 the qSupported:xmlRegisters=i386 handling. */
4627 if (remote_support_xml != NULL)
4628 q = remote_query_supported_append (q, remote_support_xml);
4630 q = reconcat (q, "qSupported:", q, (char *) NULL);
4633 do_cleanups (old_chain);
4635 getpkt (&rs->buf, &rs->buf_size, 0);
4637 /* If an error occured, warn, but do not return - just reset the
4638 buffer to empty and go on to disable features. */
4639 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4642 warning (_("Remote failure reply: %s"), rs->buf);
4647 memset (seen, 0, sizeof (seen));
4652 enum packet_support is_supported;
4653 char *p, *end, *name_end, *value;
4655 /* First separate out this item from the rest of the packet. If
4656 there's another item after this, we overwrite the separator
4657 (terminated strings are much easier to work with). */
4659 end = strchr (p, ';');
4662 end = p + strlen (p);
4672 warning (_("empty item in \"qSupported\" response"));
4677 name_end = strchr (p, '=');
4680 /* This is a name=value entry. */
4681 is_supported = PACKET_ENABLE;
4682 value = name_end + 1;
4691 is_supported = PACKET_ENABLE;
4695 is_supported = PACKET_DISABLE;
4699 is_supported = PACKET_SUPPORT_UNKNOWN;
4703 warning (_("unrecognized item \"%s\" "
4704 "in \"qSupported\" response"), p);
4710 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4711 if (strcmp (remote_protocol_features[i].name, p) == 0)
4713 const struct protocol_feature *feature;
4716 feature = &remote_protocol_features[i];
4717 feature->func (feature, is_supported, value);
4722 /* If we increased the packet size, make sure to increase the global
4723 buffer size also. We delay this until after parsing the entire
4724 qSupported packet, because this is the same buffer we were
4726 if (rs->buf_size < rs->explicit_packet_size)
4728 rs->buf_size = rs->explicit_packet_size;
4729 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4732 /* Handle the defaults for unmentioned features. */
4733 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4736 const struct protocol_feature *feature;
4738 feature = &remote_protocol_features[i];
4739 feature->func (feature, feature->default_support, NULL);
4743 /* Remove any of the remote.c targets from target stack. Upper targets depend
4744 on it so remove them first. */
4747 remote_unpush_target (void)
4749 pop_all_targets_at_and_above (process_stratum);
4753 remote_open_1 (const char *name, int from_tty,
4754 struct target_ops *target, int extended_p)
4756 struct remote_state *rs = get_remote_state ();
4759 error (_("To open a remote debug connection, you need to specify what\n"
4760 "serial device is attached to the remote system\n"
4761 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4763 /* See FIXME above. */
4764 if (!target_async_permitted)
4765 wait_forever_enabled_p = 1;
4767 /* If we're connected to a running target, target_preopen will kill it.
4768 Ask this question first, before target_preopen has a chance to kill
4770 if (rs->remote_desc != NULL && !have_inferiors ())
4773 && !query (_("Already connected to a remote target. Disconnect? ")))
4774 error (_("Still connected."));
4777 /* Here the possibly existing remote target gets unpushed. */
4778 target_preopen (from_tty);
4780 /* Make sure we send the passed signals list the next time we resume. */
4781 xfree (rs->last_pass_packet);
4782 rs->last_pass_packet = NULL;
4784 /* Make sure we send the program signals list the next time we
4786 xfree (rs->last_program_signals_packet);
4787 rs->last_program_signals_packet = NULL;
4789 remote_fileio_reset ();
4790 reopen_exec_file ();
4793 rs->remote_desc = remote_serial_open (name);
4794 if (!rs->remote_desc)
4795 perror_with_name (name);
4797 if (baud_rate != -1)
4799 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4801 /* The requested speed could not be set. Error out to
4802 top level after closing remote_desc. Take care to
4803 set remote_desc to NULL to avoid closing remote_desc
4805 serial_close (rs->remote_desc);
4806 rs->remote_desc = NULL;
4807 perror_with_name (name);
4811 serial_setparity (rs->remote_desc, serial_parity);
4812 serial_raw (rs->remote_desc);
4814 /* If there is something sitting in the buffer we might take it as a
4815 response to a command, which would be bad. */
4816 serial_flush_input (rs->remote_desc);
4820 puts_filtered ("Remote debugging using ");
4821 puts_filtered (name);
4822 puts_filtered ("\n");
4824 push_target (target); /* Switch to using remote target now. */
4826 /* Register extra event sources in the event loop. */
4827 remote_async_inferior_event_token
4828 = create_async_event_handler (remote_async_inferior_event_handler,
4830 rs->notif_state = remote_notif_state_allocate ();
4832 /* Reset the target state; these things will be queried either by
4833 remote_query_supported or as they are needed. */
4834 reset_all_packet_configs_support ();
4835 rs->cached_wait_status = 0;
4836 rs->explicit_packet_size = 0;
4838 rs->extended = extended_p;
4839 rs->waiting_for_stop_reply = 0;
4840 rs->ctrlc_pending_p = 0;
4842 rs->general_thread = not_sent_ptid;
4843 rs->continue_thread = not_sent_ptid;
4844 rs->remote_traceframe_number = -1;
4846 /* Probe for ability to use "ThreadInfo" query, as required. */
4847 rs->use_threadinfo_query = 1;
4848 rs->use_threadextra_query = 1;
4850 readahead_cache_invalidate ();
4852 if (target_async_permitted)
4854 /* With this target we start out by owning the terminal. */
4855 remote_async_terminal_ours_p = 1;
4857 /* FIXME: cagney/1999-09-23: During the initial connection it is
4858 assumed that the target is already ready and able to respond to
4859 requests. Unfortunately remote_start_remote() eventually calls
4860 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4861 around this. Eventually a mechanism that allows
4862 wait_for_inferior() to expect/get timeouts will be
4864 wait_forever_enabled_p = 0;
4867 /* First delete any symbols previously loaded from shared libraries. */
4868 no_shared_libraries (NULL, 0);
4871 init_thread_list ();
4873 /* Start the remote connection. If error() or QUIT, discard this
4874 target (we'd otherwise be in an inconsistent state) and then
4875 propogate the error on up the exception chain. This ensures that
4876 the caller doesn't stumble along blindly assuming that the
4877 function succeeded. The CLI doesn't have this problem but other
4878 UI's, such as MI do.
4880 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4881 this function should return an error indication letting the
4882 caller restore the previous state. Unfortunately the command
4883 ``target remote'' is directly wired to this function making that
4884 impossible. On a positive note, the CLI side of this problem has
4885 been fixed - the function set_cmd_context() makes it possible for
4886 all the ``target ....'' commands to share a common callback
4887 function. See cli-dump.c. */
4892 remote_start_remote (from_tty, target, extended_p);
4894 CATCH (ex, RETURN_MASK_ALL)
4896 /* Pop the partially set up target - unless something else did
4897 already before throwing the exception. */
4898 if (rs->remote_desc != NULL)
4899 remote_unpush_target ();
4900 if (target_async_permitted)
4901 wait_forever_enabled_p = 1;
4902 throw_exception (ex);
4907 remote_btrace_reset ();
4909 if (target_async_permitted)
4910 wait_forever_enabled_p = 1;
4913 /* Detach the specified process. */
4916 remote_detach_pid (int pid)
4918 struct remote_state *rs = get_remote_state ();
4920 if (remote_multi_process_p (rs))
4921 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4923 strcpy (rs->buf, "D");
4926 getpkt (&rs->buf, &rs->buf_size, 0);
4928 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4930 else if (rs->buf[0] == '\0')
4931 error (_("Remote doesn't know how to detach"));
4933 error (_("Can't detach process."));
4936 /* This detaches a program to which we previously attached, using
4937 inferior_ptid to identify the process. After this is done, GDB
4938 can be used to debug some other program. We better not have left
4939 any breakpoints in the target program or it'll die when it hits
4943 remote_detach_1 (const char *args, int from_tty)
4945 int pid = ptid_get_pid (inferior_ptid);
4946 struct remote_state *rs = get_remote_state ();
4947 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4951 error (_("Argument given to \"detach\" when remotely debugging."));
4953 if (!target_has_execution)
4954 error (_("No process to detach from."));
4958 char *exec_file = get_exec_file (0);
4959 if (exec_file == NULL)
4961 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4962 target_pid_to_str (pid_to_ptid (pid)));
4963 gdb_flush (gdb_stdout);
4966 /* Tell the remote target to detach. */
4967 remote_detach_pid (pid);
4969 if (from_tty && !rs->extended)
4970 puts_filtered (_("Ending remote debugging.\n"));
4972 /* Check to see if we are detaching a fork parent. Note that if we
4973 are detaching a fork child, tp == NULL. */
4974 is_fork_parent = (tp != NULL
4975 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4977 /* If doing detach-on-fork, we don't mourn, because that will delete
4978 breakpoints that should be available for the followed inferior. */
4979 if (!is_fork_parent)
4980 target_mourn_inferior ();
4983 inferior_ptid = null_ptid;
4984 detach_inferior (pid);
4989 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4991 remote_detach_1 (args, from_tty);
4995 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4997 remote_detach_1 (args, from_tty);
5000 /* Target follow-fork function for remote targets. On entry, and
5001 at return, the current inferior is the fork parent.
5003 Note that although this is currently only used for extended-remote,
5004 it is named remote_follow_fork in anticipation of using it for the
5005 remote target as well. */
5008 remote_follow_fork (struct target_ops *ops, int follow_child,
5011 struct remote_state *rs = get_remote_state ();
5012 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5014 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5015 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5017 /* When following the parent and detaching the child, we detach
5018 the child here. For the case of following the child and
5019 detaching the parent, the detach is done in the target-
5020 independent follow fork code in infrun.c. We can't use
5021 target_detach when detaching an unfollowed child because
5022 the client side doesn't know anything about the child. */
5023 if (detach_fork && !follow_child)
5025 /* Detach the fork child. */
5029 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5030 child_pid = ptid_get_pid (child_ptid);
5032 remote_detach_pid (child_pid);
5033 detach_inferior (child_pid);
5039 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5040 in the program space of the new inferior. On entry and at return the
5041 current inferior is the exec'ing inferior. INF is the new exec'd
5042 inferior, which may be the same as the exec'ing inferior unless
5043 follow-exec-mode is "new". */
5046 remote_follow_exec (struct target_ops *ops,
5047 struct inferior *inf, char *execd_pathname)
5049 /* We know that this is a target file name, so if it has the "target:"
5050 prefix we strip it off before saving it in the program space. */
5051 if (is_target_filename (execd_pathname))
5052 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5054 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5057 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5060 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5063 error (_("Argument given to \"disconnect\" when remotely debugging."));
5065 /* Make sure we unpush even the extended remote targets; mourn
5066 won't do it. So call remote_mourn directly instead of
5067 target_mourn_inferior. */
5068 remote_mourn (target);
5071 puts_filtered ("Ending remote debugging.\n");
5074 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5075 be chatty about it. */
5078 extended_remote_attach (struct target_ops *target, const char *args,
5081 struct remote_state *rs = get_remote_state ();
5083 char *wait_status = NULL;
5085 pid = parse_pid_to_attach (args);
5087 /* Remote PID can be freely equal to getpid, do not check it here the same
5088 way as in other targets. */
5090 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5091 error (_("This target does not support attaching to a process"));
5095 char *exec_file = get_exec_file (0);
5098 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5099 target_pid_to_str (pid_to_ptid (pid)));
5101 printf_unfiltered (_("Attaching to %s\n"),
5102 target_pid_to_str (pid_to_ptid (pid)));
5104 gdb_flush (gdb_stdout);
5107 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5109 getpkt (&rs->buf, &rs->buf_size, 0);
5111 switch (packet_ok (rs->buf,
5112 &remote_protocol_packets[PACKET_vAttach]))
5115 if (!target_is_non_stop_p ())
5117 /* Save the reply for later. */
5118 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5119 strcpy (wait_status, rs->buf);
5121 else if (strcmp (rs->buf, "OK") != 0)
5122 error (_("Attaching to %s failed with: %s"),
5123 target_pid_to_str (pid_to_ptid (pid)),
5126 case PACKET_UNKNOWN:
5127 error (_("This target does not support attaching to a process"));
5129 error (_("Attaching to %s failed"),
5130 target_pid_to_str (pid_to_ptid (pid)));
5133 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5135 inferior_ptid = pid_to_ptid (pid);
5137 if (target_is_non_stop_p ())
5139 struct thread_info *thread;
5141 /* Get list of threads. */
5142 remote_update_thread_list (target);
5144 thread = first_thread_of_process (pid);
5146 inferior_ptid = thread->ptid;
5148 inferior_ptid = pid_to_ptid (pid);
5150 /* Invalidate our notion of the remote current thread. */
5151 record_currthread (rs, minus_one_ptid);
5155 /* Now, if we have thread information, update inferior_ptid. */
5156 inferior_ptid = remote_current_thread (inferior_ptid);
5158 /* Add the main thread to the thread list. */
5159 add_thread_silent (inferior_ptid);
5162 /* Next, if the target can specify a description, read it. We do
5163 this before anything involving memory or registers. */
5164 target_find_description ();
5166 if (!target_is_non_stop_p ())
5168 /* Use the previously fetched status. */
5169 gdb_assert (wait_status != NULL);
5171 if (target_can_async_p ())
5173 struct notif_event *reply
5174 = remote_notif_parse (¬if_client_stop, wait_status);
5176 push_stop_reply ((struct stop_reply *) reply);
5182 gdb_assert (wait_status != NULL);
5183 strcpy (rs->buf, wait_status);
5184 rs->cached_wait_status = 1;
5188 gdb_assert (wait_status == NULL);
5191 /* Implementation of the to_post_attach method. */
5194 extended_remote_post_attach (struct target_ops *ops, int pid)
5196 /* Get text, data & bss offsets. */
5199 /* In certain cases GDB might not have had the chance to start
5200 symbol lookup up until now. This could happen if the debugged
5201 binary is not using shared libraries, the vsyscall page is not
5202 present (on Linux) and the binary itself hadn't changed since the
5203 debugging process was started. */
5204 if (symfile_objfile != NULL)
5205 remote_check_symbols();
5209 /* Check for the availability of vCont. This function should also check
5213 remote_vcont_probe (struct remote_state *rs)
5217 strcpy (rs->buf, "vCont?");
5219 getpkt (&rs->buf, &rs->buf_size, 0);
5222 /* Make sure that the features we assume are supported. */
5223 if (startswith (buf, "vCont"))
5226 int support_c, support_C;
5228 rs->supports_vCont.s = 0;
5229 rs->supports_vCont.S = 0;
5232 rs->supports_vCont.t = 0;
5233 rs->supports_vCont.r = 0;
5234 while (p && *p == ';')
5237 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5238 rs->supports_vCont.s = 1;
5239 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5240 rs->supports_vCont.S = 1;
5241 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5243 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5245 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5246 rs->supports_vCont.t = 1;
5247 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5248 rs->supports_vCont.r = 1;
5250 p = strchr (p, ';');
5253 /* If c, and C are not all supported, we can't use vCont. Clearing
5254 BUF will make packet_ok disable the packet. */
5255 if (!support_c || !support_C)
5259 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5262 /* Helper function for building "vCont" resumptions. Write a
5263 resumption to P. ENDP points to one-passed-the-end of the buffer
5264 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5265 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5266 resumed thread should be single-stepped and/or signalled. If PTID
5267 equals minus_one_ptid, then all threads are resumed; if PTID
5268 represents a process, then all threads of the process are resumed;
5269 the thread to be stepped and/or signalled is given in the global
5273 append_resumption (char *p, char *endp,
5274 ptid_t ptid, int step, enum gdb_signal siggnal)
5276 struct remote_state *rs = get_remote_state ();
5278 if (step && siggnal != GDB_SIGNAL_0)
5279 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5281 /* GDB is willing to range step. */
5282 && use_range_stepping
5283 /* Target supports range stepping. */
5284 && rs->supports_vCont.r
5285 /* We don't currently support range stepping multiple
5286 threads with a wildcard (though the protocol allows it,
5287 so stubs shouldn't make an active effort to forbid
5289 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5291 struct thread_info *tp;
5293 if (ptid_equal (ptid, minus_one_ptid))
5295 /* If we don't know about the target thread's tid, then
5296 we're resuming magic_null_ptid (see caller). */
5297 tp = find_thread_ptid (magic_null_ptid);
5300 tp = find_thread_ptid (ptid);
5301 gdb_assert (tp != NULL);
5303 if (tp->control.may_range_step)
5305 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5307 p += xsnprintf (p, endp - p, ";r%s,%s",
5308 phex_nz (tp->control.step_range_start,
5310 phex_nz (tp->control.step_range_end,
5314 p += xsnprintf (p, endp - p, ";s");
5317 p += xsnprintf (p, endp - p, ";s");
5318 else if (siggnal != GDB_SIGNAL_0)
5319 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5321 p += xsnprintf (p, endp - p, ";c");
5323 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5327 /* All (-1) threads of process. */
5328 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5330 p += xsnprintf (p, endp - p, ":");
5331 p = write_ptid (p, endp, nptid);
5333 else if (!ptid_equal (ptid, minus_one_ptid))
5335 p += xsnprintf (p, endp - p, ":");
5336 p = write_ptid (p, endp, ptid);
5342 /* Clear the thread's private info on resume. */
5345 resume_clear_thread_private_info (struct thread_info *thread)
5347 if (thread->priv != NULL)
5349 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5350 thread->priv->watch_data_address = 0;
5354 /* Append a vCont continue-with-signal action for threads that have a
5355 non-zero stop signal. */
5358 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5360 struct thread_info *thread;
5362 ALL_NON_EXITED_THREADS (thread)
5363 if (ptid_match (thread->ptid, ptid)
5364 && !ptid_equal (inferior_ptid, thread->ptid)
5365 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5367 p = append_resumption (p, endp, thread->ptid,
5368 0, thread->suspend.stop_signal);
5369 thread->suspend.stop_signal = GDB_SIGNAL_0;
5370 resume_clear_thread_private_info (thread);
5376 /* Resume the remote inferior by using a "vCont" packet. The thread
5377 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5378 resumed thread should be single-stepped and/or signalled. If PTID
5379 equals minus_one_ptid, then all threads are resumed; the thread to
5380 be stepped and/or signalled is given in the global INFERIOR_PTID.
5381 This function returns non-zero iff it resumes the inferior.
5383 This function issues a strict subset of all possible vCont commands at the
5387 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5389 struct remote_state *rs = get_remote_state ();
5393 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5394 remote_vcont_probe (rs);
5396 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5400 endp = rs->buf + get_remote_packet_size ();
5402 /* If we could generate a wider range of packets, we'd have to worry
5403 about overflowing BUF. Should there be a generic
5404 "multi-part-packet" packet? */
5406 p += xsnprintf (p, endp - p, "vCont");
5408 if (ptid_equal (ptid, magic_null_ptid))
5410 /* MAGIC_NULL_PTID means that we don't have any active threads,
5411 so we don't have any TID numbers the inferior will
5412 understand. Make sure to only send forms that do not specify
5414 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5416 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5418 /* Resume all threads (of all processes, or of a single
5419 process), with preference for INFERIOR_PTID. This assumes
5420 inferior_ptid belongs to the set of all threads we are about
5422 if (step || siggnal != GDB_SIGNAL_0)
5424 /* Step inferior_ptid, with or without signal. */
5425 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5428 /* Also pass down any pending signaled resumption for other
5429 threads not the current. */
5430 p = append_pending_thread_resumptions (p, endp, ptid);
5432 /* And continue others without a signal. */
5433 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5437 /* Scheduler locking; resume only PTID. */
5438 append_resumption (p, endp, ptid, step, siggnal);
5441 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5444 if (target_is_non_stop_p ())
5446 /* In non-stop, the stub replies to vCont with "OK". The stop
5447 reply will be reported asynchronously by means of a `%Stop'
5449 getpkt (&rs->buf, &rs->buf_size, 0);
5450 if (strcmp (rs->buf, "OK") != 0)
5451 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5457 /* Tell the remote machine to resume. */
5460 remote_resume (struct target_ops *ops,
5461 ptid_t ptid, int step, enum gdb_signal siggnal)
5463 struct remote_state *rs = get_remote_state ();
5465 struct thread_info *thread;
5467 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5468 (explained in remote-notif.c:handle_notification) so
5469 remote_notif_process is not called. We need find a place where
5470 it is safe to start a 'vNotif' sequence. It is good to do it
5471 before resuming inferior, because inferior was stopped and no RSP
5472 traffic at that moment. */
5473 if (!target_is_non_stop_p ())
5474 remote_notif_process (rs->notif_state, ¬if_client_stop);
5476 rs->last_sent_signal = siggnal;
5477 rs->last_sent_step = step;
5479 /* The vCont packet doesn't need to specify threads via Hc. */
5480 /* No reverse support (yet) for vCont. */
5481 if (execution_direction != EXEC_REVERSE)
5482 if (remote_vcont_resume (ptid, step, siggnal))
5485 /* All other supported resume packets do use Hc, so set the continue
5487 if (ptid_equal (ptid, minus_one_ptid))
5488 set_continue_thread (any_thread_ptid);
5490 set_continue_thread (ptid);
5492 ALL_NON_EXITED_THREADS (thread)
5493 resume_clear_thread_private_info (thread);
5496 if (execution_direction == EXEC_REVERSE)
5498 /* We don't pass signals to the target in reverse exec mode. */
5499 if (info_verbose && siggnal != GDB_SIGNAL_0)
5500 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5503 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5504 error (_("Remote reverse-step not supported."));
5505 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5506 error (_("Remote reverse-continue not supported."));
5508 strcpy (buf, step ? "bs" : "bc");
5510 else if (siggnal != GDB_SIGNAL_0)
5512 buf[0] = step ? 'S' : 'C';
5513 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5514 buf[2] = tohex (((int) siggnal) & 0xf);
5518 strcpy (buf, step ? "s" : "c");
5523 /* We are about to start executing the inferior, let's register it
5524 with the event loop. NOTE: this is the one place where all the
5525 execution commands end up. We could alternatively do this in each
5526 of the execution commands in infcmd.c. */
5527 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5528 into infcmd.c in order to allow inferior function calls to work
5529 NOT asynchronously. */
5530 if (target_can_async_p ())
5533 /* We've just told the target to resume. The remote server will
5534 wait for the inferior to stop, and then send a stop reply. In
5535 the mean time, we can't start another command/query ourselves
5536 because the stub wouldn't be ready to process it. This applies
5537 only to the base all-stop protocol, however. In non-stop (which
5538 only supports vCont), the stub replies with an "OK", and is
5539 immediate able to process further serial input. */
5540 if (!target_is_non_stop_p ())
5541 rs->waiting_for_stop_reply = 1;
5545 /* Set up the signal handler for SIGINT, while the target is
5546 executing, ovewriting the 'regular' SIGINT signal handler. */
5548 async_initialize_sigint_signal_handler (void)
5550 signal (SIGINT, async_handle_remote_sigint);
5553 /* Signal handler for SIGINT, while the target is executing. */
5555 async_handle_remote_sigint (int sig)
5557 signal (sig, async_handle_remote_sigint_twice);
5558 /* Note we need to go through gdb_call_async_signal_handler in order
5559 to wake up the event loop on Windows. */
5560 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5563 /* Signal handler for SIGINT, installed after SIGINT has already been
5564 sent once. It will take effect the second time that the user sends
5567 async_handle_remote_sigint_twice (int sig)
5569 signal (sig, async_handle_remote_sigint);
5570 /* See note in async_handle_remote_sigint. */
5571 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5574 /* Implementation of to_check_pending_interrupt. */
5577 remote_check_pending_interrupt (struct target_ops *self)
5579 struct async_signal_handler *token = async_sigint_remote_twice_token;
5581 if (async_signal_handler_is_marked (token))
5583 clear_async_signal_handler (token);
5584 call_async_signal_handler (token);
5588 /* Perform the real interruption of the target execution, in response
5591 async_remote_interrupt (gdb_client_data arg)
5594 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5596 target_interrupt (inferior_ptid);
5599 /* Perform interrupt, if the first attempt did not succeed. Just give
5600 up on the target alltogether. */
5602 async_remote_interrupt_twice (gdb_client_data arg)
5605 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5610 /* Reinstall the usual SIGINT handlers, after the target has
5613 async_cleanup_sigint_signal_handler (void *dummy)
5615 signal (SIGINT, handle_sigint);
5618 /* Send ^C to target to halt it. Target will respond, and send us a
5620 static void (*ofunc) (int);
5622 /* The command line interface's interrupt routine. This function is installed
5623 as a signal handler for SIGINT. The first time a user requests an
5624 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5625 response from the target (it didn't stop when the user requested it),
5626 we ask the user if he'd like to detach from the target. */
5629 sync_remote_interrupt (int signo)
5631 /* If this doesn't work, try more severe steps. */
5632 signal (signo, sync_remote_interrupt_twice);
5634 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5637 /* The user typed ^C twice. */
5640 sync_remote_interrupt_twice (int signo)
5642 signal (signo, ofunc);
5643 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5644 signal (signo, sync_remote_interrupt);
5647 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5648 thread, all threads of a remote process, or all threads of all
5652 remote_stop_ns (ptid_t ptid)
5654 struct remote_state *rs = get_remote_state ();
5656 char *endp = rs->buf + get_remote_packet_size ();
5658 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5659 remote_vcont_probe (rs);
5661 if (!rs->supports_vCont.t)
5662 error (_("Remote server does not support stopping threads"));
5664 if (ptid_equal (ptid, minus_one_ptid)
5665 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5666 p += xsnprintf (p, endp - p, "vCont;t");
5671 p += xsnprintf (p, endp - p, "vCont;t:");
5673 if (ptid_is_pid (ptid))
5674 /* All (-1) threads of process. */
5675 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5678 /* Small optimization: if we already have a stop reply for
5679 this thread, no use in telling the stub we want this
5681 if (peek_stop_reply (ptid))
5687 write_ptid (p, endp, nptid);
5690 /* In non-stop, we get an immediate OK reply. The stop reply will
5691 come in asynchronously by notification. */
5693 getpkt (&rs->buf, &rs->buf_size, 0);
5694 if (strcmp (rs->buf, "OK") != 0)
5695 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5698 /* All-stop version of target_interrupt. Sends a break or a ^C to
5699 interrupt the remote target. It is undefined which thread of which
5700 process reports the interrupt. */
5703 remote_interrupt_as (void)
5705 struct remote_state *rs = get_remote_state ();
5707 rs->ctrlc_pending_p = 1;
5709 /* If the inferior is stopped already, but the core didn't know
5710 about it yet, just ignore the request. The cached wait status
5711 will be collected in remote_wait. */
5712 if (rs->cached_wait_status)
5715 /* Send interrupt_sequence to remote target. */
5716 send_interrupt_sequence ();
5719 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5720 the remote target. It is undefined which thread of which process
5721 reports the interrupt. Returns true if the packet is supported by
5722 the server, false otherwise. */
5725 remote_interrupt_ns (void)
5727 struct remote_state *rs = get_remote_state ();
5729 char *endp = rs->buf + get_remote_packet_size ();
5731 xsnprintf (p, endp - p, "vCtrlC");
5733 /* In non-stop, we get an immediate OK reply. The stop reply will
5734 come in asynchronously by notification. */
5736 getpkt (&rs->buf, &rs->buf_size, 0);
5738 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5742 case PACKET_UNKNOWN:
5745 error (_("Interrupting target failed: %s"), rs->buf);
5751 /* Implement the to_stop function for the remote targets. */
5754 remote_stop (struct target_ops *self, ptid_t ptid)
5757 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5759 if (target_is_non_stop_p ())
5760 remote_stop_ns (ptid);
5763 /* We don't currently have a way to transparently pause the
5764 remote target in all-stop mode. Interrupt it instead. */
5765 remote_interrupt_as ();
5769 /* Implement the to_interrupt function for the remote targets. */
5772 remote_interrupt (struct target_ops *self, ptid_t ptid)
5775 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5779 /* In non-stop mode, we always stop with no signal instead. */
5780 remote_stop_ns (ptid);
5784 /* In all-stop, we emulate ^C-ing the remote target's
5786 if (target_is_non_stop_p ())
5788 if (!remote_interrupt_ns ())
5790 /* No support for ^C-ing the remote target. Stop it
5791 (with no signal) instead. */
5792 remote_stop_ns (ptid);
5796 remote_interrupt_as ();
5800 /* Ask the user what to do when an interrupt is received. */
5803 interrupt_query (void)
5805 struct remote_state *rs = get_remote_state ();
5806 struct cleanup *old_chain;
5808 old_chain = make_cleanup_restore_target_terminal ();
5809 target_terminal_ours ();
5811 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5813 if (query (_("The target is not responding to interrupt requests.\n"
5814 "Stop debugging it? ")))
5816 remote_unpush_target ();
5817 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5822 if (query (_("Interrupted while waiting for the program.\n"
5823 "Give up waiting? ")))
5827 do_cleanups (old_chain);
5830 /* Enable/disable target terminal ownership. Most targets can use
5831 terminal groups to control terminal ownership. Remote targets are
5832 different in that explicit transfer of ownership to/from GDB/target
5836 remote_terminal_inferior (struct target_ops *self)
5838 if (!target_async_permitted)
5839 /* Nothing to do. */
5842 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5843 idempotent. The event-loop GDB talking to an asynchronous target
5844 with a synchronous command calls this function from both
5845 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5846 transfer the terminal to the target when it shouldn't this guard
5848 if (!remote_async_terminal_ours_p)
5850 delete_file_handler (input_fd);
5851 remote_async_terminal_ours_p = 0;
5852 async_initialize_sigint_signal_handler ();
5853 /* NOTE: At this point we could also register our selves as the
5854 recipient of all input. Any characters typed could then be
5855 passed on down to the target. */
5859 remote_terminal_ours (struct target_ops *self)
5861 if (!target_async_permitted)
5862 /* Nothing to do. */
5865 /* See FIXME in remote_terminal_inferior. */
5866 if (remote_async_terminal_ours_p)
5868 async_cleanup_sigint_signal_handler (NULL);
5869 add_file_handler (input_fd, stdin_event_handler, 0);
5870 remote_async_terminal_ours_p = 1;
5874 remote_console_output (char *msg)
5878 for (p = msg; p[0] && p[1]; p += 2)
5881 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5885 fputs_unfiltered (tb, gdb_stdtarg);
5887 gdb_flush (gdb_stdtarg);
5890 typedef struct cached_reg
5893 gdb_byte data[MAX_REGISTER_SIZE];
5896 DEF_VEC_O(cached_reg_t);
5898 typedef struct stop_reply
5900 struct notif_event base;
5902 /* The identifier of the thread about this event */
5905 /* The remote state this event is associated with. When the remote
5906 connection, represented by a remote_state object, is closed,
5907 all the associated stop_reply events should be released. */
5908 struct remote_state *rs;
5910 struct target_waitstatus ws;
5912 /* Expedited registers. This makes remote debugging a bit more
5913 efficient for those targets that provide critical registers as
5914 part of their normal status mechanism (as another roundtrip to
5915 fetch them is avoided). */
5916 VEC(cached_reg_t) *regcache;
5918 enum target_stop_reason stop_reason;
5920 CORE_ADDR watch_data_address;
5925 DECLARE_QUEUE_P (stop_reply_p);
5926 DEFINE_QUEUE_P (stop_reply_p);
5927 /* The list of already fetched and acknowledged stop events. This
5928 queue is used for notification Stop, and other notifications
5929 don't need queue for their events, because the notification events
5930 of Stop can't be consumed immediately, so that events should be
5931 queued first, and be consumed by remote_wait_{ns,as} one per
5932 time. Other notifications can consume their events immediately,
5933 so queue is not needed for them. */
5934 static QUEUE (stop_reply_p) *stop_reply_queue;
5937 stop_reply_xfree (struct stop_reply *r)
5939 notif_event_xfree ((struct notif_event *) r);
5942 /* Return the length of the stop reply queue. */
5945 stop_reply_queue_length (void)
5947 return QUEUE_length (stop_reply_p, stop_reply_queue);
5951 remote_notif_stop_parse (struct notif_client *self, char *buf,
5952 struct notif_event *event)
5954 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5958 remote_notif_stop_ack (struct notif_client *self, char *buf,
5959 struct notif_event *event)
5961 struct stop_reply *stop_reply = (struct stop_reply *) event;
5964 putpkt ((char *) self->ack_command);
5966 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5967 /* We got an unknown stop reply. */
5968 error (_("Unknown stop reply"));
5970 push_stop_reply (stop_reply);
5974 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5976 /* We can't get pending events in remote_notif_process for
5977 notification stop, and we have to do this in remote_wait_ns
5978 instead. If we fetch all queued events from stub, remote stub
5979 may exit and we have no chance to process them back in
5981 mark_async_event_handler (remote_async_inferior_event_token);
5986 stop_reply_dtr (struct notif_event *event)
5988 struct stop_reply *r = (struct stop_reply *) event;
5990 VEC_free (cached_reg_t, r->regcache);
5993 static struct notif_event *
5994 remote_notif_stop_alloc_reply (void)
5996 /* We cast to a pointer to the "base class". */
5997 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5999 r->dtr = stop_reply_dtr;
6004 /* A client of notification Stop. */
6006 struct notif_client notif_client_stop =
6010 remote_notif_stop_parse,
6011 remote_notif_stop_ack,
6012 remote_notif_stop_can_get_pending_events,
6013 remote_notif_stop_alloc_reply,
6017 /* A parameter to pass data in and out. */
6019 struct queue_iter_param
6022 struct stop_reply *output;
6025 /* Determine if THREAD is a pending fork parent thread. ARG contains
6026 the pid of the process that owns the threads we want to check, or
6027 -1 if we want to check all threads. */
6030 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6033 if (ws->kind == TARGET_WAITKIND_FORKED
6034 || ws->kind == TARGET_WAITKIND_VFORKED)
6036 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6043 /* Check whether EVENT is a fork event, and if it is, remove the
6044 fork child from the context list passed in DATA. */
6047 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6048 QUEUE_ITER (stop_reply_p) *iter,
6052 struct queue_iter_param *param = (struct queue_iter_param *) data;
6053 struct threads_listing_context *context
6054 = (struct threads_listing_context *) param->input;
6056 if (event->ws.kind == TARGET_WAITKIND_FORKED
6057 || event->ws.kind == TARGET_WAITKIND_VFORKED
6058 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6059 threads_listing_context_remove (&event->ws, context);
6064 /* If CONTEXT contains any fork child threads that have not been
6065 reported yet, remove them from the CONTEXT list. If such a
6066 thread exists it is because we are stopped at a fork catchpoint
6067 and have not yet called follow_fork, which will set up the
6068 host-side data structures for the new process. */
6071 remove_new_fork_children (struct threads_listing_context *context)
6073 struct thread_info * thread;
6075 struct notif_client *notif = ¬if_client_stop;
6076 struct queue_iter_param param;
6078 /* For any threads stopped at a fork event, remove the corresponding
6079 fork child threads from the CONTEXT list. */
6080 ALL_NON_EXITED_THREADS (thread)
6082 struct target_waitstatus *ws = &thread->pending_follow;
6084 if (is_pending_fork_parent (ws, pid, thread->ptid))
6086 threads_listing_context_remove (ws, context);
6090 /* Check for any pending fork events (not reported or processed yet)
6091 in process PID and remove those fork child threads from the
6092 CONTEXT list as well. */
6093 remote_notif_get_pending_events (notif);
6094 param.input = context;
6095 param.output = NULL;
6096 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6097 remove_child_of_pending_fork, ¶m);
6100 /* Remove stop replies in the queue if its pid is equal to the given
6104 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6105 QUEUE_ITER (stop_reply_p) *iter,
6109 struct queue_iter_param *param = (struct queue_iter_param *) data;
6110 struct inferior *inf = (struct inferior *) param->input;
6112 if (ptid_get_pid (event->ptid) == inf->pid)
6114 stop_reply_xfree (event);
6115 QUEUE_remove_elem (stop_reply_p, q, iter);
6121 /* Discard all pending stop replies of inferior INF. */
6124 discard_pending_stop_replies (struct inferior *inf)
6127 struct queue_iter_param param;
6128 struct stop_reply *reply;
6129 struct remote_state *rs = get_remote_state ();
6130 struct remote_notif_state *rns = rs->notif_state;
6132 /* This function can be notified when an inferior exists. When the
6133 target is not remote, the notification state is NULL. */
6134 if (rs->remote_desc == NULL)
6137 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6139 /* Discard the in-flight notification. */
6140 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6142 stop_reply_xfree (reply);
6143 rns->pending_event[notif_client_stop.id] = NULL;
6147 param.output = NULL;
6148 /* Discard the stop replies we have already pulled with
6150 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6151 remove_stop_reply_for_inferior, ¶m);
6154 /* If its remote state is equal to the given remote state,
6155 remove EVENT from the stop reply queue. */
6158 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6159 QUEUE_ITER (stop_reply_p) *iter,
6163 struct queue_iter_param *param = (struct queue_iter_param *) data;
6164 struct remote_state *rs = (struct remote_state *) param->input;
6166 if (event->rs == rs)
6168 stop_reply_xfree (event);
6169 QUEUE_remove_elem (stop_reply_p, q, iter);
6175 /* Discard the stop replies for RS in stop_reply_queue. */
6178 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6180 struct queue_iter_param param;
6183 param.output = NULL;
6184 /* Discard the stop replies we have already pulled with
6186 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6187 remove_stop_reply_of_remote_state, ¶m);
6190 /* A parameter to pass data in and out. */
6193 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6194 QUEUE_ITER (stop_reply_p) *iter,
6198 struct queue_iter_param *param = (struct queue_iter_param *) data;
6199 ptid_t *ptid = (ptid_t *) param->input;
6201 if (ptid_match (event->ptid, *ptid))
6203 param->output = event;
6204 QUEUE_remove_elem (stop_reply_p, q, iter);
6211 /* Remove the first reply in 'stop_reply_queue' which matches
6214 static struct stop_reply *
6215 remote_notif_remove_queued_reply (ptid_t ptid)
6217 struct queue_iter_param param;
6219 param.input = &ptid;
6220 param.output = NULL;
6222 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6223 remote_notif_remove_once_on_match, ¶m);
6225 fprintf_unfiltered (gdb_stdlog,
6226 "notif: discard queued event: 'Stop' in %s\n",
6227 target_pid_to_str (ptid));
6229 return param.output;
6232 /* Look for a queued stop reply belonging to PTID. If one is found,
6233 remove it from the queue, and return it. Returns NULL if none is
6234 found. If there are still queued events left to process, tell the
6235 event loop to get back to target_wait soon. */
6237 static struct stop_reply *
6238 queued_stop_reply (ptid_t ptid)
6240 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6242 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6243 /* There's still at least an event left. */
6244 mark_async_event_handler (remote_async_inferior_event_token);
6249 /* Push a fully parsed stop reply in the stop reply queue. Since we
6250 know that we now have at least one queued event left to pass to the
6251 core side, tell the event loop to get back to target_wait soon. */
6254 push_stop_reply (struct stop_reply *new_event)
6256 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6259 fprintf_unfiltered (gdb_stdlog,
6260 "notif: push 'Stop' %s to queue %d\n",
6261 target_pid_to_str (new_event->ptid),
6262 QUEUE_length (stop_reply_p,
6265 mark_async_event_handler (remote_async_inferior_event_token);
6269 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6270 QUEUE_ITER (stop_reply_p) *iter,
6271 struct stop_reply *event,
6274 ptid_t *ptid = (ptid_t *) data;
6276 return !(ptid_equal (*ptid, event->ptid)
6277 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6280 /* Returns true if we have a stop reply for PTID. */
6283 peek_stop_reply (ptid_t ptid)
6285 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6286 stop_reply_match_ptid_and_ws, &ptid);
6289 /* Skip PACKET until the next semi-colon (or end of string). */
6292 skip_to_semicolon (char *p)
6294 while (*p != '\0' && *p != ';')
6299 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6300 starting with P and ending with PEND matches PREFIX. */
6303 strprefix (const char *p, const char *pend, const char *prefix)
6305 for ( ; p < pend; p++, prefix++)
6308 return *prefix == '\0';
6311 /* Parse the stop reply in BUF. Either the function succeeds, and the
6312 result is stored in EVENT, or throws an error. */
6315 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6317 struct remote_arch_state *rsa = get_remote_arch_state ();
6322 event->ptid = null_ptid;
6323 event->rs = get_remote_state ();
6324 event->ws.kind = TARGET_WAITKIND_IGNORE;
6325 event->ws.value.integer = 0;
6326 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6327 event->regcache = NULL;
6332 case 'T': /* Status with PC, SP, FP, ... */
6333 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6334 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6336 n... = register number
6337 r... = register contents
6340 p = &buf[3]; /* after Txx */
6346 p1 = strchr (p, ':');
6348 error (_("Malformed packet(a) (missing colon): %s\n\
6352 error (_("Malformed packet(a) (missing register number): %s\n\
6356 /* Some "registers" are actually extended stop information.
6357 Note if you're adding a new entry here: GDB 7.9 and
6358 earlier assume that all register "numbers" that start
6359 with an hex digit are real register numbers. Make sure
6360 the server only sends such a packet if it knows the
6361 client understands it. */
6363 if (strprefix (p, p1, "thread"))
6364 event->ptid = read_ptid (++p1, &p);
6365 else if (strprefix (p, p1, "watch")
6366 || strprefix (p, p1, "rwatch")
6367 || strprefix (p, p1, "awatch"))
6369 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6370 p = unpack_varlen_hex (++p1, &addr);
6371 event->watch_data_address = (CORE_ADDR) addr;
6373 else if (strprefix (p, p1, "swbreak"))
6375 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6377 /* Make sure the stub doesn't forget to indicate support
6379 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6380 error (_("Unexpected swbreak stop reason"));
6382 /* The value part is documented as "must be empty",
6383 though we ignore it, in case we ever decide to make
6384 use of it in a backward compatible way. */
6385 p = skip_to_semicolon (p1 + 1);
6387 else if (strprefix (p, p1, "hwbreak"))
6389 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6391 /* Make sure the stub doesn't forget to indicate support
6393 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6394 error (_("Unexpected hwbreak stop reason"));
6397 p = skip_to_semicolon (p1 + 1);
6399 else if (strprefix (p, p1, "library"))
6401 event->ws.kind = TARGET_WAITKIND_LOADED;
6402 p = skip_to_semicolon (p1 + 1);
6404 else if (strprefix (p, p1, "replaylog"))
6406 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6407 /* p1 will indicate "begin" or "end", but it makes
6408 no difference for now, so ignore it. */
6409 p = skip_to_semicolon (p1 + 1);
6411 else if (strprefix (p, p1, "core"))
6415 p = unpack_varlen_hex (++p1, &c);
6418 else if (strprefix (p, p1, "fork"))
6420 event->ws.value.related_pid = read_ptid (++p1, &p);
6421 event->ws.kind = TARGET_WAITKIND_FORKED;
6423 else if (strprefix (p, p1, "vfork"))
6425 event->ws.value.related_pid = read_ptid (++p1, &p);
6426 event->ws.kind = TARGET_WAITKIND_VFORKED;
6428 else if (strprefix (p, p1, "vforkdone"))
6430 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6431 p = skip_to_semicolon (p1 + 1);
6433 else if (strprefix (p, p1, "exec"))
6436 char pathname[PATH_MAX];
6439 /* Determine the length of the execd pathname. */
6440 p = unpack_varlen_hex (++p1, &ignored);
6441 pathlen = (p - p1) / 2;
6443 /* Save the pathname for event reporting and for
6444 the next run command. */
6445 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6446 pathname[pathlen] = '\0';
6448 /* This is freed during event handling. */
6449 event->ws.value.execd_pathname = xstrdup (pathname);
6450 event->ws.kind = TARGET_WAITKIND_EXECD;
6452 /* Skip the registers included in this packet, since
6453 they may be for an architecture different from the
6454 one used by the original program. */
6457 else if (strprefix (p, p1, "create"))
6459 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6460 p = skip_to_semicolon (p1 + 1);
6469 p = skip_to_semicolon (p1 + 1);
6474 /* Maybe a real ``P'' register number. */
6475 p_temp = unpack_varlen_hex (p, &pnum);
6476 /* If the first invalid character is the colon, we got a
6477 register number. Otherwise, it's an unknown stop
6481 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6482 cached_reg_t cached_reg;
6485 error (_("Remote sent bad register number %s: %s\n\
6487 hex_string (pnum), p, buf);
6489 cached_reg.num = reg->regnum;
6492 fieldsize = hex2bin (p, cached_reg.data,
6493 register_size (target_gdbarch (),
6496 if (fieldsize < register_size (target_gdbarch (),
6498 warning (_("Remote reply is too short: %s"), buf);
6500 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6504 /* Not a number. Silently skip unknown optional
6506 p = skip_to_semicolon (p1 + 1);
6511 error (_("Remote register badly formatted: %s\nhere: %s"),
6516 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6520 case 'S': /* Old style status, just signal only. */
6524 event->ws.kind = TARGET_WAITKIND_STOPPED;
6525 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6526 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6527 event->ws.value.sig = (enum gdb_signal) sig;
6529 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6532 case 'w': /* Thread exited. */
6537 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6538 p = unpack_varlen_hex (&buf[1], &value);
6539 event->ws.value.integer = value;
6541 error (_("stop reply packet badly formatted: %s"), buf);
6542 event->ptid = read_ptid (++p, &p);
6545 case 'W': /* Target exited. */
6552 /* GDB used to accept only 2 hex chars here. Stubs should
6553 only send more if they detect GDB supports multi-process
6555 p = unpack_varlen_hex (&buf[1], &value);
6559 /* The remote process exited. */
6560 event->ws.kind = TARGET_WAITKIND_EXITED;
6561 event->ws.value.integer = value;
6565 /* The remote process exited with a signal. */
6566 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6567 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6568 event->ws.value.sig = (enum gdb_signal) value;
6570 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6573 /* If no process is specified, assume inferior_ptid. */
6574 pid = ptid_get_pid (inferior_ptid);
6583 else if (startswith (p, "process:"))
6587 p += sizeof ("process:") - 1;
6588 unpack_varlen_hex (p, &upid);
6592 error (_("unknown stop reply packet: %s"), buf);
6595 error (_("unknown stop reply packet: %s"), buf);
6596 event->ptid = pid_to_ptid (pid);
6601 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6602 error (_("No process or thread specified in stop reply: %s"), buf);
6605 /* When the stub wants to tell GDB about a new notification reply, it
6606 sends a notification (%Stop, for example). Those can come it at
6607 any time, hence, we have to make sure that any pending
6608 putpkt/getpkt sequence we're making is finished, before querying
6609 the stub for more events with the corresponding ack command
6610 (vStopped, for example). E.g., if we started a vStopped sequence
6611 immediately upon receiving the notification, something like this
6619 1.6) <-- (registers reply to step #1.3)
6621 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6624 To solve this, whenever we parse a %Stop notification successfully,
6625 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6626 doing whatever we were doing:
6632 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6633 2.5) <-- (registers reply to step #2.3)
6635 Eventualy after step #2.5, we return to the event loop, which
6636 notices there's an event on the
6637 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6638 associated callback --- the function below. At this point, we're
6639 always safe to start a vStopped sequence. :
6642 2.7) <-- T05 thread:2
6648 remote_notif_get_pending_events (struct notif_client *nc)
6650 struct remote_state *rs = get_remote_state ();
6652 if (rs->notif_state->pending_event[nc->id] != NULL)
6655 fprintf_unfiltered (gdb_stdlog,
6656 "notif: process: '%s' ack pending event\n",
6660 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6661 rs->notif_state->pending_event[nc->id] = NULL;
6665 getpkt (&rs->buf, &rs->buf_size, 0);
6666 if (strcmp (rs->buf, "OK") == 0)
6669 remote_notif_ack (nc, rs->buf);
6675 fprintf_unfiltered (gdb_stdlog,
6676 "notif: process: '%s' no pending reply\n",
6681 /* Called when it is decided that STOP_REPLY holds the info of the
6682 event that is to be returned to the core. This function always
6683 destroys STOP_REPLY. */
6686 process_stop_reply (struct stop_reply *stop_reply,
6687 struct target_waitstatus *status)
6691 *status = stop_reply->ws;
6692 ptid = stop_reply->ptid;
6694 /* If no thread/process was reported by the stub, assume the current
6696 if (ptid_equal (ptid, null_ptid))
6697 ptid = inferior_ptid;
6699 if (status->kind != TARGET_WAITKIND_EXITED
6700 && status->kind != TARGET_WAITKIND_SIGNALLED)
6702 struct remote_state *rs = get_remote_state ();
6703 struct private_thread_info *remote_thr;
6705 /* Expedited registers. */
6706 if (stop_reply->regcache)
6708 struct regcache *regcache
6709 = get_thread_arch_regcache (ptid, target_gdbarch ());
6714 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6716 regcache_raw_supply (regcache, reg->num, reg->data);
6717 VEC_free (cached_reg_t, stop_reply->regcache);
6720 remote_notice_new_inferior (ptid, 0);
6721 remote_thr = demand_private_info (ptid);
6722 remote_thr->core = stop_reply->core;
6723 remote_thr->stop_reason = stop_reply->stop_reason;
6724 remote_thr->watch_data_address = stop_reply->watch_data_address;
6727 stop_reply_xfree (stop_reply);
6731 /* The non-stop mode version of target_wait. */
6734 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6736 struct remote_state *rs = get_remote_state ();
6737 struct stop_reply *stop_reply;
6741 /* If in non-stop mode, get out of getpkt even if a
6742 notification is received. */
6744 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6745 0 /* forever */, &is_notif);
6748 if (ret != -1 && !is_notif)
6751 case 'E': /* Error of some sort. */
6752 /* We're out of sync with the target now. Did it continue
6753 or not? We can't tell which thread it was in non-stop,
6754 so just ignore this. */
6755 warning (_("Remote failure reply: %s"), rs->buf);
6757 case 'O': /* Console output. */
6758 remote_console_output (rs->buf + 1);
6761 warning (_("Invalid remote reply: %s"), rs->buf);
6765 /* Acknowledge a pending stop reply that may have arrived in the
6767 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6768 remote_notif_get_pending_events (¬if_client_stop);
6770 /* If indeed we noticed a stop reply, we're done. */
6771 stop_reply = queued_stop_reply (ptid);
6772 if (stop_reply != NULL)
6773 return process_stop_reply (stop_reply, status);
6775 /* Still no event. If we're just polling for an event, then
6776 return to the event loop. */
6777 if (options & TARGET_WNOHANG)
6779 status->kind = TARGET_WAITKIND_IGNORE;
6780 return minus_one_ptid;
6783 /* Otherwise do a blocking wait. */
6784 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6785 1 /* forever */, &is_notif);
6789 /* Wait until the remote machine stops, then return, storing status in
6790 STATUS just as `wait' would. */
6793 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6795 struct remote_state *rs = get_remote_state ();
6796 ptid_t event_ptid = null_ptid;
6798 struct stop_reply *stop_reply;
6802 status->kind = TARGET_WAITKIND_IGNORE;
6803 status->value.integer = 0;
6805 stop_reply = queued_stop_reply (ptid);
6806 if (stop_reply != NULL)
6807 return process_stop_reply (stop_reply, status);
6809 if (rs->cached_wait_status)
6810 /* Use the cached wait status, but only once. */
6811 rs->cached_wait_status = 0;
6816 int forever = ((options & TARGET_WNOHANG) == 0
6817 && wait_forever_enabled_p);
6819 if (!rs->waiting_for_stop_reply)
6821 status->kind = TARGET_WAITKIND_NO_RESUMED;
6822 return minus_one_ptid;
6825 if (!target_is_async_p ())
6827 ofunc = signal (SIGINT, sync_remote_interrupt);
6828 /* If the user hit C-c before this packet, or between packets,
6829 pretend that it was hit right here. */
6830 if (check_quit_flag ())
6833 sync_remote_interrupt (SIGINT);
6837 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6838 _never_ wait for ever -> test on target_is_async_p().
6839 However, before we do that we need to ensure that the caller
6840 knows how to take the target into/out of async mode. */
6841 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6842 forever, &is_notif);
6844 if (!target_is_async_p ())
6845 signal (SIGINT, ofunc);
6847 /* GDB gets a notification. Return to core as this event is
6849 if (ret != -1 && is_notif)
6850 return minus_one_ptid;
6852 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6853 return minus_one_ptid;
6858 /* Assume that the target has acknowledged Ctrl-C unless we receive
6859 an 'F' or 'O' packet. */
6860 if (buf[0] != 'F' && buf[0] != 'O')
6861 rs->ctrlc_pending_p = 0;
6865 case 'E': /* Error of some sort. */
6866 /* We're out of sync with the target now. Did it continue or
6867 not? Not is more likely, so report a stop. */
6868 rs->waiting_for_stop_reply = 0;
6870 warning (_("Remote failure reply: %s"), buf);
6871 status->kind = TARGET_WAITKIND_STOPPED;
6872 status->value.sig = GDB_SIGNAL_0;
6874 case 'F': /* File-I/O request. */
6875 remote_fileio_request (buf, rs->ctrlc_pending_p);
6876 rs->ctrlc_pending_p = 0;
6878 case 'T': case 'S': case 'X': case 'W':
6880 struct stop_reply *stop_reply;
6882 /* There is a stop reply to handle. */
6883 rs->waiting_for_stop_reply = 0;
6886 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6889 event_ptid = process_stop_reply (stop_reply, status);
6892 case 'O': /* Console output. */
6893 remote_console_output (buf + 1);
6896 if (rs->last_sent_signal != GDB_SIGNAL_0)
6898 /* Zero length reply means that we tried 'S' or 'C' and the
6899 remote system doesn't support it. */
6900 target_terminal_ours_for_output ();
6902 ("Can't send signals to this remote system. %s not sent.\n",
6903 gdb_signal_to_name (rs->last_sent_signal));
6904 rs->last_sent_signal = GDB_SIGNAL_0;
6905 target_terminal_inferior ();
6907 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6908 putpkt ((char *) buf);
6911 /* else fallthrough */
6913 warning (_("Invalid remote reply: %s"), buf);
6917 if (status->kind == TARGET_WAITKIND_IGNORE)
6919 /* Nothing interesting happened. If we're doing a non-blocking
6920 poll, we're done. Otherwise, go back to waiting. */
6921 if (options & TARGET_WNOHANG)
6922 return minus_one_ptid;
6926 else if (status->kind != TARGET_WAITKIND_EXITED
6927 && status->kind != TARGET_WAITKIND_SIGNALLED)
6929 if (!ptid_equal (event_ptid, null_ptid))
6930 record_currthread (rs, event_ptid);
6932 event_ptid = inferior_ptid;
6935 /* A process exit. Invalidate our notion of current thread. */
6936 record_currthread (rs, minus_one_ptid);
6941 /* Wait until the remote machine stops, then return, storing status in
6942 STATUS just as `wait' would. */
6945 remote_wait (struct target_ops *ops,
6946 ptid_t ptid, struct target_waitstatus *status, int options)
6950 if (target_is_non_stop_p ())
6951 event_ptid = remote_wait_ns (ptid, status, options);
6953 event_ptid = remote_wait_as (ptid, status, options);
6955 if (target_is_async_p ())
6957 /* If there are are events left in the queue tell the event loop
6959 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6960 mark_async_event_handler (remote_async_inferior_event_token);
6966 /* Fetch a single register using a 'p' packet. */
6969 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6971 struct remote_state *rs = get_remote_state ();
6973 char regp[MAX_REGISTER_SIZE];
6976 if (packet_support (PACKET_p) == PACKET_DISABLE)
6979 if (reg->pnum == -1)
6984 p += hexnumstr (p, reg->pnum);
6987 getpkt (&rs->buf, &rs->buf_size, 0);
6991 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6995 case PACKET_UNKNOWN:
6998 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6999 gdbarch_register_name (get_regcache_arch (regcache),
7004 /* If this register is unfetchable, tell the regcache. */
7007 regcache_raw_supply (regcache, reg->regnum, NULL);
7011 /* Otherwise, parse and supply the value. */
7017 error (_("fetch_register_using_p: early buf termination"));
7019 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7022 regcache_raw_supply (regcache, reg->regnum, regp);
7026 /* Fetch the registers included in the target's 'g' packet. */
7029 send_g_packet (void)
7031 struct remote_state *rs = get_remote_state ();
7034 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7035 remote_send (&rs->buf, &rs->buf_size);
7037 /* We can get out of synch in various cases. If the first character
7038 in the buffer is not a hex character, assume that has happened
7039 and try to fetch another packet to read. */
7040 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7041 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7042 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7043 && rs->buf[0] != 'x') /* New: unavailable register value. */
7046 fprintf_unfiltered (gdb_stdlog,
7047 "Bad register packet; fetching a new packet\n");
7048 getpkt (&rs->buf, &rs->buf_size, 0);
7051 buf_len = strlen (rs->buf);
7053 /* Sanity check the received packet. */
7054 if (buf_len % 2 != 0)
7055 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7061 process_g_packet (struct regcache *regcache)
7063 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7064 struct remote_state *rs = get_remote_state ();
7065 struct remote_arch_state *rsa = get_remote_arch_state ();
7070 buf_len = strlen (rs->buf);
7072 /* Further sanity checks, with knowledge of the architecture. */
7073 if (buf_len > 2 * rsa->sizeof_g_packet)
7074 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7076 /* Save the size of the packet sent to us by the target. It is used
7077 as a heuristic when determining the max size of packets that the
7078 target can safely receive. */
7079 if (rsa->actual_register_packet_size == 0)
7080 rsa->actual_register_packet_size = buf_len;
7082 /* If this is smaller than we guessed the 'g' packet would be,
7083 update our records. A 'g' reply that doesn't include a register's
7084 value implies either that the register is not available, or that
7085 the 'p' packet must be used. */
7086 if (buf_len < 2 * rsa->sizeof_g_packet)
7088 rsa->sizeof_g_packet = buf_len / 2;
7090 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7092 if (rsa->regs[i].pnum == -1)
7095 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7096 rsa->regs[i].in_g_packet = 0;
7098 rsa->regs[i].in_g_packet = 1;
7102 regs = (char *) alloca (rsa->sizeof_g_packet);
7104 /* Unimplemented registers read as all bits zero. */
7105 memset (regs, 0, rsa->sizeof_g_packet);
7107 /* Reply describes registers byte by byte, each byte encoded as two
7108 hex characters. Suck them all up, then supply them to the
7109 register cacheing/storage mechanism. */
7112 for (i = 0; i < rsa->sizeof_g_packet; i++)
7114 if (p[0] == 0 || p[1] == 0)
7115 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7116 internal_error (__FILE__, __LINE__,
7117 _("unexpected end of 'g' packet reply"));
7119 if (p[0] == 'x' && p[1] == 'x')
7120 regs[i] = 0; /* 'x' */
7122 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7126 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7128 struct packet_reg *r = &rsa->regs[i];
7132 if (r->offset * 2 >= strlen (rs->buf))
7133 /* This shouldn't happen - we adjusted in_g_packet above. */
7134 internal_error (__FILE__, __LINE__,
7135 _("unexpected end of 'g' packet reply"));
7136 else if (rs->buf[r->offset * 2] == 'x')
7138 gdb_assert (r->offset * 2 < strlen (rs->buf));
7139 /* The register isn't available, mark it as such (at
7140 the same time setting the value to zero). */
7141 regcache_raw_supply (regcache, r->regnum, NULL);
7144 regcache_raw_supply (regcache, r->regnum,
7151 fetch_registers_using_g (struct regcache *regcache)
7154 process_g_packet (regcache);
7157 /* Make the remote selected traceframe match GDB's selected
7161 set_remote_traceframe (void)
7164 struct remote_state *rs = get_remote_state ();
7166 if (rs->remote_traceframe_number == get_traceframe_number ())
7169 /* Avoid recursion, remote_trace_find calls us again. */
7170 rs->remote_traceframe_number = get_traceframe_number ();
7172 newnum = target_trace_find (tfind_number,
7173 get_traceframe_number (), 0, 0, NULL);
7175 /* Should not happen. If it does, all bets are off. */
7176 if (newnum != get_traceframe_number ())
7177 warning (_("could not set remote traceframe"));
7181 remote_fetch_registers (struct target_ops *ops,
7182 struct regcache *regcache, int regnum)
7184 struct remote_arch_state *rsa = get_remote_arch_state ();
7187 set_remote_traceframe ();
7188 set_general_thread (inferior_ptid);
7192 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7194 gdb_assert (reg != NULL);
7196 /* If this register might be in the 'g' packet, try that first -
7197 we are likely to read more than one register. If this is the
7198 first 'g' packet, we might be overly optimistic about its
7199 contents, so fall back to 'p'. */
7200 if (reg->in_g_packet)
7202 fetch_registers_using_g (regcache);
7203 if (reg->in_g_packet)
7207 if (fetch_register_using_p (regcache, reg))
7210 /* This register is not available. */
7211 regcache_raw_supply (regcache, reg->regnum, NULL);
7216 fetch_registers_using_g (regcache);
7218 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7219 if (!rsa->regs[i].in_g_packet)
7220 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7222 /* This register is not available. */
7223 regcache_raw_supply (regcache, i, NULL);
7227 /* Prepare to store registers. Since we may send them all (using a
7228 'G' request), we have to read out the ones we don't want to change
7232 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7234 struct remote_arch_state *rsa = get_remote_arch_state ();
7236 gdb_byte buf[MAX_REGISTER_SIZE];
7238 /* Make sure the entire registers array is valid. */
7239 switch (packet_support (PACKET_P))
7241 case PACKET_DISABLE:
7242 case PACKET_SUPPORT_UNKNOWN:
7243 /* Make sure all the necessary registers are cached. */
7244 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7245 if (rsa->regs[i].in_g_packet)
7246 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7253 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7254 packet was not recognized. */
7257 store_register_using_P (const struct regcache *regcache,
7258 struct packet_reg *reg)
7260 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7261 struct remote_state *rs = get_remote_state ();
7262 /* Try storing a single register. */
7263 char *buf = rs->buf;
7264 gdb_byte regp[MAX_REGISTER_SIZE];
7267 if (packet_support (PACKET_P) == PACKET_DISABLE)
7270 if (reg->pnum == -1)
7273 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7274 p = buf + strlen (buf);
7275 regcache_raw_collect (regcache, reg->regnum, regp);
7276 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7278 getpkt (&rs->buf, &rs->buf_size, 0);
7280 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7285 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7286 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7287 case PACKET_UNKNOWN:
7290 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7294 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7295 contents of the register cache buffer. FIXME: ignores errors. */
7298 store_registers_using_G (const struct regcache *regcache)
7300 struct remote_state *rs = get_remote_state ();
7301 struct remote_arch_state *rsa = get_remote_arch_state ();
7305 /* Extract all the registers in the regcache copying them into a
7310 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7311 memset (regs, 0, rsa->sizeof_g_packet);
7312 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7314 struct packet_reg *r = &rsa->regs[i];
7317 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7321 /* Command describes registers byte by byte,
7322 each byte encoded as two hex characters. */
7325 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7327 bin2hex (regs, p, rsa->sizeof_g_packet);
7329 getpkt (&rs->buf, &rs->buf_size, 0);
7330 if (packet_check_result (rs->buf) == PACKET_ERROR)
7331 error (_("Could not write registers; remote failure reply '%s'"),
7335 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7336 of the register cache buffer. FIXME: ignores errors. */
7339 remote_store_registers (struct target_ops *ops,
7340 struct regcache *regcache, int regnum)
7342 struct remote_arch_state *rsa = get_remote_arch_state ();
7345 set_remote_traceframe ();
7346 set_general_thread (inferior_ptid);
7350 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7352 gdb_assert (reg != NULL);
7354 /* Always prefer to store registers using the 'P' packet if
7355 possible; we often change only a small number of registers.
7356 Sometimes we change a larger number; we'd need help from a
7357 higher layer to know to use 'G'. */
7358 if (store_register_using_P (regcache, reg))
7361 /* For now, don't complain if we have no way to write the
7362 register. GDB loses track of unavailable registers too
7363 easily. Some day, this may be an error. We don't have
7364 any way to read the register, either... */
7365 if (!reg->in_g_packet)
7368 store_registers_using_G (regcache);
7372 store_registers_using_G (regcache);
7374 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7375 if (!rsa->regs[i].in_g_packet)
7376 if (!store_register_using_P (regcache, &rsa->regs[i]))
7377 /* See above for why we do not issue an error here. */
7382 /* Return the number of hex digits in num. */
7385 hexnumlen (ULONGEST num)
7389 for (i = 0; num != 0; i++)
7395 /* Set BUF to the minimum number of hex digits representing NUM. */
7398 hexnumstr (char *buf, ULONGEST num)
7400 int len = hexnumlen (num);
7402 return hexnumnstr (buf, num, len);
7406 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7409 hexnumnstr (char *buf, ULONGEST num, int width)
7415 for (i = width - 1; i >= 0; i--)
7417 buf[i] = "0123456789abcdef"[(num & 0xf)];
7424 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7427 remote_address_masked (CORE_ADDR addr)
7429 unsigned int address_size = remote_address_size;
7431 /* If "remoteaddresssize" was not set, default to target address size. */
7433 address_size = gdbarch_addr_bit (target_gdbarch ());
7435 if (address_size > 0
7436 && address_size < (sizeof (ULONGEST) * 8))
7438 /* Only create a mask when that mask can safely be constructed
7439 in a ULONGEST variable. */
7442 mask = (mask << address_size) - 1;
7448 /* Determine whether the remote target supports binary downloading.
7449 This is accomplished by sending a no-op memory write of zero length
7450 to the target at the specified address. It does not suffice to send
7451 the whole packet, since many stubs strip the eighth bit and
7452 subsequently compute a wrong checksum, which causes real havoc with
7455 NOTE: This can still lose if the serial line is not eight-bit
7456 clean. In cases like this, the user should clear "remote
7460 check_binary_download (CORE_ADDR addr)
7462 struct remote_state *rs = get_remote_state ();
7464 switch (packet_support (PACKET_X))
7466 case PACKET_DISABLE:
7470 case PACKET_SUPPORT_UNKNOWN:
7476 p += hexnumstr (p, (ULONGEST) addr);
7478 p += hexnumstr (p, (ULONGEST) 0);
7482 putpkt_binary (rs->buf, (int) (p - rs->buf));
7483 getpkt (&rs->buf, &rs->buf_size, 0);
7485 if (rs->buf[0] == '\0')
7488 fprintf_unfiltered (gdb_stdlog,
7489 "binary downloading NOT "
7490 "supported by target\n");
7491 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7496 fprintf_unfiltered (gdb_stdlog,
7497 "binary downloading supported by target\n");
7498 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7505 /* Helper function to resize the payload in order to try to get a good
7506 alignment. We try to write an amount of data such that the next write will
7507 start on an address aligned on REMOTE_ALIGN_WRITES. */
7510 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7512 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7515 /* Write memory data directly to the remote machine.
7516 This does not inform the data cache; the data cache uses this.
7517 HEADER is the starting part of the packet.
7518 MEMADDR is the address in the remote memory space.
7519 MYADDR is the address of the buffer in our space.
7520 LEN_UNITS is the number of addressable units to write.
7521 UNIT_SIZE is the length in bytes of an addressable unit.
7522 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7523 should send data as binary ('X'), or hex-encoded ('M').
7525 The function creates packet of the form
7526 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7528 where encoding of <DATA> is terminated by PACKET_FORMAT.
7530 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7533 Return the transferred status, error or OK (an
7534 'enum target_xfer_status' value). Save the number of addressable units
7535 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7537 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7538 exchange between gdb and the stub could look like (?? in place of the
7544 -> $M1000,3:eeeeffffeeee#??
7548 <- eeeeffffeeeedddd */
7550 static enum target_xfer_status
7551 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7552 const gdb_byte *myaddr, ULONGEST len_units,
7553 int unit_size, ULONGEST *xfered_len_units,
7554 char packet_format, int use_length)
7556 struct remote_state *rs = get_remote_state ();
7562 int payload_capacity_bytes;
7563 int payload_length_bytes;
7565 if (packet_format != 'X' && packet_format != 'M')
7566 internal_error (__FILE__, __LINE__,
7567 _("remote_write_bytes_aux: bad packet format"));
7570 return TARGET_XFER_EOF;
7572 payload_capacity_bytes = get_memory_write_packet_size ();
7574 /* The packet buffer will be large enough for the payload;
7575 get_memory_packet_size ensures this. */
7578 /* Compute the size of the actual payload by subtracting out the
7579 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7581 payload_capacity_bytes -= strlen ("$,:#NN");
7583 /* The comma won't be used. */
7584 payload_capacity_bytes += 1;
7585 payload_capacity_bytes -= strlen (header);
7586 payload_capacity_bytes -= hexnumlen (memaddr);
7588 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7590 strcat (rs->buf, header);
7591 p = rs->buf + strlen (header);
7593 /* Compute a best guess of the number of bytes actually transfered. */
7594 if (packet_format == 'X')
7596 /* Best guess at number of bytes that will fit. */
7597 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7599 payload_capacity_bytes -= hexnumlen (todo_units);
7600 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7604 /* Number of bytes that will fit. */
7605 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7607 payload_capacity_bytes -= hexnumlen (todo_units);
7608 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7611 if (todo_units <= 0)
7612 internal_error (__FILE__, __LINE__,
7613 _("minimum packet size too small to write data"));
7615 /* If we already need another packet, then try to align the end
7616 of this packet to a useful boundary. */
7617 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7618 todo_units = align_for_efficient_write (todo_units, memaddr);
7620 /* Append "<memaddr>". */
7621 memaddr = remote_address_masked (memaddr);
7622 p += hexnumstr (p, (ULONGEST) memaddr);
7629 /* Append the length and retain its location and size. It may need to be
7630 adjusted once the packet body has been created. */
7632 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7640 /* Append the packet body. */
7641 if (packet_format == 'X')
7643 /* Binary mode. Send target system values byte by byte, in
7644 increasing byte addresses. Only escape certain critical
7646 payload_length_bytes =
7647 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7648 &units_written, payload_capacity_bytes);
7650 /* If not all TODO units fit, then we'll need another packet. Make
7651 a second try to keep the end of the packet aligned. Don't do
7652 this if the packet is tiny. */
7653 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7657 new_todo_units = align_for_efficient_write (units_written, memaddr);
7659 if (new_todo_units != units_written)
7660 payload_length_bytes =
7661 remote_escape_output (myaddr, new_todo_units, unit_size,
7662 (gdb_byte *) p, &units_written,
7663 payload_capacity_bytes);
7666 p += payload_length_bytes;
7667 if (use_length && units_written < todo_units)
7669 /* Escape chars have filled up the buffer prematurely,
7670 and we have actually sent fewer units than planned.
7671 Fix-up the length field of the packet. Use the same
7672 number of characters as before. */
7673 plen += hexnumnstr (plen, (ULONGEST) units_written,
7675 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7680 /* Normal mode: Send target system values byte by byte, in
7681 increasing byte addresses. Each byte is encoded as a two hex
7683 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7684 units_written = todo_units;
7687 putpkt_binary (rs->buf, (int) (p - rs->buf));
7688 getpkt (&rs->buf, &rs->buf_size, 0);
7690 if (rs->buf[0] == 'E')
7691 return TARGET_XFER_E_IO;
7693 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7694 send fewer units than we'd planned. */
7695 *xfered_len_units = (ULONGEST) units_written;
7696 return TARGET_XFER_OK;
7699 /* Write memory data directly to the remote machine.
7700 This does not inform the data cache; the data cache uses this.
7701 MEMADDR is the address in the remote memory space.
7702 MYADDR is the address of the buffer in our space.
7703 LEN is the number of bytes.
7705 Return the transferred status, error or OK (an
7706 'enum target_xfer_status' value). Save the number of bytes
7707 transferred in *XFERED_LEN. Only transfer a single packet. */
7709 static enum target_xfer_status
7710 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7711 int unit_size, ULONGEST *xfered_len)
7713 char *packet_format = 0;
7715 /* Check whether the target supports binary download. */
7716 check_binary_download (memaddr);
7718 switch (packet_support (PACKET_X))
7721 packet_format = "X";
7723 case PACKET_DISABLE:
7724 packet_format = "M";
7726 case PACKET_SUPPORT_UNKNOWN:
7727 internal_error (__FILE__, __LINE__,
7728 _("remote_write_bytes: bad internal state"));
7730 internal_error (__FILE__, __LINE__, _("bad switch"));
7733 return remote_write_bytes_aux (packet_format,
7734 memaddr, myaddr, len, unit_size, xfered_len,
7735 packet_format[0], 1);
7738 /* Read memory data directly from the remote machine.
7739 This does not use the data cache; the data cache uses this.
7740 MEMADDR is the address in the remote memory space.
7741 MYADDR is the address of the buffer in our space.
7742 LEN_UNITS is the number of addressable memory units to read..
7743 UNIT_SIZE is the length in bytes of an addressable unit.
7745 Return the transferred status, error or OK (an
7746 'enum target_xfer_status' value). Save the number of bytes
7747 transferred in *XFERED_LEN_UNITS.
7749 See the comment of remote_write_bytes_aux for an example of
7750 memory read/write exchange between gdb and the stub. */
7752 static enum target_xfer_status
7753 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7754 int unit_size, ULONGEST *xfered_len_units)
7756 struct remote_state *rs = get_remote_state ();
7757 int buf_size_bytes; /* Max size of packet output buffer. */
7762 buf_size_bytes = get_memory_read_packet_size ();
7763 /* The packet buffer will be large enough for the payload;
7764 get_memory_packet_size ensures this. */
7766 /* Number of units that will fit. */
7767 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7769 /* Construct "m"<memaddr>","<len>". */
7770 memaddr = remote_address_masked (memaddr);
7773 p += hexnumstr (p, (ULONGEST) memaddr);
7775 p += hexnumstr (p, (ULONGEST) todo_units);
7778 getpkt (&rs->buf, &rs->buf_size, 0);
7779 if (rs->buf[0] == 'E'
7780 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7781 && rs->buf[3] == '\0')
7782 return TARGET_XFER_E_IO;
7783 /* Reply describes memory byte by byte, each byte encoded as two hex
7786 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7787 /* Return what we have. Let higher layers handle partial reads. */
7788 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7789 return TARGET_XFER_OK;
7792 /* Using the set of read-only target sections of remote, read live
7795 For interface/parameters/return description see target.h,
7798 static enum target_xfer_status
7799 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7800 ULONGEST memaddr, ULONGEST len,
7801 int unit_size, ULONGEST *xfered_len)
7803 struct target_section *secp;
7804 struct target_section_table *table;
7806 secp = target_section_by_addr (ops, memaddr);
7808 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7809 secp->the_bfd_section)
7812 struct target_section *p;
7813 ULONGEST memend = memaddr + len;
7815 table = target_get_section_table (ops);
7817 for (p = table->sections; p < table->sections_end; p++)
7819 if (memaddr >= p->addr)
7821 if (memend <= p->endaddr)
7823 /* Entire transfer is within this section. */
7824 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7827 else if (memaddr >= p->endaddr)
7829 /* This section ends before the transfer starts. */
7834 /* This section overlaps the transfer. Just do half. */
7835 len = p->endaddr - memaddr;
7836 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7843 return TARGET_XFER_EOF;
7846 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7847 first if the requested memory is unavailable in traceframe.
7848 Otherwise, fall back to remote_read_bytes_1. */
7850 static enum target_xfer_status
7851 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7852 gdb_byte *myaddr, ULONGEST len, int unit_size,
7853 ULONGEST *xfered_len)
7856 return TARGET_XFER_EOF;
7858 if (get_traceframe_number () != -1)
7860 VEC(mem_range_s) *available;
7862 /* If we fail to get the set of available memory, then the
7863 target does not support querying traceframe info, and so we
7864 attempt reading from the traceframe anyway (assuming the
7865 target implements the old QTro packet then). */
7866 if (traceframe_available_memory (&available, memaddr, len))
7868 struct cleanup *old_chain;
7870 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7872 if (VEC_empty (mem_range_s, available)
7873 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7875 enum target_xfer_status res;
7877 /* Don't read into the traceframe's available
7879 if (!VEC_empty (mem_range_s, available))
7881 LONGEST oldlen = len;
7883 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7884 gdb_assert (len <= oldlen);
7887 do_cleanups (old_chain);
7889 /* This goes through the topmost target again. */
7890 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7891 len, unit_size, xfered_len);
7892 if (res == TARGET_XFER_OK)
7893 return TARGET_XFER_OK;
7896 /* No use trying further, we know some memory starting
7897 at MEMADDR isn't available. */
7899 return TARGET_XFER_UNAVAILABLE;
7903 /* Don't try to read more than how much is available, in
7904 case the target implements the deprecated QTro packet to
7905 cater for older GDBs (the target's knowledge of read-only
7906 sections may be outdated by now). */
7907 len = VEC_index (mem_range_s, available, 0)->length;
7909 do_cleanups (old_chain);
7913 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7918 /* Sends a packet with content determined by the printf format string
7919 FORMAT and the remaining arguments, then gets the reply. Returns
7920 whether the packet was a success, a failure, or unknown. */
7922 static enum packet_result remote_send_printf (const char *format, ...)
7923 ATTRIBUTE_PRINTF (1, 2);
7925 static enum packet_result
7926 remote_send_printf (const char *format, ...)
7928 struct remote_state *rs = get_remote_state ();
7929 int max_size = get_remote_packet_size ();
7932 va_start (ap, format);
7935 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7936 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7938 if (putpkt (rs->buf) < 0)
7939 error (_("Communication problem with target."));
7942 getpkt (&rs->buf, &rs->buf_size, 0);
7944 return packet_check_result (rs->buf);
7948 restore_remote_timeout (void *p)
7950 int value = *(int *)p;
7952 remote_timeout = value;
7955 /* Flash writing can take quite some time. We'll set
7956 effectively infinite timeout for flash operations.
7957 In future, we'll need to decide on a better approach. */
7958 static const int remote_flash_timeout = 1000;
7961 remote_flash_erase (struct target_ops *ops,
7962 ULONGEST address, LONGEST length)
7964 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7965 int saved_remote_timeout = remote_timeout;
7966 enum packet_result ret;
7967 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7968 &saved_remote_timeout);
7970 remote_timeout = remote_flash_timeout;
7972 ret = remote_send_printf ("vFlashErase:%s,%s",
7973 phex (address, addr_size),
7977 case PACKET_UNKNOWN:
7978 error (_("Remote target does not support flash erase"));
7980 error (_("Error erasing flash with vFlashErase packet"));
7985 do_cleanups (back_to);
7988 static enum target_xfer_status
7989 remote_flash_write (struct target_ops *ops, ULONGEST address,
7990 ULONGEST length, ULONGEST *xfered_len,
7991 const gdb_byte *data)
7993 int saved_remote_timeout = remote_timeout;
7994 enum target_xfer_status ret;
7995 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7996 &saved_remote_timeout);
7998 remote_timeout = remote_flash_timeout;
7999 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8001 do_cleanups (back_to);
8007 remote_flash_done (struct target_ops *ops)
8009 int saved_remote_timeout = remote_timeout;
8011 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8012 &saved_remote_timeout);
8014 remote_timeout = remote_flash_timeout;
8015 ret = remote_send_printf ("vFlashDone");
8016 do_cleanups (back_to);
8020 case PACKET_UNKNOWN:
8021 error (_("Remote target does not support vFlashDone"));
8023 error (_("Error finishing flash operation"));
8030 remote_files_info (struct target_ops *ignore)
8032 puts_filtered ("Debugging a target over a serial line.\n");
8035 /* Stuff for dealing with the packets which are part of this protocol.
8036 See comment at top of file for details. */
8038 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8039 error to higher layers. Called when a serial error is detected.
8040 The exception message is STRING, followed by a colon and a blank,
8041 the system error message for errno at function entry and final dot
8042 for output compatibility with throw_perror_with_name. */
8045 unpush_and_perror (const char *string)
8047 int saved_errno = errno;
8049 remote_unpush_target ();
8050 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8051 safe_strerror (saved_errno));
8054 /* Read a single character from the remote end. */
8057 readchar (int timeout)
8060 struct remote_state *rs = get_remote_state ();
8062 ch = serial_readchar (rs->remote_desc, timeout);
8067 switch ((enum serial_rc) ch)
8070 remote_unpush_target ();
8071 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8074 unpush_and_perror (_("Remote communication error. "
8075 "Target disconnected."));
8077 case SERIAL_TIMEOUT:
8083 /* Wrapper for serial_write that closes the target and throws if
8087 remote_serial_write (const char *str, int len)
8089 struct remote_state *rs = get_remote_state ();
8091 if (serial_write (rs->remote_desc, str, len))
8093 unpush_and_perror (_("Remote communication error. "
8094 "Target disconnected."));
8098 /* Send the command in *BUF to the remote machine, and read the reply
8099 into *BUF. Report an error if we get an error reply. Resize
8100 *BUF using xrealloc if necessary to hold the result, and update
8104 remote_send (char **buf,
8108 getpkt (buf, sizeof_buf, 0);
8110 if ((*buf)[0] == 'E')
8111 error (_("Remote failure reply: %s"), *buf);
8114 /* Return a pointer to an xmalloc'ed string representing an escaped
8115 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8116 etc. The caller is responsible for releasing the returned
8120 escape_buffer (const char *buf, int n)
8122 struct cleanup *old_chain;
8123 struct ui_file *stb;
8126 stb = mem_fileopen ();
8127 old_chain = make_cleanup_ui_file_delete (stb);
8129 fputstrn_unfiltered (buf, n, '\\', stb);
8130 str = ui_file_xstrdup (stb, NULL);
8131 do_cleanups (old_chain);
8135 /* Display a null-terminated packet on stdout, for debugging, using C
8139 print_packet (const char *buf)
8141 puts_filtered ("\"");
8142 fputstr_filtered (buf, '"', gdb_stdout);
8143 puts_filtered ("\"");
8147 putpkt (const char *buf)
8149 return putpkt_binary (buf, strlen (buf));
8152 /* Send a packet to the remote machine, with error checking. The data
8153 of the packet is in BUF. The string in BUF can be at most
8154 get_remote_packet_size () - 5 to account for the $, # and checksum,
8155 and for a possible /0 if we are debugging (remote_debug) and want
8156 to print the sent packet as a string. */
8159 putpkt_binary (const char *buf, int cnt)
8161 struct remote_state *rs = get_remote_state ();
8163 unsigned char csum = 0;
8164 char *buf2 = (char *) xmalloc (cnt + 6);
8165 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8172 /* Catch cases like trying to read memory or listing threads while
8173 we're waiting for a stop reply. The remote server wouldn't be
8174 ready to handle this request, so we'd hang and timeout. We don't
8175 have to worry about this in synchronous mode, because in that
8176 case it's not possible to issue a command while the target is
8177 running. This is not a problem in non-stop mode, because in that
8178 case, the stub is always ready to process serial input. */
8179 if (!target_is_non_stop_p ()
8180 && target_is_async_p ()
8181 && rs->waiting_for_stop_reply)
8183 error (_("Cannot execute this command while the target is running.\n"
8184 "Use the \"interrupt\" command to stop the target\n"
8185 "and then try again."));
8188 /* We're sending out a new packet. Make sure we don't look at a
8189 stale cached response. */
8190 rs->cached_wait_status = 0;
8192 /* Copy the packet into buffer BUF2, encapsulating it
8193 and giving it a checksum. */
8198 for (i = 0; i < cnt; i++)
8204 *p++ = tohex ((csum >> 4) & 0xf);
8205 *p++ = tohex (csum & 0xf);
8207 /* Send it over and over until we get a positive ack. */
8211 int started_error_output = 0;
8215 struct cleanup *old_chain;
8219 str = escape_buffer (buf2, p - buf2);
8220 old_chain = make_cleanup (xfree, str);
8221 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8222 gdb_flush (gdb_stdlog);
8223 do_cleanups (old_chain);
8225 remote_serial_write (buf2, p - buf2);
8227 /* If this is a no acks version of the remote protocol, send the
8228 packet and move on. */
8232 /* Read until either a timeout occurs (-2) or '+' is read.
8233 Handle any notification that arrives in the mean time. */
8236 ch = readchar (remote_timeout);
8244 case SERIAL_TIMEOUT:
8247 if (started_error_output)
8249 putchar_unfiltered ('\n');
8250 started_error_output = 0;
8259 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8260 do_cleanups (old_chain);
8264 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8266 case SERIAL_TIMEOUT:
8270 do_cleanups (old_chain);
8273 break; /* Retransmit buffer. */
8277 fprintf_unfiltered (gdb_stdlog,
8278 "Packet instead of Ack, ignoring it\n");
8279 /* It's probably an old response sent because an ACK
8280 was lost. Gobble up the packet and ack it so it
8281 doesn't get retransmitted when we resend this
8284 remote_serial_write ("+", 1);
8285 continue; /* Now, go look for +. */
8292 /* If we got a notification, handle it, and go back to looking
8294 /* We've found the start of a notification. Now
8295 collect the data. */
8296 val = read_frame (&rs->buf, &rs->buf_size);
8301 struct cleanup *old_chain;
8304 str = escape_buffer (rs->buf, val);
8305 old_chain = make_cleanup (xfree, str);
8306 fprintf_unfiltered (gdb_stdlog,
8307 " Notification received: %s\n",
8309 do_cleanups (old_chain);
8311 handle_notification (rs->notif_state, rs->buf);
8312 /* We're in sync now, rewait for the ack. */
8319 if (!started_error_output)
8321 started_error_output = 1;
8322 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8324 fputc_unfiltered (ch & 0177, gdb_stdlog);
8325 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8334 if (!started_error_output)
8336 started_error_output = 1;
8337 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8339 fputc_unfiltered (ch & 0177, gdb_stdlog);
8343 break; /* Here to retransmit. */
8347 /* This is wrong. If doing a long backtrace, the user should be
8348 able to get out next time we call QUIT, without anything as
8349 violent as interrupt_query. If we want to provide a way out of
8350 here without getting to the next QUIT, it should be based on
8351 hitting ^C twice as in remote_wait. */
8360 do_cleanups (old_chain);
8364 /* Come here after finding the start of a frame when we expected an
8365 ack. Do our best to discard the rest of this packet. */
8374 c = readchar (remote_timeout);
8377 case SERIAL_TIMEOUT:
8378 /* Nothing we can do. */
8381 /* Discard the two bytes of checksum and stop. */
8382 c = readchar (remote_timeout);
8384 c = readchar (remote_timeout);
8387 case '*': /* Run length encoding. */
8388 /* Discard the repeat count. */
8389 c = readchar (remote_timeout);
8394 /* A regular character. */
8400 /* Come here after finding the start of the frame. Collect the rest
8401 into *BUF, verifying the checksum, length, and handling run-length
8402 compression. NUL terminate the buffer. If there is not enough room,
8403 expand *BUF using xrealloc.
8405 Returns -1 on error, number of characters in buffer (ignoring the
8406 trailing NULL) on success. (could be extended to return one of the
8407 SERIAL status indications). */
8410 read_frame (char **buf_p,
8417 struct remote_state *rs = get_remote_state ();
8424 c = readchar (remote_timeout);
8427 case SERIAL_TIMEOUT:
8429 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8433 fputs_filtered ("Saw new packet start in middle of old one\n",
8435 return -1; /* Start a new packet, count retries. */
8438 unsigned char pktcsum;
8444 check_0 = readchar (remote_timeout);
8446 check_1 = readchar (remote_timeout);
8448 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8451 fputs_filtered ("Timeout in checksum, retrying\n",
8455 else if (check_0 < 0 || check_1 < 0)
8458 fputs_filtered ("Communication error in checksum\n",
8463 /* Don't recompute the checksum; with no ack packets we
8464 don't have any way to indicate a packet retransmission
8469 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8470 if (csum == pktcsum)
8475 struct cleanup *old_chain;
8478 str = escape_buffer (buf, bc);
8479 old_chain = make_cleanup (xfree, str);
8480 fprintf_unfiltered (gdb_stdlog,
8481 "Bad checksum, sentsum=0x%x, "
8482 "csum=0x%x, buf=%s\n",
8483 pktcsum, csum, str);
8484 do_cleanups (old_chain);
8486 /* Number of characters in buffer ignoring trailing
8490 case '*': /* Run length encoding. */
8495 c = readchar (remote_timeout);
8497 repeat = c - ' ' + 3; /* Compute repeat count. */
8499 /* The character before ``*'' is repeated. */
8501 if (repeat > 0 && repeat <= 255 && bc > 0)
8503 if (bc + repeat - 1 >= *sizeof_buf - 1)
8505 /* Make some more room in the buffer. */
8506 *sizeof_buf += repeat;
8507 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8511 memset (&buf[bc], buf[bc - 1], repeat);
8517 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8521 if (bc >= *sizeof_buf - 1)
8523 /* Make some more room in the buffer. */
8525 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8536 /* Read a packet from the remote machine, with error checking, and
8537 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8538 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8539 rather than timing out; this is used (in synchronous mode) to wait
8540 for a target that is is executing user code to stop. */
8541 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8542 don't have to change all the calls to getpkt to deal with the
8543 return value, because at the moment I don't know what the right
8544 thing to do it for those. */
8552 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8556 /* Read a packet from the remote machine, with error checking, and
8557 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8558 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8559 rather than timing out; this is used (in synchronous mode) to wait
8560 for a target that is is executing user code to stop. If FOREVER ==
8561 0, this function is allowed to time out gracefully and return an
8562 indication of this to the caller. Otherwise return the number of
8563 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8564 enough reason to return to the caller. *IS_NOTIF is an output
8565 boolean that indicates whether *BUF holds a notification or not
8566 (a regular packet). */
8569 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8570 int expecting_notif, int *is_notif)
8572 struct remote_state *rs = get_remote_state ();
8578 /* We're reading a new response. Make sure we don't look at a
8579 previously cached response. */
8580 rs->cached_wait_status = 0;
8582 strcpy (*buf, "timeout");
8585 timeout = watchdog > 0 ? watchdog : -1;
8586 else if (expecting_notif)
8587 timeout = 0; /* There should already be a char in the buffer. If
8590 timeout = remote_timeout;
8594 /* Process any number of notifications, and then return when
8598 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8600 for (tries = 1; tries <= MAX_TRIES; tries++)
8602 /* This can loop forever if the remote side sends us
8603 characters continuously, but if it pauses, we'll get
8604 SERIAL_TIMEOUT from readchar because of timeout. Then
8605 we'll count that as a retry.
8607 Note that even when forever is set, we will only wait
8608 forever prior to the start of a packet. After that, we
8609 expect characters to arrive at a brisk pace. They should
8610 show up within remote_timeout intervals. */
8612 c = readchar (timeout);
8613 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8615 if (c == SERIAL_TIMEOUT)
8617 if (expecting_notif)
8618 return -1; /* Don't complain, it's normal to not get
8619 anything in this case. */
8621 if (forever) /* Watchdog went off? Kill the target. */
8624 remote_unpush_target ();
8625 throw_error (TARGET_CLOSE_ERROR,
8626 _("Watchdog timeout has expired. "
8627 "Target detached."));
8630 fputs_filtered ("Timed out.\n", gdb_stdlog);
8634 /* We've found the start of a packet or notification.
8635 Now collect the data. */
8636 val = read_frame (buf, sizeof_buf);
8641 remote_serial_write ("-", 1);
8644 if (tries > MAX_TRIES)
8646 /* We have tried hard enough, and just can't receive the
8647 packet/notification. Give up. */
8648 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8650 /* Skip the ack char if we're in no-ack mode. */
8651 if (!rs->noack_mode)
8652 remote_serial_write ("+", 1);
8656 /* If we got an ordinary packet, return that to our caller. */
8661 struct cleanup *old_chain;
8664 str = escape_buffer (*buf, val);
8665 old_chain = make_cleanup (xfree, str);
8666 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8667 do_cleanups (old_chain);
8670 /* Skip the ack char if we're in no-ack mode. */
8671 if (!rs->noack_mode)
8672 remote_serial_write ("+", 1);
8673 if (is_notif != NULL)
8678 /* If we got a notification, handle it, and go back to looking
8682 gdb_assert (c == '%');
8686 struct cleanup *old_chain;
8689 str = escape_buffer (*buf, val);
8690 old_chain = make_cleanup (xfree, str);
8691 fprintf_unfiltered (gdb_stdlog,
8692 " Notification received: %s\n",
8694 do_cleanups (old_chain);
8696 if (is_notif != NULL)
8699 handle_notification (rs->notif_state, *buf);
8701 /* Notifications require no acknowledgement. */
8703 if (expecting_notif)
8710 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8712 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8716 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8719 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8723 /* Check whether EVENT is a fork event for the process specified
8724 by the pid passed in DATA, and if it is, kill the fork child. */
8727 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8728 QUEUE_ITER (stop_reply_p) *iter,
8732 struct queue_iter_param *param = (struct queue_iter_param *) data;
8733 int parent_pid = *(int *) param->input;
8735 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8737 struct remote_state *rs = get_remote_state ();
8738 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8741 res = remote_vkill (child_pid, rs);
8743 error (_("Can't kill fork child process %d"), child_pid);
8749 /* Kill any new fork children of process PID that haven't been
8750 processed by follow_fork. */
8753 kill_new_fork_children (int pid, struct remote_state *rs)
8755 struct thread_info *thread;
8756 struct notif_client *notif = ¬if_client_stop;
8757 struct queue_iter_param param;
8759 /* Kill the fork child threads of any threads in process PID
8760 that are stopped at a fork event. */
8761 ALL_NON_EXITED_THREADS (thread)
8763 struct target_waitstatus *ws = &thread->pending_follow;
8765 if (is_pending_fork_parent (ws, pid, thread->ptid))
8767 struct remote_state *rs = get_remote_state ();
8768 int child_pid = ptid_get_pid (ws->value.related_pid);
8771 res = remote_vkill (child_pid, rs);
8773 error (_("Can't kill fork child process %d"), child_pid);
8777 /* Check for any pending fork events (not reported or processed yet)
8778 in process PID and kill those fork child threads as well. */
8779 remote_notif_get_pending_events (notif);
8781 param.output = NULL;
8782 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8783 kill_child_of_pending_fork, ¶m);
8788 remote_kill (struct target_ops *ops)
8791 /* Catch errors so the user can quit from gdb even when we
8792 aren't on speaking terms with the remote system. */
8797 CATCH (ex, RETURN_MASK_ERROR)
8799 if (ex.error == TARGET_CLOSE_ERROR)
8801 /* If we got an (EOF) error that caused the target
8802 to go away, then we're done, that's what we wanted.
8803 "k" is susceptible to cause a premature EOF, given
8804 that the remote server isn't actually required to
8805 reply to "k", and it can happen that it doesn't
8806 even get to reply ACK to the "k". */
8810 /* Otherwise, something went wrong. We didn't actually kill
8811 the target. Just propagate the exception, and let the
8812 user or higher layers decide what to do. */
8813 throw_exception (ex);
8817 /* We've killed the remote end, we get to mourn it. Since this is
8818 target remote, single-process, mourning the inferior also
8819 unpushes remote_ops. */
8820 target_mourn_inferior ();
8824 remote_vkill (int pid, struct remote_state *rs)
8826 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8829 /* Tell the remote target to detach. */
8830 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8832 getpkt (&rs->buf, &rs->buf_size, 0);
8834 switch (packet_ok (rs->buf,
8835 &remote_protocol_packets[PACKET_vKill]))
8841 case PACKET_UNKNOWN:
8844 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8849 extended_remote_kill (struct target_ops *ops)
8852 int pid = ptid_get_pid (inferior_ptid);
8853 struct remote_state *rs = get_remote_state ();
8855 /* If we're stopped while forking and we haven't followed yet, kill the
8856 child task. We need to do this before killing the parent task
8857 because if this is a vfork then the parent will be sleeping. */
8858 kill_new_fork_children (pid, rs);
8860 res = remote_vkill (pid, rs);
8861 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8863 /* Don't try 'k' on a multi-process aware stub -- it has no way
8864 to specify the pid. */
8868 getpkt (&rs->buf, &rs->buf_size, 0);
8869 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8872 /* Don't wait for it to die. I'm not really sure it matters whether
8873 we do or not. For the existing stubs, kill is a noop. */
8879 error (_("Can't kill process"));
8881 target_mourn_inferior ();
8885 remote_mourn (struct target_ops *target)
8887 unpush_target (target);
8889 /* remote_close takes care of doing most of the clean up. */
8890 generic_mourn_inferior ();
8894 extended_remote_mourn (struct target_ops *target)
8896 struct remote_state *rs = get_remote_state ();
8898 /* In case we got here due to an error, but we're going to stay
8900 rs->waiting_for_stop_reply = 0;
8902 /* If the current general thread belonged to the process we just
8903 detached from or has exited, the remote side current general
8904 thread becomes undefined. Considering a case like this:
8906 - We just got here due to a detach.
8907 - The process that we're detaching from happens to immediately
8908 report a global breakpoint being hit in non-stop mode, in the
8909 same thread we had selected before.
8910 - GDB attaches to this process again.
8911 - This event happens to be the next event we handle.
8913 GDB would consider that the current general thread didn't need to
8914 be set on the stub side (with Hg), since for all it knew,
8915 GENERAL_THREAD hadn't changed.
8917 Notice that although in all-stop mode, the remote server always
8918 sets the current thread to the thread reporting the stop event,
8919 that doesn't happen in non-stop mode; in non-stop, the stub *must
8920 not* change the current thread when reporting a breakpoint hit,
8921 due to the decoupling of event reporting and event handling.
8923 To keep things simple, we always invalidate our notion of the
8925 record_currthread (rs, minus_one_ptid);
8927 /* Unlike "target remote", we do not want to unpush the target; then
8928 the next time the user says "run", we won't be connected. */
8930 /* Call common code to mark the inferior as not running. */
8931 generic_mourn_inferior ();
8933 if (!have_inferiors ())
8935 if (!remote_multi_process_p (rs))
8937 /* Check whether the target is running now - some remote stubs
8938 automatically restart after kill. */
8940 getpkt (&rs->buf, &rs->buf_size, 0);
8942 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8944 /* Assume that the target has been restarted. Set
8945 inferior_ptid so that bits of core GDB realizes
8946 there's something here, e.g., so that the user can
8947 say "kill" again. */
8948 inferior_ptid = magic_null_ptid;
8955 extended_remote_supports_disable_randomization (struct target_ops *self)
8957 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8961 extended_remote_disable_randomization (int val)
8963 struct remote_state *rs = get_remote_state ();
8966 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8969 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8971 error (_("Target does not support QDisableRandomization."));
8972 if (strcmp (reply, "OK") != 0)
8973 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8977 extended_remote_run (char *args)
8979 struct remote_state *rs = get_remote_state ();
8981 const char *remote_exec_file = get_remote_exec_file ();
8983 /* If the user has disabled vRun support, or we have detected that
8984 support is not available, do not try it. */
8985 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8988 strcpy (rs->buf, "vRun;");
8989 len = strlen (rs->buf);
8991 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8992 error (_("Remote file name too long for run packet"));
8993 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8994 strlen (remote_exec_file));
8996 gdb_assert (args != NULL);
8999 struct cleanup *back_to;
9003 argv = gdb_buildargv (args);
9004 back_to = make_cleanup_freeargv (argv);
9005 for (i = 0; argv[i] != NULL; i++)
9007 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9008 error (_("Argument list too long for run packet"));
9009 rs->buf[len++] = ';';
9010 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9013 do_cleanups (back_to);
9016 rs->buf[len++] = '\0';
9019 getpkt (&rs->buf, &rs->buf_size, 0);
9021 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9024 /* We have a wait response. All is well. */
9026 case PACKET_UNKNOWN:
9029 if (remote_exec_file[0] == '\0')
9030 error (_("Running the default executable on the remote target failed; "
9031 "try \"set remote exec-file\"?"));
9033 error (_("Running \"%s\" on the remote target failed"),
9036 gdb_assert_not_reached (_("bad switch"));
9040 /* In the extended protocol we want to be able to do things like
9041 "run" and have them basically work as expected. So we need
9042 a special create_inferior function. We support changing the
9043 executable file and the command line arguments, but not the
9047 extended_remote_create_inferior (struct target_ops *ops,
9048 char *exec_file, char *args,
9049 char **env, int from_tty)
9053 struct remote_state *rs = get_remote_state ();
9054 const char *remote_exec_file = get_remote_exec_file ();
9056 /* If running asynchronously, register the target file descriptor
9057 with the event loop. */
9058 if (target_can_async_p ())
9061 /* Disable address space randomization if requested (and supported). */
9062 if (extended_remote_supports_disable_randomization (ops))
9063 extended_remote_disable_randomization (disable_randomization);
9065 /* Now restart the remote server. */
9066 run_worked = extended_remote_run (args) != -1;
9069 /* vRun was not supported. Fail if we need it to do what the
9071 if (remote_exec_file[0])
9072 error (_("Remote target does not support \"set remote exec-file\""));
9074 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9076 /* Fall back to "R". */
9077 extended_remote_restart ();
9080 if (!have_inferiors ())
9082 /* Clean up from the last time we ran, before we mark the target
9083 running again. This will mark breakpoints uninserted, and
9084 get_offsets may insert breakpoints. */
9085 init_thread_list ();
9086 init_wait_for_inferior ();
9089 /* vRun's success return is a stop reply. */
9090 stop_reply = run_worked ? rs->buf : NULL;
9091 add_current_inferior_and_thread (stop_reply);
9093 /* Get updated offsets, if the stub uses qOffsets. */
9098 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9099 the list of conditions (in agent expression bytecode format), if any, the
9100 target needs to evaluate. The output is placed into the packet buffer
9101 started from BUF and ended at BUF_END. */
9104 remote_add_target_side_condition (struct gdbarch *gdbarch,
9105 struct bp_target_info *bp_tgt, char *buf,
9108 struct agent_expr *aexpr = NULL;
9111 char *buf_start = buf;
9113 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9116 buf += strlen (buf);
9117 xsnprintf (buf, buf_end - buf, "%s", ";");
9120 /* Send conditions to the target and free the vector. */
9122 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9125 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9126 buf += strlen (buf);
9127 for (i = 0; i < aexpr->len; ++i)
9128 buf = pack_hex_byte (buf, aexpr->buf[i]);
9135 remote_add_target_side_commands (struct gdbarch *gdbarch,
9136 struct bp_target_info *bp_tgt, char *buf)
9138 struct agent_expr *aexpr = NULL;
9141 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9144 buf += strlen (buf);
9146 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9147 buf += strlen (buf);
9149 /* Concatenate all the agent expressions that are commands into the
9152 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9155 sprintf (buf, "X%x,", aexpr->len);
9156 buf += strlen (buf);
9157 for (i = 0; i < aexpr->len; ++i)
9158 buf = pack_hex_byte (buf, aexpr->buf[i]);
9163 /* Insert a breakpoint. On targets that have software breakpoint
9164 support, we ask the remote target to do the work; on targets
9165 which don't, we insert a traditional memory breakpoint. */
9168 remote_insert_breakpoint (struct target_ops *ops,
9169 struct gdbarch *gdbarch,
9170 struct bp_target_info *bp_tgt)
9172 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9173 If it succeeds, then set the support to PACKET_ENABLE. If it
9174 fails, and the user has explicitly requested the Z support then
9175 report an error, otherwise, mark it disabled and go on. */
9177 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9179 CORE_ADDR addr = bp_tgt->reqstd_address;
9180 struct remote_state *rs;
9183 struct condition_list *cond = NULL;
9185 /* Make sure the remote is pointing at the right process, if
9187 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9188 set_general_process ();
9190 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9192 rs = get_remote_state ();
9194 endbuf = rs->buf + get_remote_packet_size ();
9199 addr = (ULONGEST) remote_address_masked (addr);
9200 p += hexnumstr (p, addr);
9201 xsnprintf (p, endbuf - p, ",%d", bpsize);
9203 if (remote_supports_cond_breakpoints (ops))
9204 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9206 if (remote_can_run_breakpoint_commands (ops))
9207 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9210 getpkt (&rs->buf, &rs->buf_size, 0);
9212 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9217 bp_tgt->placed_address = addr;
9218 bp_tgt->placed_size = bpsize;
9220 case PACKET_UNKNOWN:
9225 /* If this breakpoint has target-side commands but this stub doesn't
9226 support Z0 packets, throw error. */
9227 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9228 throw_error (NOT_SUPPORTED_ERROR, _("\
9229 Target doesn't support breakpoints that have target side commands."));
9231 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9235 remote_remove_breakpoint (struct target_ops *ops,
9236 struct gdbarch *gdbarch,
9237 struct bp_target_info *bp_tgt)
9239 CORE_ADDR addr = bp_tgt->placed_address;
9240 struct remote_state *rs = get_remote_state ();
9242 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9245 char *endbuf = rs->buf + get_remote_packet_size ();
9247 /* Make sure the remote is pointing at the right process, if
9249 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9250 set_general_process ();
9256 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9257 p += hexnumstr (p, addr);
9258 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9261 getpkt (&rs->buf, &rs->buf_size, 0);
9263 return (rs->buf[0] == 'E');
9266 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9269 static enum Z_packet_type
9270 watchpoint_to_Z_packet (int type)
9275 return Z_PACKET_WRITE_WP;
9278 return Z_PACKET_READ_WP;
9281 return Z_PACKET_ACCESS_WP;
9284 internal_error (__FILE__, __LINE__,
9285 _("hw_bp_to_z: bad watchpoint type %d"), type);
9290 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9291 enum target_hw_bp_type type, struct expression *cond)
9293 struct remote_state *rs = get_remote_state ();
9294 char *endbuf = rs->buf + get_remote_packet_size ();
9296 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9298 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9301 /* Make sure the remote is pointing at the right process, if
9303 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9304 set_general_process ();
9306 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9307 p = strchr (rs->buf, '\0');
9308 addr = remote_address_masked (addr);
9309 p += hexnumstr (p, (ULONGEST) addr);
9310 xsnprintf (p, endbuf - p, ",%x", len);
9313 getpkt (&rs->buf, &rs->buf_size, 0);
9315 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9319 case PACKET_UNKNOWN:
9324 internal_error (__FILE__, __LINE__,
9325 _("remote_insert_watchpoint: reached end of function"));
9329 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9330 CORE_ADDR start, int length)
9332 CORE_ADDR diff = remote_address_masked (addr - start);
9334 return diff < length;
9339 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9340 enum target_hw_bp_type type, struct expression *cond)
9342 struct remote_state *rs = get_remote_state ();
9343 char *endbuf = rs->buf + get_remote_packet_size ();
9345 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9347 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9350 /* Make sure the remote is pointing at the right process, if
9352 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9353 set_general_process ();
9355 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9356 p = strchr (rs->buf, '\0');
9357 addr = remote_address_masked (addr);
9358 p += hexnumstr (p, (ULONGEST) addr);
9359 xsnprintf (p, endbuf - p, ",%x", len);
9361 getpkt (&rs->buf, &rs->buf_size, 0);
9363 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9366 case PACKET_UNKNOWN:
9371 internal_error (__FILE__, __LINE__,
9372 _("remote_remove_watchpoint: reached end of function"));
9376 int remote_hw_watchpoint_limit = -1;
9377 int remote_hw_watchpoint_length_limit = -1;
9378 int remote_hw_breakpoint_limit = -1;
9381 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9382 CORE_ADDR addr, int len)
9384 if (remote_hw_watchpoint_length_limit == 0)
9386 else if (remote_hw_watchpoint_length_limit < 0)
9388 else if (len <= remote_hw_watchpoint_length_limit)
9395 remote_check_watch_resources (struct target_ops *self,
9396 enum bptype type, int cnt, int ot)
9398 if (type == bp_hardware_breakpoint)
9400 if (remote_hw_breakpoint_limit == 0)
9402 else if (remote_hw_breakpoint_limit < 0)
9404 else if (cnt <= remote_hw_breakpoint_limit)
9409 if (remote_hw_watchpoint_limit == 0)
9411 else if (remote_hw_watchpoint_limit < 0)
9415 else if (cnt <= remote_hw_watchpoint_limit)
9421 /* The to_stopped_by_sw_breakpoint method of target remote. */
9424 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9426 struct thread_info *thread = inferior_thread ();
9428 return (thread->priv != NULL
9429 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9432 /* The to_supports_stopped_by_sw_breakpoint method of target
9436 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9438 struct remote_state *rs = get_remote_state ();
9440 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9443 /* The to_stopped_by_hw_breakpoint method of target remote. */
9446 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9448 struct thread_info *thread = inferior_thread ();
9450 return (thread->priv != NULL
9451 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9454 /* The to_supports_stopped_by_hw_breakpoint method of target
9458 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9460 struct remote_state *rs = get_remote_state ();
9462 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9466 remote_stopped_by_watchpoint (struct target_ops *ops)
9468 struct thread_info *thread = inferior_thread ();
9470 return (thread->priv != NULL
9471 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9475 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9477 struct thread_info *thread = inferior_thread ();
9479 if (thread->priv != NULL
9480 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9482 *addr_p = thread->priv->watch_data_address;
9491 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9492 struct bp_target_info *bp_tgt)
9494 CORE_ADDR addr = bp_tgt->reqstd_address;
9495 struct remote_state *rs;
9500 /* The length field should be set to the size of a breakpoint
9501 instruction, even though we aren't inserting one ourselves. */
9503 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9505 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9508 /* Make sure the remote is pointing at the right process, if
9510 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9511 set_general_process ();
9513 rs = get_remote_state ();
9515 endbuf = rs->buf + get_remote_packet_size ();
9521 addr = remote_address_masked (addr);
9522 p += hexnumstr (p, (ULONGEST) addr);
9523 xsnprintf (p, endbuf - p, ",%x", bpsize);
9525 if (remote_supports_cond_breakpoints (self))
9526 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9528 if (remote_can_run_breakpoint_commands (self))
9529 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9532 getpkt (&rs->buf, &rs->buf_size, 0);
9534 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9537 if (rs->buf[1] == '.')
9539 message = strchr (rs->buf + 2, '.');
9541 error (_("Remote failure reply: %s"), message + 1);
9544 case PACKET_UNKNOWN:
9547 bp_tgt->placed_address = addr;
9548 bp_tgt->placed_size = bpsize;
9551 internal_error (__FILE__, __LINE__,
9552 _("remote_insert_hw_breakpoint: reached end of function"));
9557 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9558 struct bp_target_info *bp_tgt)
9561 struct remote_state *rs = get_remote_state ();
9563 char *endbuf = rs->buf + get_remote_packet_size ();
9565 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9568 /* Make sure the remote is pointing at the right process, if
9570 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9571 set_general_process ();
9577 addr = remote_address_masked (bp_tgt->placed_address);
9578 p += hexnumstr (p, (ULONGEST) addr);
9579 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9582 getpkt (&rs->buf, &rs->buf_size, 0);
9584 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9587 case PACKET_UNKNOWN:
9592 internal_error (__FILE__, __LINE__,
9593 _("remote_remove_hw_breakpoint: reached end of function"));
9596 /* Verify memory using the "qCRC:" request. */
9599 remote_verify_memory (struct target_ops *ops,
9600 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9602 struct remote_state *rs = get_remote_state ();
9603 unsigned long host_crc, target_crc;
9606 /* It doesn't make sense to use qCRC if the remote target is
9607 connected but not running. */
9608 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9610 enum packet_result result;
9612 /* Make sure the remote is pointing at the right process. */
9613 set_general_process ();
9615 /* FIXME: assumes lma can fit into long. */
9616 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9617 (long) lma, (long) size);
9620 /* Be clever; compute the host_crc before waiting for target
9622 host_crc = xcrc32 (data, size, 0xffffffff);
9624 getpkt (&rs->buf, &rs->buf_size, 0);
9626 result = packet_ok (rs->buf,
9627 &remote_protocol_packets[PACKET_qCRC]);
9628 if (result == PACKET_ERROR)
9630 else if (result == PACKET_OK)
9632 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9633 target_crc = target_crc * 16 + fromhex (*tmp);
9635 return (host_crc == target_crc);
9639 return simple_verify_memory (ops, data, lma, size);
9642 /* compare-sections command
9644 With no arguments, compares each loadable section in the exec bfd
9645 with the same memory range on the target, and reports mismatches.
9646 Useful for verifying the image on the target against the exec file. */
9649 compare_sections_command (char *args, int from_tty)
9652 struct cleanup *old_chain;
9654 const char *sectname;
9663 error (_("command cannot be used without an exec file"));
9665 /* Make sure the remote is pointing at the right process. */
9666 set_general_process ();
9668 if (args != NULL && strcmp (args, "-r") == 0)
9674 for (s = exec_bfd->sections; s; s = s->next)
9676 if (!(s->flags & SEC_LOAD))
9677 continue; /* Skip non-loadable section. */
9679 if (read_only && (s->flags & SEC_READONLY) == 0)
9680 continue; /* Skip writeable sections */
9682 size = bfd_get_section_size (s);
9684 continue; /* Skip zero-length section. */
9686 sectname = bfd_get_section_name (exec_bfd, s);
9687 if (args && strcmp (args, sectname) != 0)
9688 continue; /* Not the section selected by user. */
9690 matched = 1; /* Do this section. */
9693 sectdata = (gdb_byte *) xmalloc (size);
9694 old_chain = make_cleanup (xfree, sectdata);
9695 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9697 res = target_verify_memory (sectdata, lma, size);
9700 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9701 paddress (target_gdbarch (), lma),
9702 paddress (target_gdbarch (), lma + size));
9704 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9705 paddress (target_gdbarch (), lma),
9706 paddress (target_gdbarch (), lma + size));
9708 printf_filtered ("matched.\n");
9711 printf_filtered ("MIS-MATCHED!\n");
9715 do_cleanups (old_chain);
9718 warning (_("One or more sections of the target image does not match\n\
9719 the loaded file\n"));
9720 if (args && !matched)
9721 printf_filtered (_("No loaded section named '%s'.\n"), args);
9724 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9725 into remote target. The number of bytes written to the remote
9726 target is returned, or -1 for error. */
9728 static enum target_xfer_status
9729 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9730 const char *annex, const gdb_byte *writebuf,
9731 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9732 struct packet_config *packet)
9736 struct remote_state *rs = get_remote_state ();
9737 int max_size = get_memory_write_packet_size ();
9739 if (packet->support == PACKET_DISABLE)
9740 return TARGET_XFER_E_IO;
9742 /* Insert header. */
9743 i = snprintf (rs->buf, max_size,
9744 "qXfer:%s:write:%s:%s:",
9745 object_name, annex ? annex : "",
9746 phex_nz (offset, sizeof offset));
9747 max_size -= (i + 1);
9749 /* Escape as much data as fits into rs->buf. */
9750 buf_len = remote_escape_output
9751 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9753 if (putpkt_binary (rs->buf, i + buf_len) < 0
9754 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9755 || packet_ok (rs->buf, packet) != PACKET_OK)
9756 return TARGET_XFER_E_IO;
9758 unpack_varlen_hex (rs->buf, &n);
9761 return TARGET_XFER_OK;
9764 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9765 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9766 number of bytes read is returned, or 0 for EOF, or -1 for error.
9767 The number of bytes read may be less than LEN without indicating an
9768 EOF. PACKET is checked and updated to indicate whether the remote
9769 target supports this object. */
9771 static enum target_xfer_status
9772 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9774 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9775 ULONGEST *xfered_len,
9776 struct packet_config *packet)
9778 struct remote_state *rs = get_remote_state ();
9779 LONGEST i, n, packet_len;
9781 if (packet->support == PACKET_DISABLE)
9782 return TARGET_XFER_E_IO;
9784 /* Check whether we've cached an end-of-object packet that matches
9786 if (rs->finished_object)
9788 if (strcmp (object_name, rs->finished_object) == 0
9789 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9790 && offset == rs->finished_offset)
9791 return TARGET_XFER_EOF;
9794 /* Otherwise, we're now reading something different. Discard
9796 xfree (rs->finished_object);
9797 xfree (rs->finished_annex);
9798 rs->finished_object = NULL;
9799 rs->finished_annex = NULL;
9802 /* Request only enough to fit in a single packet. The actual data
9803 may not, since we don't know how much of it will need to be escaped;
9804 the target is free to respond with slightly less data. We subtract
9805 five to account for the response type and the protocol frame. */
9806 n = min (get_remote_packet_size () - 5, len);
9807 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9808 object_name, annex ? annex : "",
9809 phex_nz (offset, sizeof offset),
9810 phex_nz (n, sizeof n));
9811 i = putpkt (rs->buf);
9813 return TARGET_XFER_E_IO;
9816 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9817 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9818 return TARGET_XFER_E_IO;
9820 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9821 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9823 /* 'm' means there is (or at least might be) more data after this
9824 batch. That does not make sense unless there's at least one byte
9825 of data in this reply. */
9826 if (rs->buf[0] == 'm' && packet_len == 1)
9827 error (_("Remote qXfer reply contained no data."));
9829 /* Got some data. */
9830 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9831 packet_len - 1, readbuf, n);
9833 /* 'l' is an EOF marker, possibly including a final block of data,
9834 or possibly empty. If we have the final block of a non-empty
9835 object, record this fact to bypass a subsequent partial read. */
9836 if (rs->buf[0] == 'l' && offset + i > 0)
9838 rs->finished_object = xstrdup (object_name);
9839 rs->finished_annex = xstrdup (annex ? annex : "");
9840 rs->finished_offset = offset + i;
9844 return TARGET_XFER_EOF;
9848 return TARGET_XFER_OK;
9852 static enum target_xfer_status
9853 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9854 const char *annex, gdb_byte *readbuf,
9855 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9856 ULONGEST *xfered_len)
9858 struct remote_state *rs;
9862 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9864 set_remote_traceframe ();
9865 set_general_thread (inferior_ptid);
9867 rs = get_remote_state ();
9869 /* Handle memory using the standard memory routines. */
9870 if (object == TARGET_OBJECT_MEMORY)
9872 /* If the remote target is connected but not running, we should
9873 pass this request down to a lower stratum (e.g. the executable
9875 if (!target_has_execution)
9876 return TARGET_XFER_EOF;
9878 if (writebuf != NULL)
9879 return remote_write_bytes (offset, writebuf, len, unit_size,
9882 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9886 /* Handle SPU memory using qxfer packets. */
9887 if (object == TARGET_OBJECT_SPU)
9890 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9891 xfered_len, &remote_protocol_packets
9892 [PACKET_qXfer_spu_read]);
9894 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9895 xfered_len, &remote_protocol_packets
9896 [PACKET_qXfer_spu_write]);
9899 /* Handle extra signal info using qxfer packets. */
9900 if (object == TARGET_OBJECT_SIGNAL_INFO)
9903 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9904 xfered_len, &remote_protocol_packets
9905 [PACKET_qXfer_siginfo_read]);
9907 return remote_write_qxfer (ops, "siginfo", annex,
9908 writebuf, offset, len, xfered_len,
9909 &remote_protocol_packets
9910 [PACKET_qXfer_siginfo_write]);
9913 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9916 return remote_read_qxfer (ops, "statictrace", annex,
9917 readbuf, offset, len, xfered_len,
9918 &remote_protocol_packets
9919 [PACKET_qXfer_statictrace_read]);
9921 return TARGET_XFER_E_IO;
9924 /* Only handle flash writes. */
9925 if (writebuf != NULL)
9931 case TARGET_OBJECT_FLASH:
9932 return remote_flash_write (ops, offset, len, xfered_len,
9936 return TARGET_XFER_E_IO;
9940 /* Map pre-existing objects onto letters. DO NOT do this for new
9941 objects!!! Instead specify new query packets. */
9944 case TARGET_OBJECT_AVR:
9948 case TARGET_OBJECT_AUXV:
9949 gdb_assert (annex == NULL);
9950 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9952 &remote_protocol_packets[PACKET_qXfer_auxv]);
9954 case TARGET_OBJECT_AVAILABLE_FEATURES:
9955 return remote_read_qxfer
9956 (ops, "features", annex, readbuf, offset, len, xfered_len,
9957 &remote_protocol_packets[PACKET_qXfer_features]);
9959 case TARGET_OBJECT_LIBRARIES:
9960 return remote_read_qxfer
9961 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9962 &remote_protocol_packets[PACKET_qXfer_libraries]);
9964 case TARGET_OBJECT_LIBRARIES_SVR4:
9965 return remote_read_qxfer
9966 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9967 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9969 case TARGET_OBJECT_MEMORY_MAP:
9970 gdb_assert (annex == NULL);
9971 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9973 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9975 case TARGET_OBJECT_OSDATA:
9976 /* Should only get here if we're connected. */
9977 gdb_assert (rs->remote_desc);
9978 return remote_read_qxfer
9979 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9980 &remote_protocol_packets[PACKET_qXfer_osdata]);
9982 case TARGET_OBJECT_THREADS:
9983 gdb_assert (annex == NULL);
9984 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9986 &remote_protocol_packets[PACKET_qXfer_threads]);
9988 case TARGET_OBJECT_TRACEFRAME_INFO:
9989 gdb_assert (annex == NULL);
9990 return remote_read_qxfer
9991 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9992 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9994 case TARGET_OBJECT_FDPIC:
9995 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9997 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9999 case TARGET_OBJECT_OPENVMS_UIB:
10000 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10002 &remote_protocol_packets[PACKET_qXfer_uib]);
10004 case TARGET_OBJECT_BTRACE:
10005 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10007 &remote_protocol_packets[PACKET_qXfer_btrace]);
10009 case TARGET_OBJECT_BTRACE_CONF:
10010 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10012 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10014 case TARGET_OBJECT_EXEC_FILE:
10015 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10017 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10020 return TARGET_XFER_E_IO;
10023 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10024 large enough let the caller deal with it. */
10025 if (len < get_remote_packet_size ())
10026 return TARGET_XFER_E_IO;
10027 len = get_remote_packet_size ();
10029 /* Except for querying the minimum buffer size, target must be open. */
10030 if (!rs->remote_desc)
10031 error (_("remote query is only available after target open"));
10033 gdb_assert (annex != NULL);
10034 gdb_assert (readbuf != NULL);
10038 *p2++ = query_type;
10040 /* We used one buffer char for the remote protocol q command and
10041 another for the query type. As the remote protocol encapsulation
10042 uses 4 chars plus one extra in case we are debugging
10043 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10046 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10048 /* Bad caller may have sent forbidden characters. */
10049 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10054 gdb_assert (annex[i] == '\0');
10056 i = putpkt (rs->buf);
10058 return TARGET_XFER_E_IO;
10060 getpkt (&rs->buf, &rs->buf_size, 0);
10061 strcpy ((char *) readbuf, rs->buf);
10063 *xfered_len = strlen ((char *) readbuf);
10064 return TARGET_XFER_OK;
10068 remote_search_memory (struct target_ops* ops,
10069 CORE_ADDR start_addr, ULONGEST search_space_len,
10070 const gdb_byte *pattern, ULONGEST pattern_len,
10071 CORE_ADDR *found_addrp)
10073 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10074 struct remote_state *rs = get_remote_state ();
10075 int max_size = get_memory_write_packet_size ();
10076 struct packet_config *packet =
10077 &remote_protocol_packets[PACKET_qSearch_memory];
10078 /* Number of packet bytes used to encode the pattern;
10079 this could be more than PATTERN_LEN due to escape characters. */
10080 int escaped_pattern_len;
10081 /* Amount of pattern that was encodable in the packet. */
10082 int used_pattern_len;
10085 ULONGEST found_addr;
10087 /* Don't go to the target if we don't have to.
10088 This is done before checking packet->support to avoid the possibility that
10089 a success for this edge case means the facility works in general. */
10090 if (pattern_len > search_space_len)
10092 if (pattern_len == 0)
10094 *found_addrp = start_addr;
10098 /* If we already know the packet isn't supported, fall back to the simple
10099 way of searching memory. */
10101 if (packet_config_support (packet) == PACKET_DISABLE)
10103 /* Target doesn't provided special support, fall back and use the
10104 standard support (copy memory and do the search here). */
10105 return simple_search_memory (ops, start_addr, search_space_len,
10106 pattern, pattern_len, found_addrp);
10109 /* Make sure the remote is pointing at the right process. */
10110 set_general_process ();
10112 /* Insert header. */
10113 i = snprintf (rs->buf, max_size,
10114 "qSearch:memory:%s;%s;",
10115 phex_nz (start_addr, addr_size),
10116 phex_nz (search_space_len, sizeof (search_space_len)));
10117 max_size -= (i + 1);
10119 /* Escape as much data as fits into rs->buf. */
10120 escaped_pattern_len =
10121 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10122 &used_pattern_len, max_size);
10124 /* Bail if the pattern is too large. */
10125 if (used_pattern_len != pattern_len)
10126 error (_("Pattern is too large to transmit to remote target."));
10128 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10129 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10130 || packet_ok (rs->buf, packet) != PACKET_OK)
10132 /* The request may not have worked because the command is not
10133 supported. If so, fall back to the simple way. */
10134 if (packet->support == PACKET_DISABLE)
10136 return simple_search_memory (ops, start_addr, search_space_len,
10137 pattern, pattern_len, found_addrp);
10142 if (rs->buf[0] == '0')
10144 else if (rs->buf[0] == '1')
10147 if (rs->buf[1] != ',')
10148 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10149 unpack_varlen_hex (rs->buf + 2, &found_addr);
10150 *found_addrp = found_addr;
10153 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10159 remote_rcmd (struct target_ops *self, const char *command,
10160 struct ui_file *outbuf)
10162 struct remote_state *rs = get_remote_state ();
10165 if (!rs->remote_desc)
10166 error (_("remote rcmd is only available after target open"));
10168 /* Send a NULL command across as an empty command. */
10169 if (command == NULL)
10172 /* The query prefix. */
10173 strcpy (rs->buf, "qRcmd,");
10174 p = strchr (rs->buf, '\0');
10176 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10177 > get_remote_packet_size ())
10178 error (_("\"monitor\" command ``%s'' is too long."), command);
10180 /* Encode the actual command. */
10181 bin2hex ((const gdb_byte *) command, p, strlen (command));
10183 if (putpkt (rs->buf) < 0)
10184 error (_("Communication problem with target."));
10186 /* get/display the response */
10191 /* XXX - see also remote_get_noisy_reply(). */
10192 QUIT; /* Allow user to bail out with ^C. */
10194 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10196 /* Timeout. Continue to (try to) read responses.
10197 This is better than stopping with an error, assuming the stub
10198 is still executing the (long) monitor command.
10199 If needed, the user can interrupt gdb using C-c, obtaining
10200 an effect similar to stop on timeout. */
10204 if (buf[0] == '\0')
10205 error (_("Target does not support this command."));
10206 if (buf[0] == 'O' && buf[1] != 'K')
10208 remote_console_output (buf + 1); /* 'O' message from stub. */
10211 if (strcmp (buf, "OK") == 0)
10213 if (strlen (buf) == 3 && buf[0] == 'E'
10214 && isdigit (buf[1]) && isdigit (buf[2]))
10216 error (_("Protocol error with Rcmd"));
10218 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10220 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10222 fputc_unfiltered (c, outbuf);
10228 static VEC(mem_region_s) *
10229 remote_memory_map (struct target_ops *ops)
10231 VEC(mem_region_s) *result = NULL;
10232 char *text = target_read_stralloc (¤t_target,
10233 TARGET_OBJECT_MEMORY_MAP, NULL);
10237 struct cleanup *back_to = make_cleanup (xfree, text);
10239 result = parse_memory_map (text);
10240 do_cleanups (back_to);
10247 packet_command (char *args, int from_tty)
10249 struct remote_state *rs = get_remote_state ();
10251 if (!rs->remote_desc)
10252 error (_("command can only be used with remote target"));
10255 error (_("remote-packet command requires packet text as argument"));
10257 puts_filtered ("sending: ");
10258 print_packet (args);
10259 puts_filtered ("\n");
10262 getpkt (&rs->buf, &rs->buf_size, 0);
10263 puts_filtered ("received: ");
10264 print_packet (rs->buf);
10265 puts_filtered ("\n");
10269 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10271 static void display_thread_info (struct gdb_ext_thread_info *info);
10273 static void threadset_test_cmd (char *cmd, int tty);
10275 static void threadalive_test (char *cmd, int tty);
10277 static void threadlist_test_cmd (char *cmd, int tty);
10279 int get_and_display_threadinfo (threadref *ref);
10281 static void threadinfo_test_cmd (char *cmd, int tty);
10283 static int thread_display_step (threadref *ref, void *context);
10285 static void threadlist_update_test_cmd (char *cmd, int tty);
10287 static void init_remote_threadtests (void);
10289 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10292 threadset_test_cmd (char *cmd, int tty)
10294 int sample_thread = SAMPLE_THREAD;
10296 printf_filtered (_("Remote threadset test\n"));
10297 set_general_thread (sample_thread);
10302 threadalive_test (char *cmd, int tty)
10304 int sample_thread = SAMPLE_THREAD;
10305 int pid = ptid_get_pid (inferior_ptid);
10306 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10308 if (remote_thread_alive (ptid))
10309 printf_filtered ("PASS: Thread alive test\n");
10311 printf_filtered ("FAIL: Thread alive test\n");
10314 void output_threadid (char *title, threadref *ref);
10317 output_threadid (char *title, threadref *ref)
10321 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10323 printf_filtered ("%s %s\n", title, (&hexid[0]));
10327 threadlist_test_cmd (char *cmd, int tty)
10330 threadref nextthread;
10331 int done, result_count;
10332 threadref threadlist[3];
10334 printf_filtered ("Remote Threadlist test\n");
10335 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10336 &result_count, &threadlist[0]))
10337 printf_filtered ("FAIL: threadlist test\n");
10340 threadref *scan = threadlist;
10341 threadref *limit = scan + result_count;
10343 while (scan < limit)
10344 output_threadid (" thread ", scan++);
10349 display_thread_info (struct gdb_ext_thread_info *info)
10351 output_threadid ("Threadid: ", &info->threadid);
10352 printf_filtered ("Name: %s\n ", info->shortname);
10353 printf_filtered ("State: %s\n", info->display);
10354 printf_filtered ("other: %s\n\n", info->more_display);
10358 get_and_display_threadinfo (threadref *ref)
10362 struct gdb_ext_thread_info threadinfo;
10364 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10365 | TAG_MOREDISPLAY | TAG_DISPLAY;
10366 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10367 display_thread_info (&threadinfo);
10372 threadinfo_test_cmd (char *cmd, int tty)
10374 int athread = SAMPLE_THREAD;
10378 int_to_threadref (&thread, athread);
10379 printf_filtered ("Remote Threadinfo test\n");
10380 if (!get_and_display_threadinfo (&thread))
10381 printf_filtered ("FAIL cannot get thread info\n");
10385 thread_display_step (threadref *ref, void *context)
10387 /* output_threadid(" threadstep ",ref); *//* simple test */
10388 return get_and_display_threadinfo (ref);
10392 threadlist_update_test_cmd (char *cmd, int tty)
10394 printf_filtered ("Remote Threadlist update test\n");
10395 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10399 init_remote_threadtests (void)
10401 add_com ("tlist", class_obscure, threadlist_test_cmd,
10402 _("Fetch and print the remote list of "
10403 "thread identifiers, one pkt only"));
10404 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10405 _("Fetch and display info about one thread"));
10406 add_com ("tset", class_obscure, threadset_test_cmd,
10407 _("Test setting to a different thread"));
10408 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10409 _("Iterate through updating all remote thread info"));
10410 add_com ("talive", class_obscure, threadalive_test,
10411 _(" Remote thread alive test "));
10416 /* Convert a thread ID to a string. Returns the string in a static
10420 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10422 static char buf[64];
10423 struct remote_state *rs = get_remote_state ();
10425 if (ptid_equal (ptid, null_ptid))
10426 return normal_pid_to_str (ptid);
10427 else if (ptid_is_pid (ptid))
10429 /* Printing an inferior target id. */
10431 /* When multi-process extensions are off, there's no way in the
10432 remote protocol to know the remote process id, if there's any
10433 at all. There's one exception --- when we're connected with
10434 target extended-remote, and we manually attached to a process
10435 with "attach PID". We don't record anywhere a flag that
10436 allows us to distinguish that case from the case of
10437 connecting with extended-remote and the stub already being
10438 attached to a process, and reporting yes to qAttached, hence
10439 no smart special casing here. */
10440 if (!remote_multi_process_p (rs))
10442 xsnprintf (buf, sizeof buf, "Remote target");
10446 return normal_pid_to_str (ptid);
10450 if (ptid_equal (magic_null_ptid, ptid))
10451 xsnprintf (buf, sizeof buf, "Thread <main>");
10452 else if (rs->extended && remote_multi_process_p (rs))
10453 if (ptid_get_lwp (ptid) == 0)
10454 return normal_pid_to_str (ptid);
10456 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10457 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10459 xsnprintf (buf, sizeof buf, "Thread %ld",
10460 ptid_get_lwp (ptid));
10465 /* Get the address of the thread local variable in OBJFILE which is
10466 stored at OFFSET within the thread local storage for thread PTID. */
10469 remote_get_thread_local_address (struct target_ops *ops,
10470 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10472 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10474 struct remote_state *rs = get_remote_state ();
10476 char *endp = rs->buf + get_remote_packet_size ();
10477 enum packet_result result;
10479 strcpy (p, "qGetTLSAddr:");
10481 p = write_ptid (p, endp, ptid);
10483 p += hexnumstr (p, offset);
10485 p += hexnumstr (p, lm);
10489 getpkt (&rs->buf, &rs->buf_size, 0);
10490 result = packet_ok (rs->buf,
10491 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10492 if (result == PACKET_OK)
10496 unpack_varlen_hex (rs->buf, &result);
10499 else if (result == PACKET_UNKNOWN)
10500 throw_error (TLS_GENERIC_ERROR,
10501 _("Remote target doesn't support qGetTLSAddr packet"));
10503 throw_error (TLS_GENERIC_ERROR,
10504 _("Remote target failed to process qGetTLSAddr request"));
10507 throw_error (TLS_GENERIC_ERROR,
10508 _("TLS not supported or disabled on this target"));
10513 /* Provide thread local base, i.e. Thread Information Block address.
10514 Returns 1 if ptid is found and thread_local_base is non zero. */
10517 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10519 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10521 struct remote_state *rs = get_remote_state ();
10523 char *endp = rs->buf + get_remote_packet_size ();
10524 enum packet_result result;
10526 strcpy (p, "qGetTIBAddr:");
10528 p = write_ptid (p, endp, ptid);
10532 getpkt (&rs->buf, &rs->buf_size, 0);
10533 result = packet_ok (rs->buf,
10534 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10535 if (result == PACKET_OK)
10539 unpack_varlen_hex (rs->buf, &result);
10541 *addr = (CORE_ADDR) result;
10544 else if (result == PACKET_UNKNOWN)
10545 error (_("Remote target doesn't support qGetTIBAddr packet"));
10547 error (_("Remote target failed to process qGetTIBAddr request"));
10550 error (_("qGetTIBAddr not supported or disabled on this target"));
10555 /* Support for inferring a target description based on the current
10556 architecture and the size of a 'g' packet. While the 'g' packet
10557 can have any size (since optional registers can be left off the
10558 end), some sizes are easily recognizable given knowledge of the
10559 approximate architecture. */
10561 struct remote_g_packet_guess
10564 const struct target_desc *tdesc;
10566 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10567 DEF_VEC_O(remote_g_packet_guess_s);
10569 struct remote_g_packet_data
10571 VEC(remote_g_packet_guess_s) *guesses;
10574 static struct gdbarch_data *remote_g_packet_data_handle;
10577 remote_g_packet_data_init (struct obstack *obstack)
10579 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10583 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10584 const struct target_desc *tdesc)
10586 struct remote_g_packet_data *data
10587 = ((struct remote_g_packet_data *)
10588 gdbarch_data (gdbarch, remote_g_packet_data_handle));
10589 struct remote_g_packet_guess new_guess, *guess;
10592 gdb_assert (tdesc != NULL);
10595 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10597 if (guess->bytes == bytes)
10598 internal_error (__FILE__, __LINE__,
10599 _("Duplicate g packet description added for size %d"),
10602 new_guess.bytes = bytes;
10603 new_guess.tdesc = tdesc;
10604 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10607 /* Return 1 if remote_read_description would do anything on this target
10608 and architecture, 0 otherwise. */
10611 remote_read_description_p (struct target_ops *target)
10613 struct remote_g_packet_data *data
10614 = ((struct remote_g_packet_data *)
10615 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10617 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10623 static const struct target_desc *
10624 remote_read_description (struct target_ops *target)
10626 struct remote_g_packet_data *data
10627 = ((struct remote_g_packet_data *)
10628 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10630 /* Do not try this during initial connection, when we do not know
10631 whether there is a running but stopped thread. */
10632 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10633 return target->beneath->to_read_description (target->beneath);
10635 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10637 struct remote_g_packet_guess *guess;
10639 int bytes = send_g_packet ();
10642 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10644 if (guess->bytes == bytes)
10645 return guess->tdesc;
10647 /* We discard the g packet. A minor optimization would be to
10648 hold on to it, and fill the register cache once we have selected
10649 an architecture, but it's too tricky to do safely. */
10652 return target->beneath->to_read_description (target->beneath);
10655 /* Remote file transfer support. This is host-initiated I/O, not
10656 target-initiated; for target-initiated, see remote-fileio.c. */
10658 /* If *LEFT is at least the length of STRING, copy STRING to
10659 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10660 decrease *LEFT. Otherwise raise an error. */
10663 remote_buffer_add_string (char **buffer, int *left, char *string)
10665 int len = strlen (string);
10668 error (_("Packet too long for target."));
10670 memcpy (*buffer, string, len);
10674 /* NUL-terminate the buffer as a convenience, if there is
10680 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10681 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10682 decrease *LEFT. Otherwise raise an error. */
10685 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10688 if (2 * len > *left)
10689 error (_("Packet too long for target."));
10691 bin2hex (bytes, *buffer, len);
10692 *buffer += 2 * len;
10695 /* NUL-terminate the buffer as a convenience, if there is
10701 /* If *LEFT is large enough, convert VALUE to hex and add it to
10702 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10703 decrease *LEFT. Otherwise raise an error. */
10706 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10708 int len = hexnumlen (value);
10711 error (_("Packet too long for target."));
10713 hexnumstr (*buffer, value);
10717 /* NUL-terminate the buffer as a convenience, if there is
10723 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10724 value, *REMOTE_ERRNO to the remote error number or zero if none
10725 was included, and *ATTACHMENT to point to the start of the annex
10726 if any. The length of the packet isn't needed here; there may
10727 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10729 Return 0 if the packet could be parsed, -1 if it could not. If
10730 -1 is returned, the other variables may not be initialized. */
10733 remote_hostio_parse_result (char *buffer, int *retcode,
10734 int *remote_errno, char **attachment)
10739 *attachment = NULL;
10741 if (buffer[0] != 'F')
10745 *retcode = strtol (&buffer[1], &p, 16);
10746 if (errno != 0 || p == &buffer[1])
10749 /* Check for ",errno". */
10753 *remote_errno = strtol (p + 1, &p2, 16);
10754 if (errno != 0 || p + 1 == p2)
10759 /* Check for ";attachment". If there is no attachment, the
10760 packet should end here. */
10763 *attachment = p + 1;
10766 else if (*p == '\0')
10772 /* Send a prepared I/O packet to the target and read its response.
10773 The prepared packet is in the global RS->BUF before this function
10774 is called, and the answer is there when we return.
10776 COMMAND_BYTES is the length of the request to send, which may include
10777 binary data. WHICH_PACKET is the packet configuration to check
10778 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10779 is set to the error number and -1 is returned. Otherwise the value
10780 returned by the function is returned.
10782 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10783 attachment is expected; an error will be reported if there's a
10784 mismatch. If one is found, *ATTACHMENT will be set to point into
10785 the packet buffer and *ATTACHMENT_LEN will be set to the
10786 attachment's length. */
10789 remote_hostio_send_command (int command_bytes, int which_packet,
10790 int *remote_errno, char **attachment,
10791 int *attachment_len)
10793 struct remote_state *rs = get_remote_state ();
10794 int ret, bytes_read;
10795 char *attachment_tmp;
10797 if (!rs->remote_desc
10798 || packet_support (which_packet) == PACKET_DISABLE)
10800 *remote_errno = FILEIO_ENOSYS;
10804 putpkt_binary (rs->buf, command_bytes);
10805 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10807 /* If it timed out, something is wrong. Don't try to parse the
10809 if (bytes_read < 0)
10811 *remote_errno = FILEIO_EINVAL;
10815 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10818 *remote_errno = FILEIO_EINVAL;
10820 case PACKET_UNKNOWN:
10821 *remote_errno = FILEIO_ENOSYS;
10827 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10830 *remote_errno = FILEIO_EINVAL;
10834 /* Make sure we saw an attachment if and only if we expected one. */
10835 if ((attachment_tmp == NULL && attachment != NULL)
10836 || (attachment_tmp != NULL && attachment == NULL))
10838 *remote_errno = FILEIO_EINVAL;
10842 /* If an attachment was found, it must point into the packet buffer;
10843 work out how many bytes there were. */
10844 if (attachment_tmp != NULL)
10846 *attachment = attachment_tmp;
10847 *attachment_len = bytes_read - (*attachment - rs->buf);
10853 /* Invalidate the readahead cache. */
10856 readahead_cache_invalidate (void)
10858 struct remote_state *rs = get_remote_state ();
10860 rs->readahead_cache.fd = -1;
10863 /* Invalidate the readahead cache if it is holding data for FD. */
10866 readahead_cache_invalidate_fd (int fd)
10868 struct remote_state *rs = get_remote_state ();
10870 if (rs->readahead_cache.fd == fd)
10871 rs->readahead_cache.fd = -1;
10874 /* Set the filesystem remote_hostio functions that take FILENAME
10875 arguments will use. Return 0 on success, or -1 if an error
10876 occurs (and set *REMOTE_ERRNO). */
10879 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10881 struct remote_state *rs = get_remote_state ();
10882 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10884 int left = get_remote_packet_size () - 1;
10888 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10891 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10894 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10896 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10897 remote_buffer_add_string (&p, &left, arg);
10899 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10900 remote_errno, NULL, NULL);
10902 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10906 rs->fs_pid = required_pid;
10911 /* Implementation of to_fileio_open. */
10914 remote_hostio_open (struct target_ops *self,
10915 struct inferior *inf, const char *filename,
10916 int flags, int mode, int warn_if_slow,
10919 struct remote_state *rs = get_remote_state ();
10921 int left = get_remote_packet_size () - 1;
10925 static int warning_issued = 0;
10927 printf_unfiltered (_("Reading %s from remote target...\n"),
10930 if (!warning_issued)
10932 warning (_("File transfers from remote targets can be slow."
10933 " Use \"set sysroot\" to access files locally"
10935 warning_issued = 1;
10939 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10942 remote_buffer_add_string (&p, &left, "vFile:open:");
10944 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10945 strlen (filename));
10946 remote_buffer_add_string (&p, &left, ",");
10948 remote_buffer_add_int (&p, &left, flags);
10949 remote_buffer_add_string (&p, &left, ",");
10951 remote_buffer_add_int (&p, &left, mode);
10953 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10954 remote_errno, NULL, NULL);
10957 /* Implementation of to_fileio_pwrite. */
10960 remote_hostio_pwrite (struct target_ops *self,
10961 int fd, const gdb_byte *write_buf, int len,
10962 ULONGEST offset, int *remote_errno)
10964 struct remote_state *rs = get_remote_state ();
10966 int left = get_remote_packet_size ();
10969 readahead_cache_invalidate_fd (fd);
10971 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10973 remote_buffer_add_int (&p, &left, fd);
10974 remote_buffer_add_string (&p, &left, ",");
10976 remote_buffer_add_int (&p, &left, offset);
10977 remote_buffer_add_string (&p, &left, ",");
10979 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10980 get_remote_packet_size () - (p - rs->buf));
10982 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10983 remote_errno, NULL, NULL);
10986 /* Helper for the implementation of to_fileio_pread. Read the file
10987 from the remote side with vFile:pread. */
10990 remote_hostio_pread_vFile (struct target_ops *self,
10991 int fd, gdb_byte *read_buf, int len,
10992 ULONGEST offset, int *remote_errno)
10994 struct remote_state *rs = get_remote_state ();
10997 int left = get_remote_packet_size ();
10998 int ret, attachment_len;
11001 remote_buffer_add_string (&p, &left, "vFile:pread:");
11003 remote_buffer_add_int (&p, &left, fd);
11004 remote_buffer_add_string (&p, &left, ",");
11006 remote_buffer_add_int (&p, &left, len);
11007 remote_buffer_add_string (&p, &left, ",");
11009 remote_buffer_add_int (&p, &left, offset);
11011 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11012 remote_errno, &attachment,
11018 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11020 if (read_len != ret)
11021 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11026 /* Serve pread from the readahead cache. Returns number of bytes
11027 read, or 0 if the request can't be served from the cache. */
11030 remote_hostio_pread_from_cache (struct remote_state *rs,
11031 int fd, gdb_byte *read_buf, size_t len,
11034 struct readahead_cache *cache = &rs->readahead_cache;
11036 if (cache->fd == fd
11037 && cache->offset <= offset
11038 && offset < cache->offset + cache->bufsize)
11040 ULONGEST max = cache->offset + cache->bufsize;
11042 if (offset + len > max)
11043 len = max - offset;
11045 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11052 /* Implementation of to_fileio_pread. */
11055 remote_hostio_pread (struct target_ops *self,
11056 int fd, gdb_byte *read_buf, int len,
11057 ULONGEST offset, int *remote_errno)
11060 struct remote_state *rs = get_remote_state ();
11061 struct readahead_cache *cache = &rs->readahead_cache;
11063 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11066 cache->hit_count++;
11069 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11070 pulongest (cache->hit_count));
11074 cache->miss_count++;
11076 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11077 pulongest (cache->miss_count));
11080 cache->offset = offset;
11081 cache->bufsize = get_remote_packet_size ();
11082 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11084 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11085 cache->offset, remote_errno);
11088 readahead_cache_invalidate_fd (fd);
11092 cache->bufsize = ret;
11093 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11096 /* Implementation of to_fileio_close. */
11099 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11101 struct remote_state *rs = get_remote_state ();
11103 int left = get_remote_packet_size () - 1;
11105 readahead_cache_invalidate_fd (fd);
11107 remote_buffer_add_string (&p, &left, "vFile:close:");
11109 remote_buffer_add_int (&p, &left, fd);
11111 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11112 remote_errno, NULL, NULL);
11115 /* Implementation of to_fileio_unlink. */
11118 remote_hostio_unlink (struct target_ops *self,
11119 struct inferior *inf, const char *filename,
11122 struct remote_state *rs = get_remote_state ();
11124 int left = get_remote_packet_size () - 1;
11126 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11129 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11131 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11132 strlen (filename));
11134 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11135 remote_errno, NULL, NULL);
11138 /* Implementation of to_fileio_readlink. */
11141 remote_hostio_readlink (struct target_ops *self,
11142 struct inferior *inf, const char *filename,
11145 struct remote_state *rs = get_remote_state ();
11148 int left = get_remote_packet_size ();
11149 int len, attachment_len;
11153 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11156 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11158 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11159 strlen (filename));
11161 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11162 remote_errno, &attachment,
11168 ret = (char *) xmalloc (len + 1);
11170 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11171 (gdb_byte *) ret, len);
11172 if (read_len != len)
11173 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11179 /* Implementation of to_fileio_fstat. */
11182 remote_hostio_fstat (struct target_ops *self,
11183 int fd, struct stat *st,
11186 struct remote_state *rs = get_remote_state ();
11188 int left = get_remote_packet_size ();
11189 int attachment_len, ret;
11191 struct fio_stat fst;
11194 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11196 remote_buffer_add_int (&p, &left, fd);
11198 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11199 remote_errno, &attachment,
11203 if (*remote_errno != FILEIO_ENOSYS)
11206 /* Strictly we should return -1, ENOSYS here, but when
11207 "set sysroot remote:" was implemented in August 2008
11208 BFD's need for a stat function was sidestepped with
11209 this hack. This was not remedied until March 2015
11210 so we retain the previous behavior to avoid breaking
11213 Note that the memset is a March 2015 addition; older
11214 GDBs set st_size *and nothing else* so the structure
11215 would have garbage in all other fields. This might
11216 break something but retaining the previous behavior
11217 here would be just too wrong. */
11219 memset (st, 0, sizeof (struct stat));
11220 st->st_size = INT_MAX;
11224 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11225 (gdb_byte *) &fst, sizeof (fst));
11227 if (read_len != ret)
11228 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11230 if (read_len != sizeof (fst))
11231 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11232 read_len, (int) sizeof (fst));
11234 remote_fileio_to_host_stat (&fst, st);
11239 /* Implementation of to_filesystem_is_local. */
11242 remote_filesystem_is_local (struct target_ops *self)
11244 /* Valgrind GDB presents itself as a remote target but works
11245 on the local filesystem: it does not implement remote get
11246 and users are not expected to set a sysroot. To handle
11247 this case we treat the remote filesystem as local if the
11248 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11249 does not support vFile:open. */
11250 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11252 enum packet_support ps = packet_support (PACKET_vFile_open);
11254 if (ps == PACKET_SUPPORT_UNKNOWN)
11256 int fd, remote_errno;
11258 /* Try opening a file to probe support. The supplied
11259 filename is irrelevant, we only care about whether
11260 the stub recognizes the packet or not. */
11261 fd = remote_hostio_open (self, NULL, "just probing",
11262 FILEIO_O_RDONLY, 0700, 0,
11266 remote_hostio_close (self, fd, &remote_errno);
11268 ps = packet_support (PACKET_vFile_open);
11271 if (ps == PACKET_DISABLE)
11273 static int warning_issued = 0;
11275 if (!warning_issued)
11277 warning (_("remote target does not support file"
11278 " transfer, attempting to access files"
11279 " from local filesystem."));
11280 warning_issued = 1;
11291 remote_fileio_errno_to_host (int errnum)
11297 case FILEIO_ENOENT:
11305 case FILEIO_EACCES:
11307 case FILEIO_EFAULT:
11311 case FILEIO_EEXIST:
11313 case FILEIO_ENODEV:
11315 case FILEIO_ENOTDIR:
11317 case FILEIO_EISDIR:
11319 case FILEIO_EINVAL:
11321 case FILEIO_ENFILE:
11323 case FILEIO_EMFILE:
11327 case FILEIO_ENOSPC:
11329 case FILEIO_ESPIPE:
11333 case FILEIO_ENOSYS:
11335 case FILEIO_ENAMETOOLONG:
11336 return ENAMETOOLONG;
11342 remote_hostio_error (int errnum)
11344 int host_error = remote_fileio_errno_to_host (errnum);
11346 if (host_error == -1)
11347 error (_("Unknown remote I/O error %d"), errnum);
11349 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11353 remote_hostio_close_cleanup (void *opaque)
11355 int fd = *(int *) opaque;
11358 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11362 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11364 struct cleanup *back_to, *close_cleanup;
11365 int retcode, fd, remote_errno, bytes, io_size;
11368 int bytes_in_buffer;
11371 struct remote_state *rs = get_remote_state ();
11373 if (!rs->remote_desc)
11374 error (_("command can only be used with remote target"));
11376 file = gdb_fopen_cloexec (local_file, "rb");
11378 perror_with_name (local_file);
11379 back_to = make_cleanup_fclose (file);
11381 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11382 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11384 0700, 0, &remote_errno);
11386 remote_hostio_error (remote_errno);
11388 /* Send up to this many bytes at once. They won't all fit in the
11389 remote packet limit, so we'll transfer slightly fewer. */
11390 io_size = get_remote_packet_size ();
11391 buffer = (gdb_byte *) xmalloc (io_size);
11392 make_cleanup (xfree, buffer);
11394 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11396 bytes_in_buffer = 0;
11399 while (bytes_in_buffer || !saw_eof)
11403 bytes = fread (buffer + bytes_in_buffer, 1,
11404 io_size - bytes_in_buffer,
11409 error (_("Error reading %s."), local_file);
11412 /* EOF. Unless there is something still in the
11413 buffer from the last iteration, we are done. */
11415 if (bytes_in_buffer == 0)
11423 bytes += bytes_in_buffer;
11424 bytes_in_buffer = 0;
11426 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11428 offset, &remote_errno);
11431 remote_hostio_error (remote_errno);
11432 else if (retcode == 0)
11433 error (_("Remote write of %d bytes returned 0!"), bytes);
11434 else if (retcode < bytes)
11436 /* Short write. Save the rest of the read data for the next
11438 bytes_in_buffer = bytes - retcode;
11439 memmove (buffer, buffer + retcode, bytes_in_buffer);
11445 discard_cleanups (close_cleanup);
11446 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11447 remote_hostio_error (remote_errno);
11450 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11451 do_cleanups (back_to);
11455 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11457 struct cleanup *back_to, *close_cleanup;
11458 int fd, remote_errno, bytes, io_size;
11462 struct remote_state *rs = get_remote_state ();
11464 if (!rs->remote_desc)
11465 error (_("command can only be used with remote target"));
11467 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11468 remote_file, FILEIO_O_RDONLY, 0, 0,
11471 remote_hostio_error (remote_errno);
11473 file = gdb_fopen_cloexec (local_file, "wb");
11475 perror_with_name (local_file);
11476 back_to = make_cleanup_fclose (file);
11478 /* Send up to this many bytes at once. They won't all fit in the
11479 remote packet limit, so we'll transfer slightly fewer. */
11480 io_size = get_remote_packet_size ();
11481 buffer = (gdb_byte *) xmalloc (io_size);
11482 make_cleanup (xfree, buffer);
11484 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11489 bytes = remote_hostio_pread (find_target_at (process_stratum),
11490 fd, buffer, io_size, offset, &remote_errno);
11492 /* Success, but no bytes, means end-of-file. */
11495 remote_hostio_error (remote_errno);
11499 bytes = fwrite (buffer, 1, bytes, file);
11501 perror_with_name (local_file);
11504 discard_cleanups (close_cleanup);
11505 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11506 remote_hostio_error (remote_errno);
11509 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11510 do_cleanups (back_to);
11514 remote_file_delete (const char *remote_file, int from_tty)
11516 int retcode, remote_errno;
11517 struct remote_state *rs = get_remote_state ();
11519 if (!rs->remote_desc)
11520 error (_("command can only be used with remote target"));
11522 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11523 NULL, remote_file, &remote_errno);
11525 remote_hostio_error (remote_errno);
11528 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11532 remote_put_command (char *args, int from_tty)
11534 struct cleanup *back_to;
11538 error_no_arg (_("file to put"));
11540 argv = gdb_buildargv (args);
11541 back_to = make_cleanup_freeargv (argv);
11542 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11543 error (_("Invalid parameters to remote put"));
11545 remote_file_put (argv[0], argv[1], from_tty);
11547 do_cleanups (back_to);
11551 remote_get_command (char *args, int from_tty)
11553 struct cleanup *back_to;
11557 error_no_arg (_("file to get"));
11559 argv = gdb_buildargv (args);
11560 back_to = make_cleanup_freeargv (argv);
11561 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11562 error (_("Invalid parameters to remote get"));
11564 remote_file_get (argv[0], argv[1], from_tty);
11566 do_cleanups (back_to);
11570 remote_delete_command (char *args, int from_tty)
11572 struct cleanup *back_to;
11576 error_no_arg (_("file to delete"));
11578 argv = gdb_buildargv (args);
11579 back_to = make_cleanup_freeargv (argv);
11580 if (argv[0] == NULL || argv[1] != NULL)
11581 error (_("Invalid parameters to remote delete"));
11583 remote_file_delete (argv[0], from_tty);
11585 do_cleanups (back_to);
11589 remote_command (char *args, int from_tty)
11591 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11595 remote_can_execute_reverse (struct target_ops *self)
11597 if (packet_support (PACKET_bs) == PACKET_ENABLE
11598 || packet_support (PACKET_bc) == PACKET_ENABLE)
11605 remote_supports_non_stop (struct target_ops *self)
11611 remote_supports_disable_randomization (struct target_ops *self)
11613 /* Only supported in extended mode. */
11618 remote_supports_multi_process (struct target_ops *self)
11620 struct remote_state *rs = get_remote_state ();
11622 /* Only extended-remote handles being attached to multiple
11623 processes, even though plain remote can use the multi-process
11624 thread id extensions, so that GDB knows the target process's
11626 return rs->extended && remote_multi_process_p (rs);
11630 remote_supports_cond_tracepoints (void)
11632 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11636 remote_supports_cond_breakpoints (struct target_ops *self)
11638 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11642 remote_supports_fast_tracepoints (void)
11644 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11648 remote_supports_static_tracepoints (void)
11650 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11654 remote_supports_install_in_trace (void)
11656 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11660 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11662 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11667 remote_supports_string_tracing (struct target_ops *self)
11669 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11673 remote_can_run_breakpoint_commands (struct target_ops *self)
11675 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11679 remote_trace_init (struct target_ops *self)
11682 remote_get_noisy_reply (&target_buf, &target_buf_size);
11683 if (strcmp (target_buf, "OK") != 0)
11684 error (_("Target does not support this command."));
11687 static void free_actions_list (char **actions_list);
11688 static void free_actions_list_cleanup_wrapper (void *);
11690 free_actions_list_cleanup_wrapper (void *al)
11692 free_actions_list ((char **) al);
11696 free_actions_list (char **actions_list)
11700 if (actions_list == 0)
11703 for (ndx = 0; actions_list[ndx]; ndx++)
11704 xfree (actions_list[ndx]);
11706 xfree (actions_list);
11709 /* Recursive routine to walk through command list including loops, and
11710 download packets for each command. */
11713 remote_download_command_source (int num, ULONGEST addr,
11714 struct command_line *cmds)
11716 struct remote_state *rs = get_remote_state ();
11717 struct command_line *cmd;
11719 for (cmd = cmds; cmd; cmd = cmd->next)
11721 QUIT; /* Allow user to bail out with ^C. */
11722 strcpy (rs->buf, "QTDPsrc:");
11723 encode_source_string (num, addr, "cmd", cmd->line,
11724 rs->buf + strlen (rs->buf),
11725 rs->buf_size - strlen (rs->buf));
11727 remote_get_noisy_reply (&target_buf, &target_buf_size);
11728 if (strcmp (target_buf, "OK"))
11729 warning (_("Target does not support source download."));
11731 if (cmd->control_type == while_control
11732 || cmd->control_type == while_stepping_control)
11734 remote_download_command_source (num, addr, *cmd->body_list);
11736 QUIT; /* Allow user to bail out with ^C. */
11737 strcpy (rs->buf, "QTDPsrc:");
11738 encode_source_string (num, addr, "cmd", "end",
11739 rs->buf + strlen (rs->buf),
11740 rs->buf_size - strlen (rs->buf));
11742 remote_get_noisy_reply (&target_buf, &target_buf_size);
11743 if (strcmp (target_buf, "OK"))
11744 warning (_("Target does not support source download."));
11750 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11752 #define BUF_SIZE 2048
11756 char buf[BUF_SIZE];
11757 char **tdp_actions;
11758 char **stepping_actions;
11760 struct cleanup *old_chain = NULL;
11761 struct agent_expr *aexpr;
11762 struct cleanup *aexpr_chain = NULL;
11764 struct breakpoint *b = loc->owner;
11765 struct tracepoint *t = (struct tracepoint *) b;
11767 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11768 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11770 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11773 tpaddr = loc->address;
11774 sprintf_vma (addrbuf, tpaddr);
11775 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11776 addrbuf, /* address */
11777 (b->enable_state == bp_enabled ? 'E' : 'D'),
11778 t->step_count, t->pass_count);
11779 /* Fast tracepoints are mostly handled by the target, but we can
11780 tell the target how big of an instruction block should be moved
11782 if (b->type == bp_fast_tracepoint)
11784 /* Only test for support at download time; we may not know
11785 target capabilities at definition time. */
11786 if (remote_supports_fast_tracepoints ())
11788 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11790 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11791 gdb_insn_length (loc->gdbarch, tpaddr));
11793 /* If it passed validation at definition but fails now,
11794 something is very wrong. */
11795 internal_error (__FILE__, __LINE__,
11796 _("Fast tracepoint not "
11797 "valid during download"));
11800 /* Fast tracepoints are functionally identical to regular
11801 tracepoints, so don't take lack of support as a reason to
11802 give up on the trace run. */
11803 warning (_("Target does not support fast tracepoints, "
11804 "downloading %d as regular tracepoint"), b->number);
11806 else if (b->type == bp_static_tracepoint)
11808 /* Only test for support at download time; we may not know
11809 target capabilities at definition time. */
11810 if (remote_supports_static_tracepoints ())
11812 struct static_tracepoint_marker marker;
11814 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11815 strcat (buf, ":S");
11817 error (_("Static tracepoint not valid during download"));
11820 /* Fast tracepoints are functionally identical to regular
11821 tracepoints, so don't take lack of support as a reason
11822 to give up on the trace run. */
11823 error (_("Target does not support static tracepoints"));
11825 /* If the tracepoint has a conditional, make it into an agent
11826 expression and append to the definition. */
11829 /* Only test support at download time, we may not know target
11830 capabilities at definition time. */
11831 if (remote_supports_cond_tracepoints ())
11833 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11834 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11835 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11837 pkt = buf + strlen (buf);
11838 for (ndx = 0; ndx < aexpr->len; ++ndx)
11839 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11841 do_cleanups (aexpr_chain);
11844 warning (_("Target does not support conditional tracepoints, "
11845 "ignoring tp %d cond"), b->number);
11848 if (b->commands || *default_collect)
11851 remote_get_noisy_reply (&target_buf, &target_buf_size);
11852 if (strcmp (target_buf, "OK"))
11853 error (_("Target does not support tracepoints."));
11855 /* do_single_steps (t); */
11858 for (ndx = 0; tdp_actions[ndx]; ndx++)
11860 QUIT; /* Allow user to bail out with ^C. */
11861 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11862 b->number, addrbuf, /* address */
11864 ((tdp_actions[ndx + 1] || stepping_actions)
11867 remote_get_noisy_reply (&target_buf,
11869 if (strcmp (target_buf, "OK"))
11870 error (_("Error on target while setting tracepoints."));
11873 if (stepping_actions)
11875 for (ndx = 0; stepping_actions[ndx]; ndx++)
11877 QUIT; /* Allow user to bail out with ^C. */
11878 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11879 b->number, addrbuf, /* address */
11880 ((ndx == 0) ? "S" : ""),
11881 stepping_actions[ndx],
11882 (stepping_actions[ndx + 1] ? "-" : ""));
11884 remote_get_noisy_reply (&target_buf,
11886 if (strcmp (target_buf, "OK"))
11887 error (_("Error on target while setting tracepoints."));
11891 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11893 if (b->location != NULL)
11895 strcpy (buf, "QTDPsrc:");
11896 encode_source_string (b->number, loc->address, "at",
11897 event_location_to_string (b->location),
11898 buf + strlen (buf), 2048 - strlen (buf));
11900 remote_get_noisy_reply (&target_buf, &target_buf_size);
11901 if (strcmp (target_buf, "OK"))
11902 warning (_("Target does not support source download."));
11904 if (b->cond_string)
11906 strcpy (buf, "QTDPsrc:");
11907 encode_source_string (b->number, loc->address,
11908 "cond", b->cond_string, buf + strlen (buf),
11909 2048 - strlen (buf));
11911 remote_get_noisy_reply (&target_buf, &target_buf_size);
11912 if (strcmp (target_buf, "OK"))
11913 warning (_("Target does not support source download."));
11915 remote_download_command_source (b->number, loc->address,
11916 breakpoint_commands (b));
11919 do_cleanups (old_chain);
11923 remote_can_download_tracepoint (struct target_ops *self)
11925 struct remote_state *rs = get_remote_state ();
11926 struct trace_status *ts;
11929 /* Don't try to install tracepoints until we've relocated our
11930 symbols, and fetched and merged the target's tracepoint list with
11932 if (rs->starting_up)
11935 ts = current_trace_status ();
11936 status = remote_get_trace_status (self, ts);
11938 if (status == -1 || !ts->running_known || !ts->running)
11941 /* If we are in a tracing experiment, but remote stub doesn't support
11942 installing tracepoint in trace, we have to return. */
11943 if (!remote_supports_install_in_trace ())
11951 remote_download_trace_state_variable (struct target_ops *self,
11952 struct trace_state_variable *tsv)
11954 struct remote_state *rs = get_remote_state ();
11957 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11958 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11960 p = rs->buf + strlen (rs->buf);
11961 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11962 error (_("Trace state variable name too long for tsv definition packet"));
11963 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11966 remote_get_noisy_reply (&target_buf, &target_buf_size);
11967 if (*target_buf == '\0')
11968 error (_("Target does not support this command."));
11969 if (strcmp (target_buf, "OK") != 0)
11970 error (_("Error on target while downloading trace state variable."));
11974 remote_enable_tracepoint (struct target_ops *self,
11975 struct bp_location *location)
11977 struct remote_state *rs = get_remote_state ();
11980 sprintf_vma (addr_buf, location->address);
11981 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11982 location->owner->number, addr_buf);
11984 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11985 if (*rs->buf == '\0')
11986 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11987 if (strcmp (rs->buf, "OK") != 0)
11988 error (_("Error on target while enabling tracepoint."));
11992 remote_disable_tracepoint (struct target_ops *self,
11993 struct bp_location *location)
11995 struct remote_state *rs = get_remote_state ();
11998 sprintf_vma (addr_buf, location->address);
11999 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12000 location->owner->number, addr_buf);
12002 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12003 if (*rs->buf == '\0')
12004 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12005 if (strcmp (rs->buf, "OK") != 0)
12006 error (_("Error on target while disabling tracepoint."));
12010 remote_trace_set_readonly_regions (struct target_ops *self)
12014 bfd_size_type size;
12020 return; /* No information to give. */
12022 strcpy (target_buf, "QTro");
12023 offset = strlen (target_buf);
12024 for (s = exec_bfd->sections; s; s = s->next)
12026 char tmp1[40], tmp2[40];
12029 if ((s->flags & SEC_LOAD) == 0 ||
12030 /* (s->flags & SEC_CODE) == 0 || */
12031 (s->flags & SEC_READONLY) == 0)
12035 vma = bfd_get_section_vma (abfd, s);
12036 size = bfd_get_section_size (s);
12037 sprintf_vma (tmp1, vma);
12038 sprintf_vma (tmp2, vma + size);
12039 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12040 if (offset + sec_length + 1 > target_buf_size)
12042 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12044 Too many sections for read-only sections definition packet."));
12047 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12049 offset += sec_length;
12053 putpkt (target_buf);
12054 getpkt (&target_buf, &target_buf_size, 0);
12059 remote_trace_start (struct target_ops *self)
12061 putpkt ("QTStart");
12062 remote_get_noisy_reply (&target_buf, &target_buf_size);
12063 if (*target_buf == '\0')
12064 error (_("Target does not support this command."));
12065 if (strcmp (target_buf, "OK") != 0)
12066 error (_("Bogus reply from target: %s"), target_buf);
12070 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12072 /* Initialize it just to avoid a GCC false warning. */
12074 /* FIXME we need to get register block size some other way. */
12075 extern int trace_regblock_size;
12076 enum packet_result result;
12078 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12081 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12083 putpkt ("qTStatus");
12087 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12089 CATCH (ex, RETURN_MASK_ERROR)
12091 if (ex.error != TARGET_CLOSE_ERROR)
12093 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12096 throw_exception (ex);
12100 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12102 /* If the remote target doesn't do tracing, flag it. */
12103 if (result == PACKET_UNKNOWN)
12106 /* We're working with a live target. */
12107 ts->filename = NULL;
12110 error (_("Bogus trace status reply from target: %s"), target_buf);
12112 /* Function 'parse_trace_status' sets default value of each field of
12113 'ts' at first, so we don't have to do it here. */
12114 parse_trace_status (p, ts);
12116 return ts->running;
12120 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12121 struct uploaded_tp *utp)
12123 struct remote_state *rs = get_remote_state ();
12125 struct bp_location *loc;
12126 struct tracepoint *tp = (struct tracepoint *) bp;
12127 size_t size = get_remote_packet_size ();
12131 tp->base.hit_count = 0;
12132 tp->traceframe_usage = 0;
12133 for (loc = tp->base.loc; loc; loc = loc->next)
12135 /* If the tracepoint was never downloaded, don't go asking for
12137 if (tp->number_on_target == 0)
12139 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12140 phex_nz (loc->address, 0));
12142 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12143 if (reply && *reply)
12146 parse_tracepoint_status (reply + 1, bp, utp);
12152 utp->hit_count = 0;
12153 utp->traceframe_usage = 0;
12154 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12155 phex_nz (utp->addr, 0));
12157 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12158 if (reply && *reply)
12161 parse_tracepoint_status (reply + 1, bp, utp);
12167 remote_trace_stop (struct target_ops *self)
12170 remote_get_noisy_reply (&target_buf, &target_buf_size);
12171 if (*target_buf == '\0')
12172 error (_("Target does not support this command."));
12173 if (strcmp (target_buf, "OK") != 0)
12174 error (_("Bogus reply from target: %s"), target_buf);
12178 remote_trace_find (struct target_ops *self,
12179 enum trace_find_type type, int num,
12180 CORE_ADDR addr1, CORE_ADDR addr2,
12183 struct remote_state *rs = get_remote_state ();
12184 char *endbuf = rs->buf + get_remote_packet_size ();
12186 int target_frameno = -1, target_tracept = -1;
12188 /* Lookups other than by absolute frame number depend on the current
12189 trace selected, so make sure it is correct on the remote end
12191 if (type != tfind_number)
12192 set_remote_traceframe ();
12195 strcpy (p, "QTFrame:");
12196 p = strchr (p, '\0');
12200 xsnprintf (p, endbuf - p, "%x", num);
12203 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12206 xsnprintf (p, endbuf - p, "tdp:%x", num);
12209 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12210 phex_nz (addr2, 0));
12212 case tfind_outside:
12213 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12214 phex_nz (addr2, 0));
12217 error (_("Unknown trace find type %d"), type);
12221 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12222 if (*reply == '\0')
12223 error (_("Target does not support this command."));
12225 while (reply && *reply)
12230 target_frameno = (int) strtol (p, &reply, 16);
12232 error (_("Unable to parse trace frame number"));
12233 /* Don't update our remote traceframe number cache on failure
12234 to select a remote traceframe. */
12235 if (target_frameno == -1)
12240 target_tracept = (int) strtol (p, &reply, 16);
12242 error (_("Unable to parse tracepoint number"));
12244 case 'O': /* "OK"? */
12245 if (reply[1] == 'K' && reply[2] == '\0')
12248 error (_("Bogus reply from target: %s"), reply);
12251 error (_("Bogus reply from target: %s"), reply);
12254 *tpp = target_tracept;
12256 rs->remote_traceframe_number = target_frameno;
12257 return target_frameno;
12261 remote_get_trace_state_variable_value (struct target_ops *self,
12262 int tsvnum, LONGEST *val)
12264 struct remote_state *rs = get_remote_state ();
12268 set_remote_traceframe ();
12270 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12272 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12273 if (reply && *reply)
12277 unpack_varlen_hex (reply + 1, &uval);
12278 *val = (LONGEST) uval;
12286 remote_save_trace_data (struct target_ops *self, const char *filename)
12288 struct remote_state *rs = get_remote_state ();
12292 strcpy (p, "QTSave:");
12294 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12295 error (_("Remote file name too long for trace save packet"));
12296 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12299 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12300 if (*reply == '\0')
12301 error (_("Target does not support this command."));
12302 if (strcmp (reply, "OK") != 0)
12303 error (_("Bogus reply from target: %s"), reply);
12307 /* This is basically a memory transfer, but needs to be its own packet
12308 because we don't know how the target actually organizes its trace
12309 memory, plus we want to be able to ask for as much as possible, but
12310 not be unhappy if we don't get as much as we ask for. */
12313 remote_get_raw_trace_data (struct target_ops *self,
12314 gdb_byte *buf, ULONGEST offset, LONGEST len)
12316 struct remote_state *rs = get_remote_state ();
12322 strcpy (p, "qTBuffer:");
12324 p += hexnumstr (p, offset);
12326 p += hexnumstr (p, len);
12330 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12331 if (reply && *reply)
12333 /* 'l' by itself means we're at the end of the buffer and
12334 there is nothing more to get. */
12338 /* Convert the reply into binary. Limit the number of bytes to
12339 convert according to our passed-in buffer size, rather than
12340 what was returned in the packet; if the target is
12341 unexpectedly generous and gives us a bigger reply than we
12342 asked for, we don't want to crash. */
12343 rslt = hex2bin (target_buf, buf, len);
12347 /* Something went wrong, flag as an error. */
12352 remote_set_disconnected_tracing (struct target_ops *self, int val)
12354 struct remote_state *rs = get_remote_state ();
12356 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12360 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12362 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12363 if (*reply == '\0')
12364 error (_("Target does not support this command."));
12365 if (strcmp (reply, "OK") != 0)
12366 error (_("Bogus reply from target: %s"), reply);
12369 warning (_("Target does not support disconnected tracing."));
12373 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12375 struct thread_info *info = find_thread_ptid (ptid);
12377 if (info && info->priv)
12378 return info->priv->core;
12383 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12385 struct remote_state *rs = get_remote_state ();
12388 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12390 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12391 if (*reply == '\0')
12392 error (_("Target does not support this command."));
12393 if (strcmp (reply, "OK") != 0)
12394 error (_("Bogus reply from target: %s"), reply);
12397 static struct traceframe_info *
12398 remote_traceframe_info (struct target_ops *self)
12402 text = target_read_stralloc (¤t_target,
12403 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12406 struct traceframe_info *info;
12407 struct cleanup *back_to = make_cleanup (xfree, text);
12409 info = parse_traceframe_info (text);
12410 do_cleanups (back_to);
12417 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12418 instruction on which a fast tracepoint may be placed. Returns -1
12419 if the packet is not supported, and 0 if the minimum instruction
12420 length is unknown. */
12423 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12425 struct remote_state *rs = get_remote_state ();
12428 /* If we're not debugging a process yet, the IPA can't be
12430 if (!target_has_execution)
12433 /* Make sure the remote is pointing at the right process. */
12434 set_general_process ();
12436 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12438 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12439 if (*reply == '\0')
12443 ULONGEST min_insn_len;
12445 unpack_varlen_hex (reply, &min_insn_len);
12447 return (int) min_insn_len;
12452 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12454 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12456 struct remote_state *rs = get_remote_state ();
12457 char *buf = rs->buf;
12458 char *endbuf = rs->buf + get_remote_packet_size ();
12459 enum packet_result result;
12461 gdb_assert (val >= 0 || val == -1);
12462 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12463 /* Send -1 as literal "-1" to avoid host size dependency. */
12467 buf += hexnumstr (buf, (ULONGEST) -val);
12470 buf += hexnumstr (buf, (ULONGEST) val);
12473 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12474 result = packet_ok (rs->buf,
12475 &remote_protocol_packets[PACKET_QTBuffer_size]);
12477 if (result != PACKET_OK)
12478 warning (_("Bogus reply from target: %s"), rs->buf);
12483 remote_set_trace_notes (struct target_ops *self,
12484 const char *user, const char *notes,
12485 const char *stop_notes)
12487 struct remote_state *rs = get_remote_state ();
12489 char *buf = rs->buf;
12490 char *endbuf = rs->buf + get_remote_packet_size ();
12493 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12496 buf += xsnprintf (buf, endbuf - buf, "user:");
12497 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12503 buf += xsnprintf (buf, endbuf - buf, "notes:");
12504 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12510 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12511 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12515 /* Ensure the buffer is terminated. */
12519 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12520 if (*reply == '\0')
12523 if (strcmp (reply, "OK") != 0)
12524 error (_("Bogus reply from target: %s"), reply);
12530 remote_use_agent (struct target_ops *self, int use)
12532 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12534 struct remote_state *rs = get_remote_state ();
12536 /* If the stub supports QAgent. */
12537 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12539 getpkt (&rs->buf, &rs->buf_size, 0);
12541 if (strcmp (rs->buf, "OK") == 0)
12552 remote_can_use_agent (struct target_ops *self)
12554 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12557 struct btrace_target_info
12559 /* The ptid of the traced thread. */
12562 /* The obtained branch trace configuration. */
12563 struct btrace_config conf;
12566 /* Reset our idea of our target's btrace configuration. */
12569 remote_btrace_reset (void)
12571 struct remote_state *rs = get_remote_state ();
12573 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12576 /* Check whether the target supports branch tracing. */
12579 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12581 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12583 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12588 case BTRACE_FORMAT_NONE:
12591 case BTRACE_FORMAT_BTS:
12592 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12594 case BTRACE_FORMAT_PT:
12595 /* The trace is decoded on the host. Even if our target supports it,
12596 we still need to have libipt to decode the trace. */
12597 #if defined (HAVE_LIBIPT)
12598 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12599 #else /* !defined (HAVE_LIBIPT) */
12601 #endif /* !defined (HAVE_LIBIPT) */
12604 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12607 /* Synchronize the configuration with the target. */
12610 btrace_sync_conf (const struct btrace_config *conf)
12612 struct packet_config *packet;
12613 struct remote_state *rs;
12614 char *buf, *pos, *endbuf;
12616 rs = get_remote_state ();
12618 endbuf = buf + get_remote_packet_size ();
12620 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12621 if (packet_config_support (packet) == PACKET_ENABLE
12622 && conf->bts.size != rs->btrace_config.bts.size)
12625 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12629 getpkt (&buf, &rs->buf_size, 0);
12631 if (packet_ok (buf, packet) == PACKET_ERROR)
12633 if (buf[0] == 'E' && buf[1] == '.')
12634 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12636 error (_("Failed to configure the BTS buffer size."));
12639 rs->btrace_config.bts.size = conf->bts.size;
12642 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12643 if (packet_config_support (packet) == PACKET_ENABLE
12644 && conf->pt.size != rs->btrace_config.pt.size)
12647 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12651 getpkt (&buf, &rs->buf_size, 0);
12653 if (packet_ok (buf, packet) == PACKET_ERROR)
12655 if (buf[0] == 'E' && buf[1] == '.')
12656 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12658 error (_("Failed to configure the trace buffer size."));
12661 rs->btrace_config.pt.size = conf->pt.size;
12665 /* Read the current thread's btrace configuration from the target and
12666 store it into CONF. */
12669 btrace_read_config (struct btrace_config *conf)
12673 xml = target_read_stralloc (¤t_target,
12674 TARGET_OBJECT_BTRACE_CONF, "");
12677 struct cleanup *cleanup;
12679 cleanup = make_cleanup (xfree, xml);
12680 parse_xml_btrace_conf (conf, xml);
12681 do_cleanups (cleanup);
12685 /* Enable branch tracing. */
12687 static struct btrace_target_info *
12688 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12689 const struct btrace_config *conf)
12691 struct btrace_target_info *tinfo = NULL;
12692 struct packet_config *packet = NULL;
12693 struct remote_state *rs = get_remote_state ();
12694 char *buf = rs->buf;
12695 char *endbuf = rs->buf + get_remote_packet_size ();
12697 switch (conf->format)
12699 case BTRACE_FORMAT_BTS:
12700 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12703 case BTRACE_FORMAT_PT:
12704 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12708 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12709 error (_("Target does not support branch tracing."));
12711 btrace_sync_conf (conf);
12713 set_general_thread (ptid);
12715 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12717 getpkt (&rs->buf, &rs->buf_size, 0);
12719 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12721 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12722 error (_("Could not enable branch tracing for %s: %s"),
12723 target_pid_to_str (ptid), rs->buf + 2);
12725 error (_("Could not enable branch tracing for %s."),
12726 target_pid_to_str (ptid));
12729 tinfo = XCNEW (struct btrace_target_info);
12730 tinfo->ptid = ptid;
12732 /* If we fail to read the configuration, we lose some information, but the
12733 tracing itself is not impacted. */
12736 btrace_read_config (&tinfo->conf);
12738 CATCH (err, RETURN_MASK_ERROR)
12740 if (err.message != NULL)
12741 warning ("%s", err.message);
12748 /* Disable branch tracing. */
12751 remote_disable_btrace (struct target_ops *self,
12752 struct btrace_target_info *tinfo)
12754 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12755 struct remote_state *rs = get_remote_state ();
12756 char *buf = rs->buf;
12757 char *endbuf = rs->buf + get_remote_packet_size ();
12759 if (packet_config_support (packet) != PACKET_ENABLE)
12760 error (_("Target does not support branch tracing."));
12762 set_general_thread (tinfo->ptid);
12764 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12766 getpkt (&rs->buf, &rs->buf_size, 0);
12768 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12770 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12771 error (_("Could not disable branch tracing for %s: %s"),
12772 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12774 error (_("Could not disable branch tracing for %s."),
12775 target_pid_to_str (tinfo->ptid));
12781 /* Teardown branch tracing. */
12784 remote_teardown_btrace (struct target_ops *self,
12785 struct btrace_target_info *tinfo)
12787 /* We must not talk to the target during teardown. */
12791 /* Read the branch trace. */
12793 static enum btrace_error
12794 remote_read_btrace (struct target_ops *self,
12795 struct btrace_data *btrace,
12796 struct btrace_target_info *tinfo,
12797 enum btrace_read_type type)
12799 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12800 struct remote_state *rs = get_remote_state ();
12801 struct cleanup *cleanup;
12805 if (packet_config_support (packet) != PACKET_ENABLE)
12806 error (_("Target does not support branch tracing."));
12808 #if !defined(HAVE_LIBEXPAT)
12809 error (_("Cannot process branch tracing result. XML parsing not supported."));
12814 case BTRACE_READ_ALL:
12817 case BTRACE_READ_NEW:
12820 case BTRACE_READ_DELTA:
12824 internal_error (__FILE__, __LINE__,
12825 _("Bad branch tracing read type: %u."),
12826 (unsigned int) type);
12829 xml = target_read_stralloc (¤t_target,
12830 TARGET_OBJECT_BTRACE, annex);
12832 return BTRACE_ERR_UNKNOWN;
12834 cleanup = make_cleanup (xfree, xml);
12835 parse_xml_btrace (btrace, xml);
12836 do_cleanups (cleanup);
12838 return BTRACE_ERR_NONE;
12841 static const struct btrace_config *
12842 remote_btrace_conf (struct target_ops *self,
12843 const struct btrace_target_info *tinfo)
12845 return &tinfo->conf;
12849 remote_augmented_libraries_svr4_read (struct target_ops *self)
12851 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12855 /* Implementation of to_load. */
12858 remote_load (struct target_ops *self, const char *name, int from_tty)
12860 generic_load (name, from_tty);
12863 /* Accepts an integer PID; returns a string representing a file that
12864 can be opened on the remote side to get the symbols for the child
12865 process. Returns NULL if the operation is not supported. */
12868 remote_pid_to_exec_file (struct target_ops *self, int pid)
12870 static char *filename = NULL;
12871 struct inferior *inf;
12872 char *annex = NULL;
12874 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12877 if (filename != NULL)
12880 inf = find_inferior_pid (pid);
12882 internal_error (__FILE__, __LINE__,
12883 _("not currently attached to process %d"), pid);
12885 if (!inf->fake_pid_p)
12887 const int annex_size = 9;
12889 annex = (char *) alloca (annex_size);
12890 xsnprintf (annex, annex_size, "%x", pid);
12893 filename = target_read_stralloc (¤t_target,
12894 TARGET_OBJECT_EXEC_FILE, annex);
12899 /* Implement the to_can_do_single_step target_ops method. */
12902 remote_can_do_single_step (struct target_ops *ops)
12904 /* We can only tell whether target supports single step or not by
12905 supported s and S vCont actions if the stub supports vContSupported
12906 feature. If the stub doesn't support vContSupported feature,
12907 we have conservatively to think target doesn't supports single
12909 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12911 struct remote_state *rs = get_remote_state ();
12913 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12914 remote_vcont_probe (rs);
12916 return rs->supports_vCont.s && rs->supports_vCont.S;
12923 init_remote_ops (void)
12925 remote_ops.to_shortname = "remote";
12926 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12927 remote_ops.to_doc =
12928 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12929 Specify the serial device it is connected to\n\
12930 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12931 remote_ops.to_open = remote_open;
12932 remote_ops.to_close = remote_close;
12933 remote_ops.to_detach = remote_detach;
12934 remote_ops.to_disconnect = remote_disconnect;
12935 remote_ops.to_resume = remote_resume;
12936 remote_ops.to_wait = remote_wait;
12937 remote_ops.to_fetch_registers = remote_fetch_registers;
12938 remote_ops.to_store_registers = remote_store_registers;
12939 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12940 remote_ops.to_files_info = remote_files_info;
12941 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12942 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12943 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12944 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12945 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12946 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12947 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12948 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12949 remote_ops.to_watchpoint_addr_within_range =
12950 remote_watchpoint_addr_within_range;
12951 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12952 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12953 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12954 remote_ops.to_region_ok_for_hw_watchpoint
12955 = remote_region_ok_for_hw_watchpoint;
12956 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12957 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12958 remote_ops.to_kill = remote_kill;
12959 remote_ops.to_load = remote_load;
12960 remote_ops.to_mourn_inferior = remote_mourn;
12961 remote_ops.to_pass_signals = remote_pass_signals;
12962 remote_ops.to_program_signals = remote_program_signals;
12963 remote_ops.to_thread_alive = remote_thread_alive;
12964 remote_ops.to_thread_name = remote_thread_name;
12965 remote_ops.to_update_thread_list = remote_update_thread_list;
12966 remote_ops.to_pid_to_str = remote_pid_to_str;
12967 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12968 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12969 remote_ops.to_stop = remote_stop;
12970 remote_ops.to_interrupt = remote_interrupt;
12971 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12972 remote_ops.to_xfer_partial = remote_xfer_partial;
12973 remote_ops.to_rcmd = remote_rcmd;
12974 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12975 remote_ops.to_log_command = serial_log_command;
12976 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12977 remote_ops.to_stratum = process_stratum;
12978 remote_ops.to_has_all_memory = default_child_has_all_memory;
12979 remote_ops.to_has_memory = default_child_has_memory;
12980 remote_ops.to_has_stack = default_child_has_stack;
12981 remote_ops.to_has_registers = default_child_has_registers;
12982 remote_ops.to_has_execution = default_child_has_execution;
12983 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12984 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12985 remote_ops.to_magic = OPS_MAGIC;
12986 remote_ops.to_memory_map = remote_memory_map;
12987 remote_ops.to_flash_erase = remote_flash_erase;
12988 remote_ops.to_flash_done = remote_flash_done;
12989 remote_ops.to_read_description = remote_read_description;
12990 remote_ops.to_search_memory = remote_search_memory;
12991 remote_ops.to_can_async_p = remote_can_async_p;
12992 remote_ops.to_is_async_p = remote_is_async_p;
12993 remote_ops.to_async = remote_async;
12994 remote_ops.to_thread_events = remote_thread_events;
12995 remote_ops.to_can_do_single_step = remote_can_do_single_step;
12996 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12997 remote_ops.to_terminal_ours = remote_terminal_ours;
12998 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12999 remote_ops.to_supports_multi_process = remote_supports_multi_process;
13000 remote_ops.to_supports_disable_randomization
13001 = remote_supports_disable_randomization;
13002 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13003 remote_ops.to_fileio_open = remote_hostio_open;
13004 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13005 remote_ops.to_fileio_pread = remote_hostio_pread;
13006 remote_ops.to_fileio_fstat = remote_hostio_fstat;
13007 remote_ops.to_fileio_close = remote_hostio_close;
13008 remote_ops.to_fileio_unlink = remote_hostio_unlink;
13009 remote_ops.to_fileio_readlink = remote_hostio_readlink;
13010 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13011 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13012 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13013 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13014 remote_ops.to_trace_init = remote_trace_init;
13015 remote_ops.to_download_tracepoint = remote_download_tracepoint;
13016 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13017 remote_ops.to_download_trace_state_variable
13018 = remote_download_trace_state_variable;
13019 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13020 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13021 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13022 remote_ops.to_trace_start = remote_trace_start;
13023 remote_ops.to_get_trace_status = remote_get_trace_status;
13024 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13025 remote_ops.to_trace_stop = remote_trace_stop;
13026 remote_ops.to_trace_find = remote_trace_find;
13027 remote_ops.to_get_trace_state_variable_value
13028 = remote_get_trace_state_variable_value;
13029 remote_ops.to_save_trace_data = remote_save_trace_data;
13030 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13031 remote_ops.to_upload_trace_state_variables
13032 = remote_upload_trace_state_variables;
13033 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13034 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13035 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13036 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13037 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13038 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13039 remote_ops.to_core_of_thread = remote_core_of_thread;
13040 remote_ops.to_verify_memory = remote_verify_memory;
13041 remote_ops.to_get_tib_address = remote_get_tib_address;
13042 remote_ops.to_set_permissions = remote_set_permissions;
13043 remote_ops.to_static_tracepoint_marker_at
13044 = remote_static_tracepoint_marker_at;
13045 remote_ops.to_static_tracepoint_markers_by_strid
13046 = remote_static_tracepoint_markers_by_strid;
13047 remote_ops.to_traceframe_info = remote_traceframe_info;
13048 remote_ops.to_use_agent = remote_use_agent;
13049 remote_ops.to_can_use_agent = remote_can_use_agent;
13050 remote_ops.to_supports_btrace = remote_supports_btrace;
13051 remote_ops.to_enable_btrace = remote_enable_btrace;
13052 remote_ops.to_disable_btrace = remote_disable_btrace;
13053 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13054 remote_ops.to_read_btrace = remote_read_btrace;
13055 remote_ops.to_btrace_conf = remote_btrace_conf;
13056 remote_ops.to_augmented_libraries_svr4_read =
13057 remote_augmented_libraries_svr4_read;
13060 /* Set up the extended remote vector by making a copy of the standard
13061 remote vector and adding to it. */
13064 init_extended_remote_ops (void)
13066 extended_remote_ops = remote_ops;
13068 extended_remote_ops.to_shortname = "extended-remote";
13069 extended_remote_ops.to_longname =
13070 "Extended remote serial target in gdb-specific protocol";
13071 extended_remote_ops.to_doc =
13072 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13073 Specify the serial device it is connected to (e.g. /dev/ttya).";
13074 extended_remote_ops.to_open = extended_remote_open;
13075 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13076 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
13077 extended_remote_ops.to_detach = extended_remote_detach;
13078 extended_remote_ops.to_attach = extended_remote_attach;
13079 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13080 extended_remote_ops.to_kill = extended_remote_kill;
13081 extended_remote_ops.to_supports_disable_randomization
13082 = extended_remote_supports_disable_randomization;
13083 extended_remote_ops.to_follow_fork = remote_follow_fork;
13084 extended_remote_ops.to_follow_exec = remote_follow_exec;
13085 extended_remote_ops.to_insert_fork_catchpoint
13086 = remote_insert_fork_catchpoint;
13087 extended_remote_ops.to_remove_fork_catchpoint
13088 = remote_remove_fork_catchpoint;
13089 extended_remote_ops.to_insert_vfork_catchpoint
13090 = remote_insert_vfork_catchpoint;
13091 extended_remote_ops.to_remove_vfork_catchpoint
13092 = remote_remove_vfork_catchpoint;
13093 extended_remote_ops.to_insert_exec_catchpoint
13094 = remote_insert_exec_catchpoint;
13095 extended_remote_ops.to_remove_exec_catchpoint
13096 = remote_remove_exec_catchpoint;
13100 remote_can_async_p (struct target_ops *ops)
13102 struct remote_state *rs = get_remote_state ();
13104 if (!target_async_permitted)
13105 /* We only enable async when the user specifically asks for it. */
13108 /* We're async whenever the serial device is. */
13109 return serial_can_async_p (rs->remote_desc);
13113 remote_is_async_p (struct target_ops *ops)
13115 struct remote_state *rs = get_remote_state ();
13117 if (!target_async_permitted)
13118 /* We only enable async when the user specifically asks for it. */
13121 /* We're async whenever the serial device is. */
13122 return serial_is_async_p (rs->remote_desc);
13125 /* Pass the SERIAL event on and up to the client. One day this code
13126 will be able to delay notifying the client of an event until the
13127 point where an entire packet has been received. */
13129 static serial_event_ftype remote_async_serial_handler;
13132 remote_async_serial_handler (struct serial *scb, void *context)
13134 struct remote_state *rs = (struct remote_state *) context;
13136 /* Don't propogate error information up to the client. Instead let
13137 the client find out about the error by querying the target. */
13138 inferior_event_handler (INF_REG_EVENT, NULL);
13142 remote_async_inferior_event_handler (gdb_client_data data)
13144 inferior_event_handler (INF_REG_EVENT, NULL);
13148 remote_async (struct target_ops *ops, int enable)
13150 struct remote_state *rs = get_remote_state ();
13154 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13156 /* If there are pending events in the stop reply queue tell the
13157 event loop to process them. */
13158 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13159 mark_async_event_handler (remote_async_inferior_event_token);
13160 /* For simplicity, below we clear the pending events token
13161 without remembering whether it is marked, so here we always
13162 mark it. If there's actually no pending notification to
13163 process, this ends up being a no-op (other than a spurious
13164 event-loop wakeup). */
13165 if (target_is_non_stop_p ())
13166 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13170 serial_async (rs->remote_desc, NULL, NULL);
13171 /* If the core is disabling async, it doesn't want to be
13172 disturbed with target events. Clear all async event sources
13174 clear_async_event_handler (remote_async_inferior_event_token);
13175 if (target_is_non_stop_p ())
13176 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13180 /* Implementation of the to_thread_events method. */
13183 remote_thread_events (struct target_ops *ops, int enable)
13185 struct remote_state *rs = get_remote_state ();
13186 size_t size = get_remote_packet_size ();
13189 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13192 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13194 getpkt (&rs->buf, &rs->buf_size, 0);
13196 switch (packet_ok (rs->buf,
13197 &remote_protocol_packets[PACKET_QThreadEvents]))
13200 if (strcmp (rs->buf, "OK") != 0)
13201 error (_("Remote refused setting thread events: %s"), rs->buf);
13204 warning (_("Remote failure reply: %s"), rs->buf);
13206 case PACKET_UNKNOWN:
13212 set_remote_cmd (char *args, int from_tty)
13214 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13218 show_remote_cmd (char *args, int from_tty)
13220 /* We can't just use cmd_show_list here, because we want to skip
13221 the redundant "show remote Z-packet" and the legacy aliases. */
13222 struct cleanup *showlist_chain;
13223 struct cmd_list_element *list = remote_show_cmdlist;
13224 struct ui_out *uiout = current_uiout;
13226 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13227 for (; list != NULL; list = list->next)
13228 if (strcmp (list->name, "Z-packet") == 0)
13230 else if (list->type == not_set_cmd)
13231 /* Alias commands are exactly like the original, except they
13232 don't have the normal type. */
13236 struct cleanup *option_chain
13237 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13239 ui_out_field_string (uiout, "name", list->name);
13240 ui_out_text (uiout, ": ");
13241 if (list->type == show_cmd)
13242 do_show_command ((char *) NULL, from_tty, list);
13244 cmd_func (list, NULL, from_tty);
13245 /* Close the tuple. */
13246 do_cleanups (option_chain);
13249 /* Close the tuple. */
13250 do_cleanups (showlist_chain);
13254 /* Function to be called whenever a new objfile (shlib) is detected. */
13256 remote_new_objfile (struct objfile *objfile)
13258 struct remote_state *rs = get_remote_state ();
13260 if (rs->remote_desc != 0) /* Have a remote connection. */
13261 remote_check_symbols ();
13264 /* Pull all the tracepoints defined on the target and create local
13265 data structures representing them. We don't want to create real
13266 tracepoints yet, we don't want to mess up the user's existing
13270 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13272 struct remote_state *rs = get_remote_state ();
13275 /* Ask for a first packet of tracepoint definition. */
13277 getpkt (&rs->buf, &rs->buf_size, 0);
13279 while (*p && *p != 'l')
13281 parse_tracepoint_definition (p, utpp);
13282 /* Ask for another packet of tracepoint definition. */
13284 getpkt (&rs->buf, &rs->buf_size, 0);
13291 remote_upload_trace_state_variables (struct target_ops *self,
13292 struct uploaded_tsv **utsvp)
13294 struct remote_state *rs = get_remote_state ();
13297 /* Ask for a first packet of variable definition. */
13299 getpkt (&rs->buf, &rs->buf_size, 0);
13301 while (*p && *p != 'l')
13303 parse_tsv_definition (p, utsvp);
13304 /* Ask for another packet of variable definition. */
13306 getpkt (&rs->buf, &rs->buf_size, 0);
13312 /* The "set/show range-stepping" show hook. */
13315 show_range_stepping (struct ui_file *file, int from_tty,
13316 struct cmd_list_element *c,
13319 fprintf_filtered (file,
13320 _("Debugger's willingness to use range stepping "
13321 "is %s.\n"), value);
13324 /* The "set/show range-stepping" set hook. */
13327 set_range_stepping (char *ignore_args, int from_tty,
13328 struct cmd_list_element *c)
13330 struct remote_state *rs = get_remote_state ();
13332 /* Whene enabling, check whether range stepping is actually
13333 supported by the target, and warn if not. */
13334 if (use_range_stepping)
13336 if (rs->remote_desc != NULL)
13338 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13339 remote_vcont_probe (rs);
13341 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13342 && rs->supports_vCont.r)
13346 warning (_("Range stepping is not supported by the current target"));
13351 _initialize_remote (void)
13353 struct remote_state *rs;
13354 struct cmd_list_element *cmd;
13355 const char *cmd_name;
13357 /* architecture specific data */
13358 remote_gdbarch_data_handle =
13359 gdbarch_data_register_post_init (init_remote_state);
13360 remote_g_packet_data_handle =
13361 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13364 = register_program_space_data_with_cleanup (NULL,
13365 remote_pspace_data_cleanup);
13367 /* Initialize the per-target state. At the moment there is only one
13368 of these, not one per target. Only one target is active at a
13370 remote_state = new_remote_state ();
13372 init_remote_ops ();
13373 add_target (&remote_ops);
13375 init_extended_remote_ops ();
13376 add_target (&extended_remote_ops);
13378 /* Hook into new objfile notification. */
13379 observer_attach_new_objfile (remote_new_objfile);
13380 /* We're no longer interested in notification events of an inferior
13382 observer_attach_inferior_exit (discard_pending_stop_replies);
13384 /* Set up signal handlers. */
13385 async_sigint_remote_token =
13386 create_async_signal_handler (async_remote_interrupt, NULL);
13387 async_sigint_remote_twice_token =
13388 create_async_signal_handler (async_remote_interrupt_twice, NULL);
13391 init_remote_threadtests ();
13394 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13395 /* set/show remote ... */
13397 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13398 Remote protocol specific variables\n\
13399 Configure various remote-protocol specific variables such as\n\
13400 the packets being used"),
13401 &remote_set_cmdlist, "set remote ",
13402 0 /* allow-unknown */, &setlist);
13403 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13404 Remote protocol specific variables\n\
13405 Configure various remote-protocol specific variables such as\n\
13406 the packets being used"),
13407 &remote_show_cmdlist, "show remote ",
13408 0 /* allow-unknown */, &showlist);
13410 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13411 Compare section data on target to the exec file.\n\
13412 Argument is a single section name (default: all loaded sections).\n\
13413 To compare only read-only loaded sections, specify the -r option."),
13416 add_cmd ("packet", class_maintenance, packet_command, _("\
13417 Send an arbitrary packet to a remote target.\n\
13418 maintenance packet TEXT\n\
13419 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13420 this command sends the string TEXT to the inferior, and displays the\n\
13421 response packet. GDB supplies the initial `$' character, and the\n\
13422 terminating `#' character and checksum."),
13425 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13426 Set whether to send break if interrupted."), _("\
13427 Show whether to send break if interrupted."), _("\
13428 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13429 set_remotebreak, show_remotebreak,
13430 &setlist, &showlist);
13431 cmd_name = "remotebreak";
13432 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13433 deprecate_cmd (cmd, "set remote interrupt-sequence");
13434 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13435 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13436 deprecate_cmd (cmd, "show remote interrupt-sequence");
13438 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13439 interrupt_sequence_modes, &interrupt_sequence_mode,
13441 Set interrupt sequence to remote target."), _("\
13442 Show interrupt sequence to remote target."), _("\
13443 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13444 NULL, show_interrupt_sequence,
13445 &remote_set_cmdlist,
13446 &remote_show_cmdlist);
13448 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13449 &interrupt_on_connect, _("\
13450 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13451 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13452 If set, interrupt sequence is sent to remote target."),
13454 &remote_set_cmdlist, &remote_show_cmdlist);
13456 /* Install commands for configuring memory read/write packets. */
13458 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13459 Set the maximum number of bytes per memory write packet (deprecated)."),
13461 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13462 Show the maximum number of bytes per memory write packet (deprecated)."),
13464 add_cmd ("memory-write-packet-size", no_class,
13465 set_memory_write_packet_size, _("\
13466 Set the maximum number of bytes per memory-write packet.\n\
13467 Specify the number of bytes in a packet or 0 (zero) for the\n\
13468 default packet size. The actual limit is further reduced\n\
13469 dependent on the target. Specify ``fixed'' to disable the\n\
13470 further restriction and ``limit'' to enable that restriction."),
13471 &remote_set_cmdlist);
13472 add_cmd ("memory-read-packet-size", no_class,
13473 set_memory_read_packet_size, _("\
13474 Set the maximum number of bytes per memory-read packet.\n\
13475 Specify the number of bytes in a packet or 0 (zero) for the\n\
13476 default packet size. The actual limit is further reduced\n\
13477 dependent on the target. Specify ``fixed'' to disable the\n\
13478 further restriction and ``limit'' to enable that restriction."),
13479 &remote_set_cmdlist);
13480 add_cmd ("memory-write-packet-size", no_class,
13481 show_memory_write_packet_size,
13482 _("Show the maximum number of bytes per memory-write packet."),
13483 &remote_show_cmdlist);
13484 add_cmd ("memory-read-packet-size", no_class,
13485 show_memory_read_packet_size,
13486 _("Show the maximum number of bytes per memory-read packet."),
13487 &remote_show_cmdlist);
13489 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13490 &remote_hw_watchpoint_limit, _("\
13491 Set the maximum number of target hardware watchpoints."), _("\
13492 Show the maximum number of target hardware watchpoints."), _("\
13493 Specify a negative limit for unlimited."),
13494 NULL, NULL, /* FIXME: i18n: The maximum
13495 number of target hardware
13496 watchpoints is %s. */
13497 &remote_set_cmdlist, &remote_show_cmdlist);
13498 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13499 &remote_hw_watchpoint_length_limit, _("\
13500 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13501 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13502 Specify a negative limit for unlimited."),
13503 NULL, NULL, /* FIXME: i18n: The maximum
13504 length (in bytes) of a target
13505 hardware watchpoint is %s. */
13506 &remote_set_cmdlist, &remote_show_cmdlist);
13507 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13508 &remote_hw_breakpoint_limit, _("\
13509 Set the maximum number of target hardware breakpoints."), _("\
13510 Show the maximum number of target hardware breakpoints."), _("\
13511 Specify a negative limit for unlimited."),
13512 NULL, NULL, /* FIXME: i18n: The maximum
13513 number of target hardware
13514 breakpoints is %s. */
13515 &remote_set_cmdlist, &remote_show_cmdlist);
13517 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13518 &remote_address_size, _("\
13519 Set the maximum size of the address (in bits) in a memory packet."), _("\
13520 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13522 NULL, /* FIXME: i18n: */
13523 &setlist, &showlist);
13525 init_all_packet_configs ();
13527 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13528 "X", "binary-download", 1);
13530 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13531 "vCont", "verbose-resume", 0);
13533 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13534 "QPassSignals", "pass-signals", 0);
13536 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13537 "QProgramSignals", "program-signals", 0);
13539 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13540 "qSymbol", "symbol-lookup", 0);
13542 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13543 "P", "set-register", 1);
13545 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13546 "p", "fetch-register", 1);
13548 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13549 "Z0", "software-breakpoint", 0);
13551 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13552 "Z1", "hardware-breakpoint", 0);
13554 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13555 "Z2", "write-watchpoint", 0);
13557 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13558 "Z3", "read-watchpoint", 0);
13560 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13561 "Z4", "access-watchpoint", 0);
13563 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13564 "qXfer:auxv:read", "read-aux-vector", 0);
13566 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13567 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13569 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13570 "qXfer:features:read", "target-features", 0);
13572 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13573 "qXfer:libraries:read", "library-info", 0);
13575 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13576 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13578 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13579 "qXfer:memory-map:read", "memory-map", 0);
13581 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13582 "qXfer:spu:read", "read-spu-object", 0);
13584 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13585 "qXfer:spu:write", "write-spu-object", 0);
13587 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13588 "qXfer:osdata:read", "osdata", 0);
13590 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13591 "qXfer:threads:read", "threads", 0);
13593 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13594 "qXfer:siginfo:read", "read-siginfo-object", 0);
13596 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13597 "qXfer:siginfo:write", "write-siginfo-object", 0);
13599 add_packet_config_cmd
13600 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13601 "qXfer:traceframe-info:read", "traceframe-info", 0);
13603 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13604 "qXfer:uib:read", "unwind-info-block", 0);
13606 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13607 "qGetTLSAddr", "get-thread-local-storage-address",
13610 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13611 "qGetTIBAddr", "get-thread-information-block-address",
13614 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13615 "bc", "reverse-continue", 0);
13617 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13618 "bs", "reverse-step", 0);
13620 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13621 "qSupported", "supported-packets", 0);
13623 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13624 "qSearch:memory", "search-memory", 0);
13626 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13627 "qTStatus", "trace-status", 0);
13629 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13630 "vFile:setfs", "hostio-setfs", 0);
13632 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13633 "vFile:open", "hostio-open", 0);
13635 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13636 "vFile:pread", "hostio-pread", 0);
13638 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13639 "vFile:pwrite", "hostio-pwrite", 0);
13641 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13642 "vFile:close", "hostio-close", 0);
13644 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13645 "vFile:unlink", "hostio-unlink", 0);
13647 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13648 "vFile:readlink", "hostio-readlink", 0);
13650 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13651 "vFile:fstat", "hostio-fstat", 0);
13653 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13654 "vAttach", "attach", 0);
13656 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13659 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13660 "QStartNoAckMode", "noack", 0);
13662 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13663 "vKill", "kill", 0);
13665 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13666 "qAttached", "query-attached", 0);
13668 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13669 "ConditionalTracepoints",
13670 "conditional-tracepoints", 0);
13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13673 "ConditionalBreakpoints",
13674 "conditional-breakpoints", 0);
13676 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13677 "BreakpointCommands",
13678 "breakpoint-commands", 0);
13680 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13681 "FastTracepoints", "fast-tracepoints", 0);
13683 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13684 "TracepointSource", "TracepointSource", 0);
13686 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13687 "QAllow", "allow", 0);
13689 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13690 "StaticTracepoints", "static-tracepoints", 0);
13692 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13693 "InstallInTrace", "install-in-trace", 0);
13695 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13696 "qXfer:statictrace:read", "read-sdata-object", 0);
13698 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13699 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13701 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13702 "QDisableRandomization", "disable-randomization", 0);
13704 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13705 "QAgent", "agent", 0);
13707 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13708 "QTBuffer:size", "trace-buffer-size", 0);
13710 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13711 "Qbtrace:off", "disable-btrace", 0);
13713 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13714 "Qbtrace:bts", "enable-btrace-bts", 0);
13716 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13717 "Qbtrace:pt", "enable-btrace-pt", 0);
13719 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13720 "qXfer:btrace", "read-btrace", 0);
13722 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13723 "qXfer:btrace-conf", "read-btrace-conf", 0);
13725 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13726 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13728 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13729 "multiprocess-feature", "multiprocess-feature", 0);
13731 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13732 "swbreak-feature", "swbreak-feature", 0);
13734 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13735 "hwbreak-feature", "hwbreak-feature", 0);
13737 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13738 "fork-event-feature", "fork-event-feature", 0);
13740 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13741 "vfork-event-feature", "vfork-event-feature", 0);
13743 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13744 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13746 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13747 "vContSupported", "verbose-resume-supported", 0);
13749 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13750 "exec-event-feature", "exec-event-feature", 0);
13752 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13753 "vCtrlC", "ctrl-c", 0);
13755 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13756 "QThreadEvents", "thread-events", 0);
13758 /* Assert that we've registered "set remote foo-packet" commands
13759 for all packet configs. */
13763 for (i = 0; i < PACKET_MAX; i++)
13765 /* Ideally all configs would have a command associated. Some
13766 still don't though. */
13771 case PACKET_QNonStop:
13772 case PACKET_EnableDisableTracepoints_feature:
13773 case PACKET_tracenz_feature:
13774 case PACKET_DisconnectedTracing_feature:
13775 case PACKET_augmented_libraries_svr4_read_feature:
13777 /* Additions to this list need to be well justified:
13778 pre-existing packets are OK; new packets are not. */
13786 /* This catches both forgetting to add a config command, and
13787 forgetting to remove a packet from the exception list. */
13788 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13792 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13793 Z sub-packet has its own set and show commands, but users may
13794 have sets to this variable in their .gdbinit files (or in their
13796 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13797 &remote_Z_packet_detect, _("\
13798 Set use of remote protocol `Z' packets"), _("\
13799 Show use of remote protocol `Z' packets "), _("\
13800 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13802 set_remote_protocol_Z_packet_cmd,
13803 show_remote_protocol_Z_packet_cmd,
13804 /* FIXME: i18n: Use of remote protocol
13805 `Z' packets is %s. */
13806 &remote_set_cmdlist, &remote_show_cmdlist);
13808 add_prefix_cmd ("remote", class_files, remote_command, _("\
13809 Manipulate files on the remote system\n\
13810 Transfer files to and from the remote target system."),
13811 &remote_cmdlist, "remote ",
13812 0 /* allow-unknown */, &cmdlist);
13814 add_cmd ("put", class_files, remote_put_command,
13815 _("Copy a local file to the remote system."),
13818 add_cmd ("get", class_files, remote_get_command,
13819 _("Copy a remote file to the local system."),
13822 add_cmd ("delete", class_files, remote_delete_command,
13823 _("Delete a remote file."),
13826 add_setshow_string_noescape_cmd ("exec-file", class_files,
13827 &remote_exec_file_var, _("\
13828 Set the remote pathname for \"run\""), _("\
13829 Show the remote pathname for \"run\""), NULL,
13830 set_remote_exec_file,
13831 show_remote_exec_file,
13832 &remote_set_cmdlist,
13833 &remote_show_cmdlist);
13835 add_setshow_boolean_cmd ("range-stepping", class_run,
13836 &use_range_stepping, _("\
13837 Enable or disable range stepping."), _("\
13838 Show whether target-assisted range stepping is enabled."), _("\
13839 If on, and the target supports it, when stepping a source line, GDB\n\
13840 tells the target to step the corresponding range of addresses itself instead\n\
13841 of issuing multiple single-steps. This speeds up source level\n\
13842 stepping. If off, GDB always issues single-steps, even if range\n\
13843 stepping is supported by the target. The default is on."),
13844 set_range_stepping,
13845 show_range_stepping,
13849 /* Eventually initialize fileio. See fileio.c */
13850 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13852 /* Take advantage of the fact that the TID field is not used, to tag
13853 special ptids with it set to != 0. */
13854 magic_null_ptid = ptid_build (42000, -1, 1);
13855 not_sent_ptid = ptid_build (42000, -2, 1);
13856 any_thread_ptid = ptid_build (42000, 0, 1);
13858 target_buf_size = 2048;
13859 target_buf = (char *) xmalloc (target_buf_size);