1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
30 /*#include "terminal.h" */
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
36 #include "remote-notif.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
50 #include "event-loop.h"
51 #include "event-top.h"
57 #include "gdbcore.h" /* for exec_bfd */
59 #include "remote-fileio.h"
60 #include "gdb/fileio.h"
62 #include "xml-support.h"
64 #include "memory-map.h"
66 #include "tracepoint.h"
72 /* Temp hacks for tracepoint encoding migration. */
73 static char *target_buf;
74 static long target_buf_size;
76 /* The size to align memory write packets, when practical. The protocol
77 does not guarantee any alignment, and gdb will generate short
78 writes and unaligned writes, but even as a best-effort attempt this
79 can improve bulk transfers. For instance, if a write is misaligned
80 relative to the target's data bus, the stub may need to make an extra
81 round trip fetching data from the target. This doesn't make a
82 huge difference, but it's easy to do, so we try to be helpful.
84 The alignment chosen is arbitrary; usually data bus width is
85 important here, not the possibly larger cache line size. */
86 enum { REMOTE_ALIGN_WRITES = 16 };
88 /* Prototypes for local functions. */
89 static void async_cleanup_sigint_signal_handler (void *dummy);
90 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
91 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
92 int forever, int *is_notif);
94 static void async_handle_remote_sigint (int);
95 static void async_handle_remote_sigint_twice (int);
97 static void remote_files_info (struct target_ops *ignore);
99 static void remote_prepare_to_store (struct target_ops *self,
100 struct regcache *regcache);
102 static void remote_open_1 (const char *, int, struct target_ops *,
105 static void remote_close (struct target_ops *self);
107 static void remote_mourn (struct target_ops *ops);
109 static void extended_remote_restart (void);
111 static void extended_remote_mourn (struct target_ops *);
113 static void remote_send (char **buf, long *sizeof_buf_p);
115 static int readchar (int timeout);
117 static void remote_serial_write (const char *str, int len);
119 static void remote_kill (struct target_ops *ops);
121 static int remote_can_async_p (struct target_ops *);
123 static int remote_is_async_p (struct target_ops *);
125 static void remote_async (struct target_ops *ops, int enable);
127 static void sync_remote_interrupt_twice (int signo);
129 static void interrupt_query (void);
131 static void set_general_thread (struct ptid ptid);
132 static void set_continue_thread (struct ptid ptid);
134 static void get_offsets (void);
136 static void skip_frame (void);
138 static long read_frame (char **buf_p, long *sizeof_buf);
140 static int hexnumlen (ULONGEST num);
142 static void init_remote_ops (void);
144 static void init_extended_remote_ops (void);
146 static void remote_stop (struct target_ops *self, ptid_t);
148 static int stubhex (int ch);
150 static int hexnumstr (char *, ULONGEST);
152 static int hexnumnstr (char *, ULONGEST, int);
154 static CORE_ADDR remote_address_masked (CORE_ADDR);
156 static void print_packet (const char *);
158 static void compare_sections_command (char *, int);
160 static void packet_command (char *, int);
162 static int stub_unpack_int (char *buff, int fieldlength);
164 static ptid_t remote_current_thread (ptid_t oldptid);
166 static int putpkt_binary (const char *buf, int cnt);
168 static void check_binary_download (CORE_ADDR addr);
170 struct packet_config;
172 static void show_packet_config_cmd (struct packet_config *config);
174 static void show_remote_protocol_packet_cmd (struct ui_file *file,
176 struct cmd_list_element *c,
179 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
180 static ptid_t read_ptid (char *buf, char **obuf);
182 static void remote_set_permissions (struct target_ops *self);
185 static int remote_get_trace_status (struct target_ops *self,
186 struct trace_status *ts);
188 static int remote_upload_tracepoints (struct target_ops *self,
189 struct uploaded_tp **utpp);
191 static int remote_upload_trace_state_variables (struct target_ops *self,
192 struct uploaded_tsv **utsvp);
194 static void remote_query_supported (void);
196 static void remote_check_symbols (void);
198 void _initialize_remote (void);
201 static void stop_reply_xfree (struct stop_reply *);
202 static void remote_parse_stop_reply (char *, struct stop_reply *);
203 static void push_stop_reply (struct stop_reply *);
204 static void discard_pending_stop_replies_in_queue (struct remote_state *);
205 static int peek_stop_reply (ptid_t ptid);
207 static void remote_async_inferior_event_handler (gdb_client_data);
209 static void remote_terminal_ours (struct target_ops *self);
211 static int remote_read_description_p (struct target_ops *target);
213 static void remote_console_output (char *msg);
215 static int remote_supports_cond_breakpoints (struct target_ops *self);
217 static int remote_can_run_breakpoint_commands (struct target_ops *self);
219 static void remote_btrace_reset (void);
223 static struct cmd_list_element *remote_cmdlist;
225 /* For "set remote" and "show remote". */
227 static struct cmd_list_element *remote_set_cmdlist;
228 static struct cmd_list_element *remote_show_cmdlist;
230 /* Stub vCont actions support.
232 Each field is a boolean flag indicating whether the stub reports
233 support for the corresponding action. */
235 struct vCont_action_support
244 /* Controls whether GDB is willing to use range stepping. */
246 static int use_range_stepping = 1;
248 #define OPAQUETHREADBYTES 8
250 /* a 64 bit opaque identifier */
251 typedef unsigned char threadref[OPAQUETHREADBYTES];
253 /* About this many threadisds fit in a packet. */
255 #define MAXTHREADLISTRESULTS 32
257 /* Description of the remote protocol state for the currently
258 connected target. This is per-target state, and independent of the
259 selected architecture. */
263 /* A buffer to use for incoming packets, and its current size. The
264 buffer is grown dynamically for larger incoming packets.
265 Outgoing packets may also be constructed in this buffer.
266 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
267 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
272 /* True if we're going through initial connection setup (finding out
273 about the remote side's threads, relocating symbols, etc.). */
276 /* If we negotiated packet size explicitly (and thus can bypass
277 heuristics for the largest packet size that will not overflow
278 a buffer in the stub), this will be set to that packet size.
279 Otherwise zero, meaning to use the guessed size. */
280 long explicit_packet_size;
282 /* remote_wait is normally called when the target is running and
283 waits for a stop reply packet. But sometimes we need to call it
284 when the target is already stopped. We can send a "?" packet
285 and have remote_wait read the response. Or, if we already have
286 the response, we can stash it in BUF and tell remote_wait to
287 skip calling getpkt. This flag is set when BUF contains a
288 stop reply packet and the target is not waiting. */
289 int cached_wait_status;
291 /* True, if in no ack mode. That is, neither GDB nor the stub will
292 expect acks from each other. The connection is assumed to be
296 /* True if we're connected in extended remote mode. */
299 /* True if we resumed the target and we're waiting for the target to
300 stop. In the mean time, we can't start another command/query.
301 The remote server wouldn't be ready to process it, so we'd
302 timeout waiting for a reply that would never come and eventually
303 we'd close the connection. This can happen in asynchronous mode
304 because we allow GDB commands while the target is running. */
305 int waiting_for_stop_reply;
307 /* The status of the stub support for the various vCont actions. */
308 struct vCont_action_support supports_vCont;
310 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
311 responded to that. */
314 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
315 remote_open knows that we don't have a file open when the program
317 struct serial *remote_desc;
319 /* These are the threads which we last sent to the remote system. The
320 TID member will be -1 for all or -2 for not sent yet. */
321 ptid_t general_thread;
322 ptid_t continue_thread;
324 /* This is the traceframe which we last selected on the remote system.
325 It will be -1 if no traceframe is selected. */
326 int remote_traceframe_number;
328 char *last_pass_packet;
330 /* The last QProgramSignals packet sent to the target. We bypass
331 sending a new program signals list down to the target if the new
332 packet is exactly the same as the last we sent. IOW, we only let
333 the target know about program signals list changes. */
334 char *last_program_signals_packet;
336 enum gdb_signal last_sent_signal;
340 char *finished_object;
341 char *finished_annex;
342 ULONGEST finished_offset;
344 /* Should we try the 'ThreadInfo' query packet?
346 This variable (NOT available to the user: auto-detect only!)
347 determines whether GDB will use the new, simpler "ThreadInfo"
348 query or the older, more complex syntax for thread queries.
349 This is an auto-detect variable (set to true at each connect,
350 and set to false when the target fails to recognize it). */
351 int use_threadinfo_query;
352 int use_threadextra_query;
354 /* This is set to the data address of the access causing the target
355 to stop for a watchpoint. */
356 CORE_ADDR remote_watch_data_address;
358 /* Whether the target stopped for a breakpoint/watchpoint. */
359 enum target_stop_reason stop_reason;
361 threadref echo_nextthread;
362 threadref nextthread;
363 threadref resultthreadlist[MAXTHREADLISTRESULTS];
365 /* The state of remote notification. */
366 struct remote_notif_state *notif_state;
368 /* The branch trace configuration. */
369 struct btrace_config btrace_config;
372 /* Private data that we'll store in (struct thread_info)->private. */
373 struct private_thread_info
380 free_private_thread_info (struct private_thread_info *info)
386 /* This data could be associated with a target, but we do not always
387 have access to the current target when we need it, so for now it is
388 static. This will be fine for as long as only one target is in use
390 static struct remote_state *remote_state;
392 static struct remote_state *
393 get_remote_state_raw (void)
398 /* Allocate a new struct remote_state with xmalloc, initialize it, and
401 static struct remote_state *
402 new_remote_state (void)
404 struct remote_state *result = XCNEW (struct remote_state);
406 /* The default buffer size is unimportant; it will be expanded
407 whenever a larger buffer is needed. */
408 result->buf_size = 400;
409 result->buf = xmalloc (result->buf_size);
410 result->remote_traceframe_number = -1;
411 result->last_sent_signal = GDB_SIGNAL_0;
416 /* Description of the remote protocol for a given architecture. */
420 long offset; /* Offset into G packet. */
421 long regnum; /* GDB's internal register number. */
422 LONGEST pnum; /* Remote protocol register number. */
423 int in_g_packet; /* Always part of G packet. */
424 /* long size in bytes; == register_size (target_gdbarch (), regnum);
426 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
430 struct remote_arch_state
432 /* Description of the remote protocol registers. */
433 long sizeof_g_packet;
435 /* Description of the remote protocol registers indexed by REGNUM
436 (making an array gdbarch_num_regs in size). */
437 struct packet_reg *regs;
439 /* This is the size (in chars) of the first response to the ``g''
440 packet. It is used as a heuristic when determining the maximum
441 size of memory-read and memory-write packets. A target will
442 typically only reserve a buffer large enough to hold the ``g''
443 packet. The size does not include packet overhead (headers and
445 long actual_register_packet_size;
447 /* This is the maximum size (in chars) of a non read/write packet.
448 It is also used as a cap on the size of read/write packets. */
449 long remote_packet_size;
452 /* Utility: generate error from an incoming stub packet. */
454 trace_error (char *buf)
457 return; /* not an error msg */
460 case '1': /* malformed packet error */
461 if (*++buf == '0') /* general case: */
462 error (_("remote.c: error in outgoing packet."));
464 error (_("remote.c: error in outgoing packet at field #%ld."),
465 strtol (buf, NULL, 16));
467 error (_("Target returns error code '%s'."), buf);
471 /* Utility: wait for reply from stub, while accepting "O" packets. */
473 remote_get_noisy_reply (char **buf_p,
476 do /* Loop on reply from remote stub. */
480 QUIT; /* Allow user to bail out with ^C. */
481 getpkt (buf_p, sizeof_buf, 0);
485 else if (startswith (buf, "qRelocInsn:"))
488 CORE_ADDR from, to, org_to;
490 int adjusted_size = 0;
493 p = buf + strlen ("qRelocInsn:");
494 pp = unpack_varlen_hex (p, &ul);
496 error (_("invalid qRelocInsn packet: %s"), buf);
500 unpack_varlen_hex (p, &ul);
507 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
510 CATCH (ex, RETURN_MASK_ALL)
512 if (ex.error == MEMORY_ERROR)
514 /* Propagate memory errors silently back to the
515 target. The stub may have limited the range of
516 addresses we can write to, for example. */
520 /* Something unexpectedly bad happened. Be verbose
521 so we can tell what, and propagate the error back
522 to the stub, so it doesn't get stuck waiting for
524 exception_fprintf (gdb_stderr, ex,
525 _("warning: relocating instruction: "));
533 adjusted_size = to - org_to;
535 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
539 else if (buf[0] == 'O' && buf[1] != 'K')
540 remote_console_output (buf + 1); /* 'O' message from stub */
542 return buf; /* Here's the actual reply. */
547 /* Handle for retreving the remote protocol data from gdbarch. */
548 static struct gdbarch_data *remote_gdbarch_data_handle;
550 static struct remote_arch_state *
551 get_remote_arch_state (void)
553 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
556 /* Fetch the global remote target state. */
558 static struct remote_state *
559 get_remote_state (void)
561 /* Make sure that the remote architecture state has been
562 initialized, because doing so might reallocate rs->buf. Any
563 function which calls getpkt also needs to be mindful of changes
564 to rs->buf, but this call limits the number of places which run
566 get_remote_arch_state ();
568 return get_remote_state_raw ();
572 compare_pnums (const void *lhs_, const void *rhs_)
574 const struct packet_reg * const *lhs = lhs_;
575 const struct packet_reg * const *rhs = rhs_;
577 if ((*lhs)->pnum < (*rhs)->pnum)
579 else if ((*lhs)->pnum == (*rhs)->pnum)
586 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
588 int regnum, num_remote_regs, offset;
589 struct packet_reg **remote_regs;
591 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
593 struct packet_reg *r = ®s[regnum];
595 if (register_size (gdbarch, regnum) == 0)
596 /* Do not try to fetch zero-sized (placeholder) registers. */
599 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
604 /* Define the g/G packet format as the contents of each register
605 with a remote protocol number, in order of ascending protocol
608 remote_regs = alloca (gdbarch_num_regs (gdbarch)
609 * sizeof (struct packet_reg *));
610 for (num_remote_regs = 0, regnum = 0;
611 regnum < gdbarch_num_regs (gdbarch);
613 if (regs[regnum].pnum != -1)
614 remote_regs[num_remote_regs++] = ®s[regnum];
616 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
619 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
621 remote_regs[regnum]->in_g_packet = 1;
622 remote_regs[regnum]->offset = offset;
623 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
629 /* Given the architecture described by GDBARCH, return the remote
630 protocol register's number and the register's offset in the g/G
631 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
632 If the target does not have a mapping for REGNUM, return false,
633 otherwise, return true. */
636 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
637 int *pnum, int *poffset)
640 struct packet_reg *regs;
641 struct cleanup *old_chain;
643 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
645 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
646 old_chain = make_cleanup (xfree, regs);
648 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
650 *pnum = regs[regnum].pnum;
651 *poffset = regs[regnum].offset;
653 do_cleanups (old_chain);
659 init_remote_state (struct gdbarch *gdbarch)
661 struct remote_state *rs = get_remote_state_raw ();
662 struct remote_arch_state *rsa;
664 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
666 /* Use the architecture to build a regnum<->pnum table, which will be
667 1:1 unless a feature set specifies otherwise. */
668 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
669 gdbarch_num_regs (gdbarch),
672 /* Record the maximum possible size of the g packet - it may turn out
674 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
676 /* Default maximum number of characters in a packet body. Many
677 remote stubs have a hardwired buffer size of 400 bytes
678 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
679 as the maximum packet-size to ensure that the packet and an extra
680 NUL character can always fit in the buffer. This stops GDB
681 trashing stubs that try to squeeze an extra NUL into what is
682 already a full buffer (As of 1999-12-04 that was most stubs). */
683 rsa->remote_packet_size = 400 - 1;
685 /* This one is filled in when a ``g'' packet is received. */
686 rsa->actual_register_packet_size = 0;
688 /* Should rsa->sizeof_g_packet needs more space than the
689 default, adjust the size accordingly. Remember that each byte is
690 encoded as two characters. 32 is the overhead for the packet
691 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
692 (``$NN:G...#NN'') is a better guess, the below has been padded a
694 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
695 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
697 /* Make sure that the packet buffer is plenty big enough for
698 this architecture. */
699 if (rs->buf_size < rsa->remote_packet_size)
701 rs->buf_size = 2 * rsa->remote_packet_size;
702 rs->buf = xrealloc (rs->buf, rs->buf_size);
708 /* Return the current allowed size of a remote packet. This is
709 inferred from the current architecture, and should be used to
710 limit the length of outgoing packets. */
712 get_remote_packet_size (void)
714 struct remote_state *rs = get_remote_state ();
715 struct remote_arch_state *rsa = get_remote_arch_state ();
717 if (rs->explicit_packet_size)
718 return rs->explicit_packet_size;
720 return rsa->remote_packet_size;
723 static struct packet_reg *
724 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
726 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
730 struct packet_reg *r = &rsa->regs[regnum];
732 gdb_assert (r->regnum == regnum);
737 static struct packet_reg *
738 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
742 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
744 struct packet_reg *r = &rsa->regs[i];
752 static struct target_ops remote_ops;
754 static struct target_ops extended_remote_ops;
756 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
757 ``forever'' still use the normal timeout mechanism. This is
758 currently used by the ASYNC code to guarentee that target reads
759 during the initial connect always time-out. Once getpkt has been
760 modified to return a timeout indication and, in turn
761 remote_wait()/wait_for_inferior() have gained a timeout parameter
763 static int wait_forever_enabled_p = 1;
765 /* Allow the user to specify what sequence to send to the remote
766 when he requests a program interruption: Although ^C is usually
767 what remote systems expect (this is the default, here), it is
768 sometimes preferable to send a break. On other systems such
769 as the Linux kernel, a break followed by g, which is Magic SysRq g
770 is required in order to interrupt the execution. */
771 const char interrupt_sequence_control_c[] = "Ctrl-C";
772 const char interrupt_sequence_break[] = "BREAK";
773 const char interrupt_sequence_break_g[] = "BREAK-g";
774 static const char *const interrupt_sequence_modes[] =
776 interrupt_sequence_control_c,
777 interrupt_sequence_break,
778 interrupt_sequence_break_g,
781 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
784 show_interrupt_sequence (struct ui_file *file, int from_tty,
785 struct cmd_list_element *c,
788 if (interrupt_sequence_mode == interrupt_sequence_control_c)
789 fprintf_filtered (file,
790 _("Send the ASCII ETX character (Ctrl-c) "
791 "to the remote target to interrupt the "
792 "execution of the program.\n"));
793 else if (interrupt_sequence_mode == interrupt_sequence_break)
794 fprintf_filtered (file,
795 _("send a break signal to the remote target "
796 "to interrupt the execution of the program.\n"));
797 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
798 fprintf_filtered (file,
799 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
800 "the remote target to interrupt the execution "
801 "of Linux kernel.\n"));
803 internal_error (__FILE__, __LINE__,
804 _("Invalid value for interrupt_sequence_mode: %s."),
805 interrupt_sequence_mode);
808 /* This boolean variable specifies whether interrupt_sequence is sent
809 to the remote target when gdb connects to it.
810 This is mostly needed when you debug the Linux kernel: The Linux kernel
811 expects BREAK g which is Magic SysRq g for connecting gdb. */
812 static int interrupt_on_connect = 0;
814 /* This variable is used to implement the "set/show remotebreak" commands.
815 Since these commands are now deprecated in favor of "set/show remote
816 interrupt-sequence", it no longer has any effect on the code. */
817 static int remote_break;
820 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
823 interrupt_sequence_mode = interrupt_sequence_break;
825 interrupt_sequence_mode = interrupt_sequence_control_c;
829 show_remotebreak (struct ui_file *file, int from_tty,
830 struct cmd_list_element *c,
835 /* This variable sets the number of bits in an address that are to be
836 sent in a memory ("M" or "m") packet. Normally, after stripping
837 leading zeros, the entire address would be sent. This variable
838 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
839 initial implementation of remote.c restricted the address sent in
840 memory packets to ``host::sizeof long'' bytes - (typically 32
841 bits). Consequently, for 64 bit targets, the upper 32 bits of an
842 address was never sent. Since fixing this bug may cause a break in
843 some remote targets this variable is principly provided to
844 facilitate backward compatibility. */
846 static unsigned int remote_address_size;
848 /* Temporary to track who currently owns the terminal. See
849 remote_terminal_* for more details. */
851 static int remote_async_terminal_ours_p;
853 /* The executable file to use for "run" on the remote side. */
855 static char *remote_exec_file = "";
858 /* User configurable variables for the number of characters in a
859 memory read/write packet. MIN (rsa->remote_packet_size,
860 rsa->sizeof_g_packet) is the default. Some targets need smaller
861 values (fifo overruns, et.al.) and some users need larger values
862 (speed up transfers). The variables ``preferred_*'' (the user
863 request), ``current_*'' (what was actually set) and ``forced_*''
864 (Positive - a soft limit, negative - a hard limit). */
866 struct memory_packet_config
873 /* Compute the current size of a read/write packet. Since this makes
874 use of ``actual_register_packet_size'' the computation is dynamic. */
877 get_memory_packet_size (struct memory_packet_config *config)
879 struct remote_state *rs = get_remote_state ();
880 struct remote_arch_state *rsa = get_remote_arch_state ();
882 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
883 law?) that some hosts don't cope very well with large alloca()
884 calls. Eventually the alloca() code will be replaced by calls to
885 xmalloc() and make_cleanups() allowing this restriction to either
886 be lifted or removed. */
887 #ifndef MAX_REMOTE_PACKET_SIZE
888 #define MAX_REMOTE_PACKET_SIZE 16384
890 /* NOTE: 20 ensures we can write at least one byte. */
891 #ifndef MIN_REMOTE_PACKET_SIZE
892 #define MIN_REMOTE_PACKET_SIZE 20
897 if (config->size <= 0)
898 what_they_get = MAX_REMOTE_PACKET_SIZE;
900 what_they_get = config->size;
904 what_they_get = get_remote_packet_size ();
905 /* Limit the packet to the size specified by the user. */
907 && what_they_get > config->size)
908 what_they_get = config->size;
910 /* Limit it to the size of the targets ``g'' response unless we have
911 permission from the stub to use a larger packet size. */
912 if (rs->explicit_packet_size == 0
913 && rsa->actual_register_packet_size > 0
914 && what_they_get > rsa->actual_register_packet_size)
915 what_they_get = rsa->actual_register_packet_size;
917 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
918 what_they_get = MAX_REMOTE_PACKET_SIZE;
919 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
920 what_they_get = MIN_REMOTE_PACKET_SIZE;
922 /* Make sure there is room in the global buffer for this packet
923 (including its trailing NUL byte). */
924 if (rs->buf_size < what_they_get + 1)
926 rs->buf_size = 2 * what_they_get;
927 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
930 return what_they_get;
933 /* Update the size of a read/write packet. If they user wants
934 something really big then do a sanity check. */
937 set_memory_packet_size (char *args, struct memory_packet_config *config)
939 int fixed_p = config->fixed_p;
940 long size = config->size;
943 error (_("Argument required (integer, `fixed' or `limited')."));
944 else if (strcmp (args, "hard") == 0
945 || strcmp (args, "fixed") == 0)
947 else if (strcmp (args, "soft") == 0
948 || strcmp (args, "limit") == 0)
954 size = strtoul (args, &end, 0);
956 error (_("Invalid %s (bad syntax)."), config->name);
958 /* Instead of explicitly capping the size of a packet to
959 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
960 instead allowed to set the size to something arbitrarily
962 if (size > MAX_REMOTE_PACKET_SIZE)
963 error (_("Invalid %s (too large)."), config->name);
967 if (fixed_p && !config->fixed_p)
969 if (! query (_("The target may not be able to correctly handle a %s\n"
970 "of %ld bytes. Change the packet size? "),
972 error (_("Packet size not changed."));
974 /* Update the config. */
975 config->fixed_p = fixed_p;
980 show_memory_packet_size (struct memory_packet_config *config)
982 printf_filtered (_("The %s is %ld. "), config->name, config->size);
984 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
985 get_memory_packet_size (config));
987 printf_filtered (_("Packets are limited to %ld bytes.\n"),
988 get_memory_packet_size (config));
991 static struct memory_packet_config memory_write_packet_config =
993 "memory-write-packet-size",
997 set_memory_write_packet_size (char *args, int from_tty)
999 set_memory_packet_size (args, &memory_write_packet_config);
1003 show_memory_write_packet_size (char *args, int from_tty)
1005 show_memory_packet_size (&memory_write_packet_config);
1009 get_memory_write_packet_size (void)
1011 return get_memory_packet_size (&memory_write_packet_config);
1014 static struct memory_packet_config memory_read_packet_config =
1016 "memory-read-packet-size",
1020 set_memory_read_packet_size (char *args, int from_tty)
1022 set_memory_packet_size (args, &memory_read_packet_config);
1026 show_memory_read_packet_size (char *args, int from_tty)
1028 show_memory_packet_size (&memory_read_packet_config);
1032 get_memory_read_packet_size (void)
1034 long size = get_memory_packet_size (&memory_read_packet_config);
1036 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1037 extra buffer size argument before the memory read size can be
1038 increased beyond this. */
1039 if (size > get_remote_packet_size ())
1040 size = get_remote_packet_size ();
1045 /* Generic configuration support for packets the stub optionally
1046 supports. Allows the user to specify the use of the packet as well
1047 as allowing GDB to auto-detect support in the remote stub. */
1051 PACKET_SUPPORT_UNKNOWN = 0,
1056 struct packet_config
1061 /* If auto, GDB auto-detects support for this packet or feature,
1062 either through qSupported, or by trying the packet and looking
1063 at the response. If true, GDB assumes the target supports this
1064 packet. If false, the packet is disabled. Configs that don't
1065 have an associated command always have this set to auto. */
1066 enum auto_boolean detect;
1068 /* Does the target support this packet? */
1069 enum packet_support support;
1072 /* Analyze a packet's return value and update the packet config
1082 static enum packet_support packet_config_support (struct packet_config *config);
1083 static enum packet_support packet_support (int packet);
1086 show_packet_config_cmd (struct packet_config *config)
1088 char *support = "internal-error";
1090 switch (packet_config_support (config))
1093 support = "enabled";
1095 case PACKET_DISABLE:
1096 support = "disabled";
1098 case PACKET_SUPPORT_UNKNOWN:
1099 support = "unknown";
1102 switch (config->detect)
1104 case AUTO_BOOLEAN_AUTO:
1105 printf_filtered (_("Support for the `%s' packet "
1106 "is auto-detected, currently %s.\n"),
1107 config->name, support);
1109 case AUTO_BOOLEAN_TRUE:
1110 case AUTO_BOOLEAN_FALSE:
1111 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1112 config->name, support);
1118 add_packet_config_cmd (struct packet_config *config, const char *name,
1119 const char *title, int legacy)
1125 config->name = name;
1126 config->title = title;
1127 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1129 show_doc = xstrprintf ("Show current use of remote "
1130 "protocol `%s' (%s) packet",
1132 /* set/show TITLE-packet {auto,on,off} */
1133 cmd_name = xstrprintf ("%s-packet", title);
1134 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1135 &config->detect, set_doc,
1136 show_doc, NULL, /* help_doc */
1138 show_remote_protocol_packet_cmd,
1139 &remote_set_cmdlist, &remote_show_cmdlist);
1140 /* The command code copies the documentation strings. */
1143 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1148 legacy_name = xstrprintf ("%s-packet", name);
1149 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1150 &remote_set_cmdlist);
1151 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1152 &remote_show_cmdlist);
1156 static enum packet_result
1157 packet_check_result (const char *buf)
1161 /* The stub recognized the packet request. Check that the
1162 operation succeeded. */
1164 && isxdigit (buf[1]) && isxdigit (buf[2])
1166 /* "Enn" - definitly an error. */
1167 return PACKET_ERROR;
1169 /* Always treat "E." as an error. This will be used for
1170 more verbose error messages, such as E.memtypes. */
1171 if (buf[0] == 'E' && buf[1] == '.')
1172 return PACKET_ERROR;
1174 /* The packet may or may not be OK. Just assume it is. */
1178 /* The stub does not support the packet. */
1179 return PACKET_UNKNOWN;
1182 static enum packet_result
1183 packet_ok (const char *buf, struct packet_config *config)
1185 enum packet_result result;
1187 if (config->detect != AUTO_BOOLEAN_TRUE
1188 && config->support == PACKET_DISABLE)
1189 internal_error (__FILE__, __LINE__,
1190 _("packet_ok: attempt to use a disabled packet"));
1192 result = packet_check_result (buf);
1197 /* The stub recognized the packet request. */
1198 if (config->support == PACKET_SUPPORT_UNKNOWN)
1201 fprintf_unfiltered (gdb_stdlog,
1202 "Packet %s (%s) is supported\n",
1203 config->name, config->title);
1204 config->support = PACKET_ENABLE;
1207 case PACKET_UNKNOWN:
1208 /* The stub does not support the packet. */
1209 if (config->detect == AUTO_BOOLEAN_AUTO
1210 && config->support == PACKET_ENABLE)
1212 /* If the stub previously indicated that the packet was
1213 supported then there is a protocol error. */
1214 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1215 config->name, config->title);
1217 else if (config->detect == AUTO_BOOLEAN_TRUE)
1219 /* The user set it wrong. */
1220 error (_("Enabled packet %s (%s) not recognized by stub"),
1221 config->name, config->title);
1225 fprintf_unfiltered (gdb_stdlog,
1226 "Packet %s (%s) is NOT supported\n",
1227 config->name, config->title);
1228 config->support = PACKET_DISABLE;
1248 PACKET_vFile_pwrite,
1250 PACKET_vFile_unlink,
1251 PACKET_vFile_readlink,
1254 PACKET_qXfer_features,
1255 PACKET_qXfer_exec_file,
1256 PACKET_qXfer_libraries,
1257 PACKET_qXfer_libraries_svr4,
1258 PACKET_qXfer_memory_map,
1259 PACKET_qXfer_spu_read,
1260 PACKET_qXfer_spu_write,
1261 PACKET_qXfer_osdata,
1262 PACKET_qXfer_threads,
1263 PACKET_qXfer_statictrace_read,
1264 PACKET_qXfer_traceframe_info,
1270 PACKET_QPassSignals,
1271 PACKET_QProgramSignals,
1273 PACKET_qSearch_memory,
1276 PACKET_QStartNoAckMode,
1278 PACKET_qXfer_siginfo_read,
1279 PACKET_qXfer_siginfo_write,
1282 /* Support for conditional tracepoints. */
1283 PACKET_ConditionalTracepoints,
1285 /* Support for target-side breakpoint conditions. */
1286 PACKET_ConditionalBreakpoints,
1288 /* Support for target-side breakpoint commands. */
1289 PACKET_BreakpointCommands,
1291 /* Support for fast tracepoints. */
1292 PACKET_FastTracepoints,
1294 /* Support for static tracepoints. */
1295 PACKET_StaticTracepoints,
1297 /* Support for installing tracepoints while a trace experiment is
1299 PACKET_InstallInTrace,
1303 PACKET_TracepointSource,
1306 PACKET_QDisableRandomization,
1308 PACKET_QTBuffer_size,
1311 PACKET_qXfer_btrace,
1313 /* Support for the QNonStop packet. */
1316 /* Support for multi-process extensions. */
1317 PACKET_multiprocess_feature,
1319 /* Support for enabling and disabling tracepoints while a trace
1320 experiment is running. */
1321 PACKET_EnableDisableTracepoints_feature,
1323 /* Support for collecting strings using the tracenz bytecode. */
1324 PACKET_tracenz_feature,
1326 /* Support for continuing to run a trace experiment while GDB is
1328 PACKET_DisconnectedTracing_feature,
1330 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1331 PACKET_augmented_libraries_svr4_read_feature,
1333 /* Support for the qXfer:btrace-conf:read packet. */
1334 PACKET_qXfer_btrace_conf,
1336 /* Support for the Qbtrace-conf:bts:size packet. */
1337 PACKET_Qbtrace_conf_bts_size,
1339 /* Support for swbreak+ feature. */
1340 PACKET_swbreak_feature,
1342 /* Support for hwbreak+ feature. */
1343 PACKET_hwbreak_feature,
1348 static struct packet_config remote_protocol_packets[PACKET_MAX];
1350 /* Returns the packet's corresponding "set remote foo-packet" command
1351 state. See struct packet_config for more details. */
1353 static enum auto_boolean
1354 packet_set_cmd_state (int packet)
1356 return remote_protocol_packets[packet].detect;
1359 /* Returns whether a given packet or feature is supported. This takes
1360 into account the state of the corresponding "set remote foo-packet"
1361 command, which may be used to bypass auto-detection. */
1363 static enum packet_support
1364 packet_config_support (struct packet_config *config)
1366 switch (config->detect)
1368 case AUTO_BOOLEAN_TRUE:
1369 return PACKET_ENABLE;
1370 case AUTO_BOOLEAN_FALSE:
1371 return PACKET_DISABLE;
1372 case AUTO_BOOLEAN_AUTO:
1373 return config->support;
1375 gdb_assert_not_reached (_("bad switch"));
1379 /* Same as packet_config_support, but takes the packet's enum value as
1382 static enum packet_support
1383 packet_support (int packet)
1385 struct packet_config *config = &remote_protocol_packets[packet];
1387 return packet_config_support (config);
1391 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1392 struct cmd_list_element *c,
1395 struct packet_config *packet;
1397 for (packet = remote_protocol_packets;
1398 packet < &remote_protocol_packets[PACKET_MAX];
1401 if (&packet->detect == c->var)
1403 show_packet_config_cmd (packet);
1407 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1411 /* Should we try one of the 'Z' requests? */
1415 Z_PACKET_SOFTWARE_BP,
1416 Z_PACKET_HARDWARE_BP,
1423 /* For compatibility with older distributions. Provide a ``set remote
1424 Z-packet ...'' command that updates all the Z packet types. */
1426 static enum auto_boolean remote_Z_packet_detect;
1429 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1430 struct cmd_list_element *c)
1434 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1435 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1439 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1440 struct cmd_list_element *c,
1445 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1447 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1451 /* Returns true if the multi-process extensions are in effect. */
1454 remote_multi_process_p (struct remote_state *rs)
1456 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1459 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1460 static struct async_signal_handler *async_sigint_remote_twice_token;
1461 static struct async_signal_handler *async_sigint_remote_token;
1464 /* Asynchronous signal handle registered as event loop source for
1465 when we have pending events ready to be passed to the core. */
1467 static struct async_event_handler *remote_async_inferior_event_token;
1471 static ptid_t magic_null_ptid;
1472 static ptid_t not_sent_ptid;
1473 static ptid_t any_thread_ptid;
1475 /* Find out if the stub attached to PID (and hence GDB should offer to
1476 detach instead of killing it when bailing out). */
1479 remote_query_attached (int pid)
1481 struct remote_state *rs = get_remote_state ();
1482 size_t size = get_remote_packet_size ();
1484 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1487 if (remote_multi_process_p (rs))
1488 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1490 xsnprintf (rs->buf, size, "qAttached");
1493 getpkt (&rs->buf, &rs->buf_size, 0);
1495 switch (packet_ok (rs->buf,
1496 &remote_protocol_packets[PACKET_qAttached]))
1499 if (strcmp (rs->buf, "1") == 0)
1503 warning (_("Remote failure reply: %s"), rs->buf);
1505 case PACKET_UNKNOWN:
1512 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1513 has been invented by GDB, instead of reported by the target. Since
1514 we can be connected to a remote system before before knowing about
1515 any inferior, mark the target with execution when we find the first
1516 inferior. If ATTACHED is 1, then we had just attached to this
1517 inferior. If it is 0, then we just created this inferior. If it
1518 is -1, then try querying the remote stub to find out if it had
1519 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1520 attempt to open this inferior's executable as the main executable
1521 if no main executable is open already. */
1523 static struct inferior *
1524 remote_add_inferior (int fake_pid_p, int pid, int attached,
1527 struct inferior *inf;
1529 /* Check whether this process we're learning about is to be
1530 considered attached, or if is to be considered to have been
1531 spawned by the stub. */
1533 attached = remote_query_attached (pid);
1535 if (gdbarch_has_global_solist (target_gdbarch ()))
1537 /* If the target shares code across all inferiors, then every
1538 attach adds a new inferior. */
1539 inf = add_inferior (pid);
1541 /* ... and every inferior is bound to the same program space.
1542 However, each inferior may still have its own address
1544 inf->aspace = maybe_new_address_space ();
1545 inf->pspace = current_program_space;
1549 /* In the traditional debugging scenario, there's a 1-1 match
1550 between program/address spaces. We simply bind the inferior
1551 to the program space's address space. */
1552 inf = current_inferior ();
1553 inferior_appeared (inf, pid);
1556 inf->attach_flag = attached;
1557 inf->fake_pid_p = fake_pid_p;
1559 /* If no main executable is currently open then attempt to
1560 open the file that was executed to create this inferior. */
1561 if (try_open_exec && get_exec_file (0) == NULL)
1562 exec_file_locate_attach (pid, 1);
1567 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1568 according to RUNNING. */
1571 remote_add_thread (ptid_t ptid, int running)
1573 struct remote_state *rs = get_remote_state ();
1575 /* GDB historically didn't pull threads in the initial connection
1576 setup. If the remote target doesn't even have a concept of
1577 threads (e.g., a bare-metal target), even if internally we
1578 consider that a single-threaded target, mentioning a new thread
1579 might be confusing to the user. Be silent then, preserving the
1580 age old behavior. */
1581 if (rs->starting_up)
1582 add_thread_silent (ptid);
1586 set_executing (ptid, running);
1587 set_running (ptid, running);
1590 /* Come here when we learn about a thread id from the remote target.
1591 It may be the first time we hear about such thread, so take the
1592 opportunity to add it to GDB's thread list. In case this is the
1593 first time we're noticing its corresponding inferior, add it to
1594 GDB's inferior list as well. */
1597 remote_notice_new_inferior (ptid_t currthread, int running)
1599 /* If this is a new thread, add it to GDB's thread list.
1600 If we leave it up to WFI to do this, bad things will happen. */
1602 if (in_thread_list (currthread) && is_exited (currthread))
1604 /* We're seeing an event on a thread id we knew had exited.
1605 This has to be a new thread reusing the old id. Add it. */
1606 remote_add_thread (currthread, running);
1610 if (!in_thread_list (currthread))
1612 struct inferior *inf = NULL;
1613 int pid = ptid_get_pid (currthread);
1615 if (ptid_is_pid (inferior_ptid)
1616 && pid == ptid_get_pid (inferior_ptid))
1618 /* inferior_ptid has no thread member yet. This can happen
1619 with the vAttach -> remote_wait,"TAAthread:" path if the
1620 stub doesn't support qC. This is the first stop reported
1621 after an attach, so this is the main thread. Update the
1622 ptid in the thread list. */
1623 if (in_thread_list (pid_to_ptid (pid)))
1624 thread_change_ptid (inferior_ptid, currthread);
1627 remote_add_thread (currthread, running);
1628 inferior_ptid = currthread;
1633 if (ptid_equal (magic_null_ptid, inferior_ptid))
1635 /* inferior_ptid is not set yet. This can happen with the
1636 vRun -> remote_wait,"TAAthread:" path if the stub
1637 doesn't support qC. This is the first stop reported
1638 after an attach, so this is the main thread. Update the
1639 ptid in the thread list. */
1640 thread_change_ptid (inferior_ptid, currthread);
1644 /* When connecting to a target remote, or to a target
1645 extended-remote which already was debugging an inferior, we
1646 may not know about it yet. Add it before adding its child
1647 thread, so notifications are emitted in a sensible order. */
1648 if (!in_inferior_list (ptid_get_pid (currthread)))
1650 struct remote_state *rs = get_remote_state ();
1651 int fake_pid_p = !remote_multi_process_p (rs);
1653 inf = remote_add_inferior (fake_pid_p,
1654 ptid_get_pid (currthread), -1, 1);
1657 /* This is really a new thread. Add it. */
1658 remote_add_thread (currthread, running);
1660 /* If we found a new inferior, let the common code do whatever
1661 it needs to with it (e.g., read shared libraries, insert
1662 breakpoints), unless we're just setting up an all-stop
1666 struct remote_state *rs = get_remote_state ();
1668 if (non_stop || !rs->starting_up)
1669 notice_new_inferior (currthread, running, 0);
1674 /* Return the private thread data, creating it if necessary. */
1676 static struct private_thread_info *
1677 demand_private_info (ptid_t ptid)
1679 struct thread_info *info = find_thread_ptid (ptid);
1685 info->priv = xmalloc (sizeof (*(info->priv)));
1686 info->private_dtor = free_private_thread_info;
1687 info->priv->core = -1;
1688 info->priv->extra = 0;
1694 /* Call this function as a result of
1695 1) A halt indication (T packet) containing a thread id
1696 2) A direct query of currthread
1697 3) Successful execution of set thread */
1700 record_currthread (struct remote_state *rs, ptid_t currthread)
1702 rs->general_thread = currthread;
1705 /* If 'QPassSignals' is supported, tell the remote stub what signals
1706 it can simply pass through to the inferior without reporting. */
1709 remote_pass_signals (struct target_ops *self,
1710 int numsigs, unsigned char *pass_signals)
1712 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1714 char *pass_packet, *p;
1716 struct remote_state *rs = get_remote_state ();
1718 gdb_assert (numsigs < 256);
1719 for (i = 0; i < numsigs; i++)
1721 if (pass_signals[i])
1724 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1725 strcpy (pass_packet, "QPassSignals:");
1726 p = pass_packet + strlen (pass_packet);
1727 for (i = 0; i < numsigs; i++)
1729 if (pass_signals[i])
1732 *p++ = tohex (i >> 4);
1733 *p++ = tohex (i & 15);
1742 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1744 putpkt (pass_packet);
1745 getpkt (&rs->buf, &rs->buf_size, 0);
1746 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1747 if (rs->last_pass_packet)
1748 xfree (rs->last_pass_packet);
1749 rs->last_pass_packet = pass_packet;
1752 xfree (pass_packet);
1756 /* If 'QProgramSignals' is supported, tell the remote stub what
1757 signals it should pass through to the inferior when detaching. */
1760 remote_program_signals (struct target_ops *self,
1761 int numsigs, unsigned char *signals)
1763 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1767 struct remote_state *rs = get_remote_state ();
1769 gdb_assert (numsigs < 256);
1770 for (i = 0; i < numsigs; i++)
1775 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1776 strcpy (packet, "QProgramSignals:");
1777 p = packet + strlen (packet);
1778 for (i = 0; i < numsigs; i++)
1780 if (signal_pass_state (i))
1783 *p++ = tohex (i >> 4);
1784 *p++ = tohex (i & 15);
1793 if (!rs->last_program_signals_packet
1794 || strcmp (rs->last_program_signals_packet, packet) != 0)
1797 getpkt (&rs->buf, &rs->buf_size, 0);
1798 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1799 xfree (rs->last_program_signals_packet);
1800 rs->last_program_signals_packet = packet;
1807 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1808 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1809 thread. If GEN is set, set the general thread, if not, then set
1810 the step/continue thread. */
1812 set_thread (struct ptid ptid, int gen)
1814 struct remote_state *rs = get_remote_state ();
1815 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1816 char *buf = rs->buf;
1817 char *endbuf = rs->buf + get_remote_packet_size ();
1819 if (ptid_equal (state, ptid))
1823 *buf++ = gen ? 'g' : 'c';
1824 if (ptid_equal (ptid, magic_null_ptid))
1825 xsnprintf (buf, endbuf - buf, "0");
1826 else if (ptid_equal (ptid, any_thread_ptid))
1827 xsnprintf (buf, endbuf - buf, "0");
1828 else if (ptid_equal (ptid, minus_one_ptid))
1829 xsnprintf (buf, endbuf - buf, "-1");
1831 write_ptid (buf, endbuf, ptid);
1833 getpkt (&rs->buf, &rs->buf_size, 0);
1835 rs->general_thread = ptid;
1837 rs->continue_thread = ptid;
1841 set_general_thread (struct ptid ptid)
1843 set_thread (ptid, 1);
1847 set_continue_thread (struct ptid ptid)
1849 set_thread (ptid, 0);
1852 /* Change the remote current process. Which thread within the process
1853 ends up selected isn't important, as long as it is the same process
1854 as what INFERIOR_PTID points to.
1856 This comes from that fact that there is no explicit notion of
1857 "selected process" in the protocol. The selected process for
1858 general operations is the process the selected general thread
1862 set_general_process (void)
1864 struct remote_state *rs = get_remote_state ();
1866 /* If the remote can't handle multiple processes, don't bother. */
1867 if (!rs->extended || !remote_multi_process_p (rs))
1870 /* We only need to change the remote current thread if it's pointing
1871 at some other process. */
1872 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1873 set_general_thread (inferior_ptid);
1877 /* Return nonzero if this is the main thread that we made up ourselves
1878 to model non-threaded targets as single-threaded. */
1881 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1883 struct remote_state *rs = get_remote_state ();
1886 if (ptid_equal (ptid, magic_null_ptid))
1887 /* The main thread is always alive. */
1890 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
1891 /* The main thread is always alive. This can happen after a
1892 vAttach, if the remote side doesn't support
1899 /* Return nonzero if the thread PTID is still alive on the remote
1903 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1905 struct remote_state *rs = get_remote_state ();
1908 /* Check if this is a thread that we made up ourselves to model
1909 non-threaded targets as single-threaded. */
1910 if (remote_thread_always_alive (ops, ptid))
1914 endp = rs->buf + get_remote_packet_size ();
1917 write_ptid (p, endp, ptid);
1920 getpkt (&rs->buf, &rs->buf_size, 0);
1921 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1924 /* About these extended threadlist and threadinfo packets. They are
1925 variable length packets but, the fields within them are often fixed
1926 length. They are redundent enough to send over UDP as is the
1927 remote protocol in general. There is a matching unit test module
1930 /* WARNING: This threadref data structure comes from the remote O.S.,
1931 libstub protocol encoding, and remote.c. It is not particularly
1934 /* Right now, the internal structure is int. We want it to be bigger.
1935 Plan to fix this. */
1937 typedef int gdb_threadref; /* Internal GDB thread reference. */
1939 /* gdb_ext_thread_info is an internal GDB data structure which is
1940 equivalent to the reply of the remote threadinfo packet. */
1942 struct gdb_ext_thread_info
1944 threadref threadid; /* External form of thread reference. */
1945 int active; /* Has state interesting to GDB?
1947 char display[256]; /* Brief state display, name,
1948 blocked/suspended. */
1949 char shortname[32]; /* To be used to name threads. */
1950 char more_display[256]; /* Long info, statistics, queue depth,
1954 /* The volume of remote transfers can be limited by submitting
1955 a mask containing bits specifying the desired information.
1956 Use a union of these values as the 'selection' parameter to
1957 get_thread_info. FIXME: Make these TAG names more thread specific. */
1959 #define TAG_THREADID 1
1960 #define TAG_EXISTS 2
1961 #define TAG_DISPLAY 4
1962 #define TAG_THREADNAME 8
1963 #define TAG_MOREDISPLAY 16
1965 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1967 static char *unpack_nibble (char *buf, int *val);
1969 static char *unpack_byte (char *buf, int *value);
1971 static char *pack_int (char *buf, int value);
1973 static char *unpack_int (char *buf, int *value);
1975 static char *unpack_string (char *src, char *dest, int length);
1977 static char *pack_threadid (char *pkt, threadref *id);
1979 static char *unpack_threadid (char *inbuf, threadref *id);
1981 void int_to_threadref (threadref *id, int value);
1983 static int threadref_to_int (threadref *ref);
1985 static void copy_threadref (threadref *dest, threadref *src);
1987 static int threadmatch (threadref *dest, threadref *src);
1989 static char *pack_threadinfo_request (char *pkt, int mode,
1992 static int remote_unpack_thread_info_response (char *pkt,
1993 threadref *expectedref,
1994 struct gdb_ext_thread_info
1998 static int remote_get_threadinfo (threadref *threadid,
1999 int fieldset, /*TAG mask */
2000 struct gdb_ext_thread_info *info);
2002 static char *pack_threadlist_request (char *pkt, int startflag,
2004 threadref *nextthread);
2006 static int parse_threadlist_response (char *pkt,
2008 threadref *original_echo,
2009 threadref *resultlist,
2012 static int remote_get_threadlist (int startflag,
2013 threadref *nextthread,
2017 threadref *threadlist);
2019 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2021 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2022 void *context, int looplimit);
2024 static int remote_newthread_step (threadref *ref, void *context);
2027 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2028 buffer we're allowed to write to. Returns
2029 BUF+CHARACTERS_WRITTEN. */
2032 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2035 struct remote_state *rs = get_remote_state ();
2037 if (remote_multi_process_p (rs))
2039 pid = ptid_get_pid (ptid);
2041 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2043 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2045 tid = ptid_get_lwp (ptid);
2047 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2049 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2054 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2055 passed the last parsed char. Returns null_ptid on error. */
2058 read_ptid (char *buf, char **obuf)
2062 ULONGEST pid = 0, tid = 0;
2066 /* Multi-process ptid. */
2067 pp = unpack_varlen_hex (p + 1, &pid);
2069 error (_("invalid remote ptid: %s"), p);
2072 pp = unpack_varlen_hex (p + 1, &tid);
2075 return ptid_build (pid, tid, 0);
2078 /* No multi-process. Just a tid. */
2079 pp = unpack_varlen_hex (p, &tid);
2081 /* Since the stub is not sending a process id, then default to
2082 what's in inferior_ptid, unless it's null at this point. If so,
2083 then since there's no way to know the pid of the reported
2084 threads, use the magic number. */
2085 if (ptid_equal (inferior_ptid, null_ptid))
2086 pid = ptid_get_pid (magic_null_ptid);
2088 pid = ptid_get_pid (inferior_ptid);
2092 return ptid_build (pid, tid, 0);
2098 if (ch >= 'a' && ch <= 'f')
2099 return ch - 'a' + 10;
2100 if (ch >= '0' && ch <= '9')
2102 if (ch >= 'A' && ch <= 'F')
2103 return ch - 'A' + 10;
2108 stub_unpack_int (char *buff, int fieldlength)
2115 nibble = stubhex (*buff++);
2119 retval = retval << 4;
2125 unpack_nibble (char *buf, int *val)
2127 *val = fromhex (*buf++);
2132 unpack_byte (char *buf, int *value)
2134 *value = stub_unpack_int (buf, 2);
2139 pack_int (char *buf, int value)
2141 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2142 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2143 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2144 buf = pack_hex_byte (buf, (value & 0xff));
2149 unpack_int (char *buf, int *value)
2151 *value = stub_unpack_int (buf, 8);
2155 #if 0 /* Currently unused, uncomment when needed. */
2156 static char *pack_string (char *pkt, char *string);
2159 pack_string (char *pkt, char *string)
2164 len = strlen (string);
2166 len = 200; /* Bigger than most GDB packets, junk??? */
2167 pkt = pack_hex_byte (pkt, len);
2171 if ((ch == '\0') || (ch == '#'))
2172 ch = '*'; /* Protect encapsulation. */
2177 #endif /* 0 (unused) */
2180 unpack_string (char *src, char *dest, int length)
2189 pack_threadid (char *pkt, threadref *id)
2192 unsigned char *altid;
2194 altid = (unsigned char *) id;
2195 limit = pkt + BUF_THREAD_ID_SIZE;
2197 pkt = pack_hex_byte (pkt, *altid++);
2203 unpack_threadid (char *inbuf, threadref *id)
2206 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2209 altref = (char *) id;
2211 while (inbuf < limit)
2213 x = stubhex (*inbuf++);
2214 y = stubhex (*inbuf++);
2215 *altref++ = (x << 4) | y;
2220 /* Externally, threadrefs are 64 bits but internally, they are still
2221 ints. This is due to a mismatch of specifications. We would like
2222 to use 64bit thread references internally. This is an adapter
2226 int_to_threadref (threadref *id, int value)
2228 unsigned char *scan;
2230 scan = (unsigned char *) id;
2236 *scan++ = (value >> 24) & 0xff;
2237 *scan++ = (value >> 16) & 0xff;
2238 *scan++ = (value >> 8) & 0xff;
2239 *scan++ = (value & 0xff);
2243 threadref_to_int (threadref *ref)
2246 unsigned char *scan;
2252 value = (value << 8) | ((*scan++) & 0xff);
2257 copy_threadref (threadref *dest, threadref *src)
2260 unsigned char *csrc, *cdest;
2262 csrc = (unsigned char *) src;
2263 cdest = (unsigned char *) dest;
2270 threadmatch (threadref *dest, threadref *src)
2272 /* Things are broken right now, so just assume we got a match. */
2274 unsigned char *srcp, *destp;
2276 srcp = (char *) src;
2277 destp = (char *) dest;
2281 result &= (*srcp++ == *destp++) ? 1 : 0;
2288 threadid:1, # always request threadid
2295 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2298 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2300 *pkt++ = 'q'; /* Info Query */
2301 *pkt++ = 'P'; /* process or thread info */
2302 pkt = pack_int (pkt, mode); /* mode */
2303 pkt = pack_threadid (pkt, id); /* threadid */
2304 *pkt = '\0'; /* terminate */
2308 /* These values tag the fields in a thread info response packet. */
2309 /* Tagging the fields allows us to request specific fields and to
2310 add more fields as time goes by. */
2312 #define TAG_THREADID 1 /* Echo the thread identifier. */
2313 #define TAG_EXISTS 2 /* Is this process defined enough to
2314 fetch registers and its stack? */
2315 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2316 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2317 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2321 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2322 struct gdb_ext_thread_info *info)
2324 struct remote_state *rs = get_remote_state ();
2328 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2331 /* info->threadid = 0; FIXME: implement zero_threadref. */
2333 info->display[0] = '\0';
2334 info->shortname[0] = '\0';
2335 info->more_display[0] = '\0';
2337 /* Assume the characters indicating the packet type have been
2339 pkt = unpack_int (pkt, &mask); /* arg mask */
2340 pkt = unpack_threadid (pkt, &ref);
2343 warning (_("Incomplete response to threadinfo request."));
2344 if (!threadmatch (&ref, expectedref))
2345 { /* This is an answer to a different request. */
2346 warning (_("ERROR RMT Thread info mismatch."));
2349 copy_threadref (&info->threadid, &ref);
2351 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2353 /* Packets are terminated with nulls. */
2354 while ((pkt < limit) && mask && *pkt)
2356 pkt = unpack_int (pkt, &tag); /* tag */
2357 pkt = unpack_byte (pkt, &length); /* length */
2358 if (!(tag & mask)) /* Tags out of synch with mask. */
2360 warning (_("ERROR RMT: threadinfo tag mismatch."));
2364 if (tag == TAG_THREADID)
2368 warning (_("ERROR RMT: length of threadid is not 16."));
2372 pkt = unpack_threadid (pkt, &ref);
2373 mask = mask & ~TAG_THREADID;
2376 if (tag == TAG_EXISTS)
2378 info->active = stub_unpack_int (pkt, length);
2380 mask = mask & ~(TAG_EXISTS);
2383 warning (_("ERROR RMT: 'exists' length too long."));
2389 if (tag == TAG_THREADNAME)
2391 pkt = unpack_string (pkt, &info->shortname[0], length);
2392 mask = mask & ~TAG_THREADNAME;
2395 if (tag == TAG_DISPLAY)
2397 pkt = unpack_string (pkt, &info->display[0], length);
2398 mask = mask & ~TAG_DISPLAY;
2401 if (tag == TAG_MOREDISPLAY)
2403 pkt = unpack_string (pkt, &info->more_display[0], length);
2404 mask = mask & ~TAG_MOREDISPLAY;
2407 warning (_("ERROR RMT: unknown thread info tag."));
2408 break; /* Not a tag we know about. */
2414 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2415 struct gdb_ext_thread_info *info)
2417 struct remote_state *rs = get_remote_state ();
2420 pack_threadinfo_request (rs->buf, fieldset, threadid);
2422 getpkt (&rs->buf, &rs->buf_size, 0);
2424 if (rs->buf[0] == '\0')
2427 result = remote_unpack_thread_info_response (rs->buf + 2,
2432 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2435 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2436 threadref *nextthread)
2438 *pkt++ = 'q'; /* info query packet */
2439 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2440 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2441 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2442 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2447 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2450 parse_threadlist_response (char *pkt, int result_limit,
2451 threadref *original_echo, threadref *resultlist,
2454 struct remote_state *rs = get_remote_state ();
2456 int count, resultcount, done;
2459 /* Assume the 'q' and 'M chars have been stripped. */
2460 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2461 /* done parse past here */
2462 pkt = unpack_byte (pkt, &count); /* count field */
2463 pkt = unpack_nibble (pkt, &done);
2464 /* The first threadid is the argument threadid. */
2465 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2466 while ((count-- > 0) && (pkt < limit))
2468 pkt = unpack_threadid (pkt, resultlist++);
2469 if (resultcount++ >= result_limit)
2477 /* Fetch the next batch of threads from the remote. Returns -1 if the
2478 qL packet is not supported, 0 on error and 1 on success. */
2481 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2482 int *done, int *result_count, threadref *threadlist)
2484 struct remote_state *rs = get_remote_state ();
2487 /* Trancate result limit to be smaller than the packet size. */
2488 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2489 >= get_remote_packet_size ())
2490 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2492 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2494 getpkt (&rs->buf, &rs->buf_size, 0);
2495 if (*rs->buf == '\0')
2497 /* Packet not supported. */
2502 parse_threadlist_response (rs->buf + 2, result_limit,
2503 &rs->echo_nextthread, threadlist, done);
2505 if (!threadmatch (&rs->echo_nextthread, nextthread))
2507 /* FIXME: This is a good reason to drop the packet. */
2508 /* Possably, there is a duplicate response. */
2510 retransmit immediatly - race conditions
2511 retransmit after timeout - yes
2513 wait for packet, then exit
2515 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2516 return 0; /* I choose simply exiting. */
2518 if (*result_count <= 0)
2522 warning (_("RMT ERROR : failed to get remote thread list."));
2525 return result; /* break; */
2527 if (*result_count > result_limit)
2530 warning (_("RMT ERROR: threadlist response longer than requested."));
2536 /* Fetch the list of remote threads, with the qL packet, and call
2537 STEPFUNCTION for each thread found. Stops iterating and returns 1
2538 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2539 STEPFUNCTION returns false. If the packet is not supported,
2543 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2546 struct remote_state *rs = get_remote_state ();
2547 int done, i, result_count;
2555 if (loopcount++ > looplimit)
2558 warning (_("Remote fetch threadlist -infinite loop-."));
2561 result = remote_get_threadlist (startflag, &rs->nextthread,
2562 MAXTHREADLISTRESULTS,
2563 &done, &result_count,
2564 rs->resultthreadlist);
2567 /* Clear for later iterations. */
2569 /* Setup to resume next batch of thread references, set nextthread. */
2570 if (result_count >= 1)
2571 copy_threadref (&rs->nextthread,
2572 &rs->resultthreadlist[result_count - 1]);
2574 while (result_count--)
2576 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2586 /* A thread found on the remote target. */
2588 typedef struct thread_item
2590 /* The thread's PTID. */
2593 /* The thread's extra info. May be NULL. */
2596 /* The core the thread was running on. -1 if not known. */
2599 DEF_VEC_O(thread_item_t);
2601 /* Context passed around to the various methods listing remote
2602 threads. As new threads are found, they're added to the ITEMS
2605 struct threads_listing_context
2607 /* The threads found on the remote target. */
2608 VEC (thread_item_t) *items;
2611 /* Discard the contents of the constructed thread listing context. */
2614 clear_threads_listing_context (void *p)
2616 struct threads_listing_context *context = p;
2618 struct thread_item *item;
2620 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2621 xfree (item->extra);
2623 VEC_free (thread_item_t, context->items);
2627 remote_newthread_step (threadref *ref, void *data)
2629 struct threads_listing_context *context = data;
2630 struct thread_item item;
2631 int pid = ptid_get_pid (inferior_ptid);
2633 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2637 VEC_safe_push (thread_item_t, context->items, &item);
2639 return 1; /* continue iterator */
2642 #define CRAZY_MAX_THREADS 1000
2645 remote_current_thread (ptid_t oldpid)
2647 struct remote_state *rs = get_remote_state ();
2650 getpkt (&rs->buf, &rs->buf_size, 0);
2651 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2652 return read_ptid (&rs->buf[2], NULL);
2657 /* List remote threads using the deprecated qL packet. */
2660 remote_get_threads_with_ql (struct target_ops *ops,
2661 struct threads_listing_context *context)
2663 if (remote_threadlist_iterator (remote_newthread_step, context,
2664 CRAZY_MAX_THREADS) >= 0)
2670 #if defined(HAVE_LIBEXPAT)
2673 start_thread (struct gdb_xml_parser *parser,
2674 const struct gdb_xml_element *element,
2675 void *user_data, VEC(gdb_xml_value_s) *attributes)
2677 struct threads_listing_context *data = user_data;
2679 struct thread_item item;
2681 struct gdb_xml_value *attr;
2683 id = xml_find_attribute (attributes, "id")->value;
2684 item.ptid = read_ptid (id, NULL);
2686 attr = xml_find_attribute (attributes, "core");
2688 item.core = *(ULONGEST *) attr->value;
2694 VEC_safe_push (thread_item_t, data->items, &item);
2698 end_thread (struct gdb_xml_parser *parser,
2699 const struct gdb_xml_element *element,
2700 void *user_data, const char *body_text)
2702 struct threads_listing_context *data = user_data;
2704 if (body_text && *body_text)
2705 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2708 const struct gdb_xml_attribute thread_attributes[] = {
2709 { "id", GDB_XML_AF_NONE, NULL, NULL },
2710 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2711 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2714 const struct gdb_xml_element thread_children[] = {
2715 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2718 const struct gdb_xml_element threads_children[] = {
2719 { "thread", thread_attributes, thread_children,
2720 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2721 start_thread, end_thread },
2722 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2725 const struct gdb_xml_element threads_elements[] = {
2726 { "threads", NULL, threads_children,
2727 GDB_XML_EF_NONE, NULL, NULL },
2728 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2733 /* List remote threads using qXfer:threads:read. */
2736 remote_get_threads_with_qxfer (struct target_ops *ops,
2737 struct threads_listing_context *context)
2739 #if defined(HAVE_LIBEXPAT)
2740 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2742 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2743 struct cleanup *back_to = make_cleanup (xfree, xml);
2745 if (xml != NULL && *xml != '\0')
2747 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2748 threads_elements, xml, context);
2751 do_cleanups (back_to);
2759 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2762 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2763 struct threads_listing_context *context)
2765 struct remote_state *rs = get_remote_state ();
2767 if (rs->use_threadinfo_query)
2771 putpkt ("qfThreadInfo");
2772 getpkt (&rs->buf, &rs->buf_size, 0);
2774 if (bufp[0] != '\0') /* q packet recognized */
2776 while (*bufp++ == 'm') /* reply contains one or more TID */
2780 struct thread_item item;
2782 item.ptid = read_ptid (bufp, &bufp);
2786 VEC_safe_push (thread_item_t, context->items, &item);
2788 while (*bufp++ == ','); /* comma-separated list */
2789 putpkt ("qsThreadInfo");
2790 getpkt (&rs->buf, &rs->buf_size, 0);
2797 /* Packet not recognized. */
2798 rs->use_threadinfo_query = 0;
2805 /* Implement the to_update_thread_list function for the remote
2809 remote_update_thread_list (struct target_ops *ops)
2811 struct remote_state *rs = get_remote_state ();
2812 struct threads_listing_context context;
2813 struct cleanup *old_chain;
2816 context.items = NULL;
2817 old_chain = make_cleanup (clear_threads_listing_context, &context);
2819 /* We have a few different mechanisms to fetch the thread list. Try
2820 them all, starting with the most preferred one first, falling
2821 back to older methods. */
2822 if (remote_get_threads_with_qxfer (ops, &context)
2823 || remote_get_threads_with_qthreadinfo (ops, &context)
2824 || remote_get_threads_with_ql (ops, &context))
2827 struct thread_item *item;
2828 struct thread_info *tp, *tmp;
2832 if (VEC_empty (thread_item_t, context.items)
2833 && remote_thread_always_alive (ops, inferior_ptid))
2835 /* Some targets don't really support threads, but still
2836 reply an (empty) thread list in response to the thread
2837 listing packets, instead of replying "packet not
2838 supported". Exit early so we don't delete the main
2840 do_cleanups (old_chain);
2844 /* CONTEXT now holds the current thread list on the remote
2845 target end. Delete GDB-side threads no longer found on the
2847 ALL_THREADS_SAFE (tp, tmp)
2850 VEC_iterate (thread_item_t, context.items, i, item);
2853 if (ptid_equal (item->ptid, tp->ptid))
2857 if (i == VEC_length (thread_item_t, context.items))
2860 delete_thread (tp->ptid);
2864 /* And now add threads we don't know about yet to our list. */
2866 VEC_iterate (thread_item_t, context.items, i, item);
2869 if (!ptid_equal (item->ptid, null_ptid))
2871 struct private_thread_info *info;
2872 /* In non-stop mode, we assume new found threads are
2873 running until proven otherwise with a stop reply. In
2874 all-stop, we can only get here if all threads are
2876 int running = non_stop ? 1 : 0;
2878 remote_notice_new_inferior (item->ptid, running);
2880 info = demand_private_info (item->ptid);
2881 info->core = item->core;
2882 info->extra = item->extra;
2890 /* If no thread listing method is supported, then query whether
2891 each known thread is alive, one by one, with the T packet.
2892 If the target doesn't support threads at all, then this is a
2893 no-op. See remote_thread_alive. */
2897 do_cleanups (old_chain);
2901 * Collect a descriptive string about the given thread.
2902 * The target may say anything it wants to about the thread
2903 * (typically info about its blocked / runnable state, name, etc.).
2904 * This string will appear in the info threads display.
2906 * Optional: targets are not required to implement this function.
2910 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
2912 struct remote_state *rs = get_remote_state ();
2916 struct gdb_ext_thread_info threadinfo;
2917 static char display_buf[100]; /* arbitrary... */
2918 int n = 0; /* position in display_buf */
2920 if (rs->remote_desc == 0) /* paranoia */
2921 internal_error (__FILE__, __LINE__,
2922 _("remote_threads_extra_info"));
2924 if (ptid_equal (tp->ptid, magic_null_ptid)
2925 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
2926 /* This is the main thread which was added by GDB. The remote
2927 server doesn't know about it. */
2930 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2932 struct thread_info *info = find_thread_ptid (tp->ptid);
2934 if (info && info->priv)
2935 return info->priv->extra;
2940 if (rs->use_threadextra_query)
2943 char *endb = rs->buf + get_remote_packet_size ();
2945 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2947 write_ptid (b, endb, tp->ptid);
2950 getpkt (&rs->buf, &rs->buf_size, 0);
2951 if (rs->buf[0] != 0)
2953 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2954 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2955 display_buf [result] = '\0';
2960 /* If the above query fails, fall back to the old method. */
2961 rs->use_threadextra_query = 0;
2962 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2963 | TAG_MOREDISPLAY | TAG_DISPLAY;
2964 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
2965 if (remote_get_threadinfo (&id, set, &threadinfo))
2966 if (threadinfo.active)
2968 if (*threadinfo.shortname)
2969 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2970 " Name: %s,", threadinfo.shortname);
2971 if (*threadinfo.display)
2972 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2973 " State: %s,", threadinfo.display);
2974 if (*threadinfo.more_display)
2975 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2976 " Priority: %s", threadinfo.more_display);
2980 /* For purely cosmetic reasons, clear up trailing commas. */
2981 if (',' == display_buf[n-1])
2982 display_buf[n-1] = ' ';
2991 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
2992 struct static_tracepoint_marker *marker)
2994 struct remote_state *rs = get_remote_state ();
2997 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2999 p += hexnumstr (p, addr);
3001 getpkt (&rs->buf, &rs->buf_size, 0);
3005 error (_("Remote failure reply: %s"), p);
3009 parse_static_tracepoint_marker_definition (p, &p, marker);
3016 static VEC(static_tracepoint_marker_p) *
3017 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3020 struct remote_state *rs = get_remote_state ();
3021 VEC(static_tracepoint_marker_p) *markers = NULL;
3022 struct static_tracepoint_marker *marker = NULL;
3023 struct cleanup *old_chain;
3026 /* Ask for a first packet of static tracepoint marker
3029 getpkt (&rs->buf, &rs->buf_size, 0);
3032 error (_("Remote failure reply: %s"), p);
3034 old_chain = make_cleanup (free_current_marker, &marker);
3039 marker = XCNEW (struct static_tracepoint_marker);
3043 parse_static_tracepoint_marker_definition (p, &p, marker);
3045 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3047 VEC_safe_push (static_tracepoint_marker_p,
3053 release_static_tracepoint_marker (marker);
3054 memset (marker, 0, sizeof (*marker));
3057 while (*p++ == ','); /* comma-separated list */
3058 /* Ask for another packet of static tracepoint definition. */
3060 getpkt (&rs->buf, &rs->buf_size, 0);
3064 do_cleanups (old_chain);
3069 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3072 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3074 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3078 /* Restart the remote side; this is an extended protocol operation. */
3081 extended_remote_restart (void)
3083 struct remote_state *rs = get_remote_state ();
3085 /* Send the restart command; for reasons I don't understand the
3086 remote side really expects a number after the "R". */
3087 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3090 remote_fileio_reset ();
3093 /* Clean up connection to a remote debugger. */
3096 remote_close (struct target_ops *self)
3098 struct remote_state *rs = get_remote_state ();
3100 if (rs->remote_desc == NULL)
3101 return; /* already closed */
3103 /* Make sure we leave stdin registered in the event loop, and we
3104 don't leave the async SIGINT signal handler installed. */
3105 remote_terminal_ours (self);
3107 serial_close (rs->remote_desc);
3108 rs->remote_desc = NULL;
3110 /* We don't have a connection to the remote stub anymore. Get rid
3111 of all the inferiors and their threads we were controlling.
3112 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3113 will be unable to find the thread corresponding to (pid, 0, 0). */
3114 inferior_ptid = null_ptid;
3115 discard_all_inferiors ();
3117 /* We are closing the remote target, so we should discard
3118 everything of this target. */
3119 discard_pending_stop_replies_in_queue (rs);
3121 if (remote_async_inferior_event_token)
3122 delete_async_event_handler (&remote_async_inferior_event_token);
3124 remote_notif_state_xfree (rs->notif_state);
3126 trace_reset_local_state ();
3129 /* Query the remote side for the text, data and bss offsets. */
3134 struct remote_state *rs = get_remote_state ();
3137 int lose, num_segments = 0, do_sections, do_segments;
3138 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3139 struct section_offsets *offs;
3140 struct symfile_segment_data *data;
3142 if (symfile_objfile == NULL)
3145 putpkt ("qOffsets");
3146 getpkt (&rs->buf, &rs->buf_size, 0);
3149 if (buf[0] == '\000')
3150 return; /* Return silently. Stub doesn't support
3154 warning (_("Remote failure reply: %s"), buf);
3158 /* Pick up each field in turn. This used to be done with scanf, but
3159 scanf will make trouble if CORE_ADDR size doesn't match
3160 conversion directives correctly. The following code will work
3161 with any size of CORE_ADDR. */
3162 text_addr = data_addr = bss_addr = 0;
3166 if (startswith (ptr, "Text="))
3169 /* Don't use strtol, could lose on big values. */
3170 while (*ptr && *ptr != ';')
3171 text_addr = (text_addr << 4) + fromhex (*ptr++);
3173 if (startswith (ptr, ";Data="))
3176 while (*ptr && *ptr != ';')
3177 data_addr = (data_addr << 4) + fromhex (*ptr++);
3182 if (!lose && startswith (ptr, ";Bss="))
3185 while (*ptr && *ptr != ';')
3186 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3188 if (bss_addr != data_addr)
3189 warning (_("Target reported unsupported offsets: %s"), buf);
3194 else if (startswith (ptr, "TextSeg="))
3197 /* Don't use strtol, could lose on big values. */
3198 while (*ptr && *ptr != ';')
3199 text_addr = (text_addr << 4) + fromhex (*ptr++);
3202 if (startswith (ptr, ";DataSeg="))
3205 while (*ptr && *ptr != ';')
3206 data_addr = (data_addr << 4) + fromhex (*ptr++);
3214 error (_("Malformed response to offset query, %s"), buf);
3215 else if (*ptr != '\0')
3216 warning (_("Target reported unsupported offsets: %s"), buf);
3218 offs = ((struct section_offsets *)
3219 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3220 memcpy (offs, symfile_objfile->section_offsets,
3221 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3223 data = get_symfile_segment_data (symfile_objfile->obfd);
3224 do_segments = (data != NULL);
3225 do_sections = num_segments == 0;
3227 if (num_segments > 0)
3229 segments[0] = text_addr;
3230 segments[1] = data_addr;
3232 /* If we have two segments, we can still try to relocate everything
3233 by assuming that the .text and .data offsets apply to the whole
3234 text and data segments. Convert the offsets given in the packet
3235 to base addresses for symfile_map_offsets_to_segments. */
3236 else if (data && data->num_segments == 2)
3238 segments[0] = data->segment_bases[0] + text_addr;
3239 segments[1] = data->segment_bases[1] + data_addr;
3242 /* If the object file has only one segment, assume that it is text
3243 rather than data; main programs with no writable data are rare,
3244 but programs with no code are useless. Of course the code might
3245 have ended up in the data segment... to detect that we would need
3246 the permissions here. */
3247 else if (data && data->num_segments == 1)
3249 segments[0] = data->segment_bases[0] + text_addr;
3252 /* There's no way to relocate by segment. */
3258 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3259 offs, num_segments, segments);
3261 if (ret == 0 && !do_sections)
3262 error (_("Can not handle qOffsets TextSeg "
3263 "response with this symbol file"));
3270 free_symfile_segment_data (data);
3274 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3276 /* This is a temporary kludge to force data and bss to use the
3277 same offsets because that's what nlmconv does now. The real
3278 solution requires changes to the stub and remote.c that I
3279 don't have time to do right now. */
3281 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3282 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3285 objfile_relocate (symfile_objfile, offs);
3288 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3289 threads we know are stopped already. This is used during the
3290 initial remote connection in non-stop mode --- threads that are
3291 reported as already being stopped are left stopped. */
3294 set_stop_requested_callback (struct thread_info *thread, void *data)
3296 /* If we have a stop reply for this thread, it must be stopped. */
3297 if (peek_stop_reply (thread->ptid))
3298 set_stop_requested (thread->ptid, 1);
3303 /* Send interrupt_sequence to remote target. */
3305 send_interrupt_sequence (void)
3307 struct remote_state *rs = get_remote_state ();
3309 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3310 remote_serial_write ("\x03", 1);
3311 else if (interrupt_sequence_mode == interrupt_sequence_break)
3312 serial_send_break (rs->remote_desc);
3313 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3315 serial_send_break (rs->remote_desc);
3316 remote_serial_write ("g", 1);
3319 internal_error (__FILE__, __LINE__,
3320 _("Invalid value for interrupt_sequence_mode: %s."),
3321 interrupt_sequence_mode);
3325 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3326 and extract the PTID. Returns NULL_PTID if not found. */
3329 stop_reply_extract_thread (char *stop_reply)
3331 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3335 /* Txx r:val ; r:val (...) */
3338 /* Look for "register" named "thread". */
3343 p1 = strchr (p, ':');
3347 if (strncmp (p, "thread", p1 - p) == 0)
3348 return read_ptid (++p1, &p);
3350 p1 = strchr (p, ';');
3362 /* Determine the remote side's current thread. If we have a stop
3363 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3364 "thread" register we can extract the current thread from. If not,
3365 ask the remote which is the current thread with qC. The former
3366 method avoids a roundtrip. */
3369 get_current_thread (char *wait_status)
3373 /* Note we don't use remote_parse_stop_reply as that makes use of
3374 the target architecture, which we haven't yet fully determined at
3376 if (wait_status != NULL)
3377 ptid = stop_reply_extract_thread (wait_status);
3378 if (ptid_equal (ptid, null_ptid))
3379 ptid = remote_current_thread (inferior_ptid);
3384 /* Query the remote target for which is the current thread/process,
3385 add it to our tables, and update INFERIOR_PTID. The caller is
3386 responsible for setting the state such that the remote end is ready
3387 to return the current thread.
3389 This function is called after handling the '?' or 'vRun' packets,
3390 whose response is a stop reply from which we can also try
3391 extracting the thread. If the target doesn't support the explicit
3392 qC query, we infer the current thread from that stop reply, passed
3393 in in WAIT_STATUS, which may be NULL. */
3396 add_current_inferior_and_thread (char *wait_status)
3398 struct remote_state *rs = get_remote_state ();
3400 ptid_t ptid = null_ptid;
3402 inferior_ptid = null_ptid;
3404 /* Now, if we have thread information, update inferior_ptid. */
3405 ptid = get_current_thread (wait_status);
3407 if (!ptid_equal (ptid, null_ptid))
3409 if (!remote_multi_process_p (rs))
3412 inferior_ptid = ptid;
3416 /* Without this, some commands which require an active target
3417 (such as kill) won't work. This variable serves (at least)
3418 double duty as both the pid of the target process (if it has
3419 such), and as a flag indicating that a target is active. */
3420 inferior_ptid = magic_null_ptid;
3424 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3426 /* Add the main thread. */
3427 add_thread_silent (inferior_ptid);
3431 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3433 struct remote_state *rs = get_remote_state ();
3434 struct packet_config *noack_config;
3435 char *wait_status = NULL;
3437 immediate_quit++; /* Allow user to interrupt it. */
3440 if (interrupt_on_connect)
3441 send_interrupt_sequence ();
3443 /* Ack any packet which the remote side has already sent. */
3444 serial_write (rs->remote_desc, "+", 1);
3446 /* Signal other parts that we're going through the initial setup,
3447 and so things may not be stable yet. */
3448 rs->starting_up = 1;
3450 /* The first packet we send to the target is the optional "supported
3451 packets" request. If the target can answer this, it will tell us
3452 which later probes to skip. */
3453 remote_query_supported ();
3455 /* If the stub wants to get a QAllow, compose one and send it. */
3456 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3457 remote_set_permissions (target);
3459 /* Next, we possibly activate noack mode.
3461 If the QStartNoAckMode packet configuration is set to AUTO,
3462 enable noack mode if the stub reported a wish for it with
3465 If set to TRUE, then enable noack mode even if the stub didn't
3466 report it in qSupported. If the stub doesn't reply OK, the
3467 session ends with an error.
3469 If FALSE, then don't activate noack mode, regardless of what the
3470 stub claimed should be the default with qSupported. */
3472 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3473 if (packet_config_support (noack_config) != PACKET_DISABLE)
3475 putpkt ("QStartNoAckMode");
3476 getpkt (&rs->buf, &rs->buf_size, 0);
3477 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3483 /* Tell the remote that we are using the extended protocol. */
3485 getpkt (&rs->buf, &rs->buf_size, 0);
3488 /* Let the target know which signals it is allowed to pass down to
3490 update_signals_program_target ();
3492 /* Next, if the target can specify a description, read it. We do
3493 this before anything involving memory or registers. */
3494 target_find_description ();
3496 /* Next, now that we know something about the target, update the
3497 address spaces in the program spaces. */
3498 update_address_spaces ();
3500 /* On OSs where the list of libraries is global to all
3501 processes, we fetch them early. */
3502 if (gdbarch_has_global_solist (target_gdbarch ()))
3503 solib_add (NULL, from_tty, target, auto_solib_add);
3507 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3508 error (_("Non-stop mode requested, but remote "
3509 "does not support non-stop"));
3511 putpkt ("QNonStop:1");
3512 getpkt (&rs->buf, &rs->buf_size, 0);
3514 if (strcmp (rs->buf, "OK") != 0)
3515 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3517 /* Find about threads and processes the stub is already
3518 controlling. We default to adding them in the running state.
3519 The '?' query below will then tell us about which threads are
3521 remote_update_thread_list (target);
3523 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3525 /* Don't assume that the stub can operate in all-stop mode.
3526 Request it explicitly. */
3527 putpkt ("QNonStop:0");
3528 getpkt (&rs->buf, &rs->buf_size, 0);
3530 if (strcmp (rs->buf, "OK") != 0)
3531 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3534 /* Upload TSVs regardless of whether the target is running or not. The
3535 remote stub, such as GDBserver, may have some predefined or builtin
3536 TSVs, even if the target is not running. */
3537 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3539 struct uploaded_tsv *uploaded_tsvs = NULL;
3541 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3542 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3545 /* Check whether the target is running now. */
3547 getpkt (&rs->buf, &rs->buf_size, 0);
3553 struct inferior *inf;
3555 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3558 error (_("The target is not running (try extended-remote?)"));
3560 /* We're connected, but not running. Drop out before we
3561 call start_remote. */
3562 rs->starting_up = 0;
3567 /* Save the reply for later. */
3568 wait_status = alloca (strlen (rs->buf) + 1);
3569 strcpy (wait_status, rs->buf);
3572 /* Fetch thread list. */
3573 target_update_thread_list ();
3575 /* Let the stub know that we want it to return the thread. */
3576 set_continue_thread (minus_one_ptid);
3578 if (thread_count () == 0)
3580 /* Target has no concept of threads at all. GDB treats
3581 non-threaded target as single-threaded; add a main
3583 add_current_inferior_and_thread (wait_status);
3587 /* We have thread information; select the thread the target
3588 says should be current. If we're reconnecting to a
3589 multi-threaded program, this will ideally be the thread
3590 that last reported an event before GDB disconnected. */
3591 inferior_ptid = get_current_thread (wait_status);
3592 if (ptid_equal (inferior_ptid, null_ptid))
3594 /* Odd... The target was able to list threads, but not
3595 tell us which thread was current (no "thread"
3596 register in T stop reply?). Just pick the first
3597 thread in the thread list then. */
3598 inferior_ptid = thread_list->ptid;
3602 /* init_wait_for_inferior should be called before get_offsets in order
3603 to manage `inserted' flag in bp loc in a correct state.
3604 breakpoint_init_inferior, called from init_wait_for_inferior, set
3605 `inserted' flag to 0, while before breakpoint_re_set, called from
3606 start_remote, set `inserted' flag to 1. In the initialization of
3607 inferior, breakpoint_init_inferior should be called first, and then
3608 breakpoint_re_set can be called. If this order is broken, state of
3609 `inserted' flag is wrong, and cause some problems on breakpoint
3611 init_wait_for_inferior ();
3613 get_offsets (); /* Get text, data & bss offsets. */
3615 /* If we could not find a description using qXfer, and we know
3616 how to do it some other way, try again. This is not
3617 supported for non-stop; it could be, but it is tricky if
3618 there are no stopped threads when we connect. */
3619 if (remote_read_description_p (target)
3620 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3622 target_clear_description ();
3623 target_find_description ();
3626 /* Use the previously fetched status. */
3627 gdb_assert (wait_status != NULL);
3628 strcpy (rs->buf, wait_status);
3629 rs->cached_wait_status = 1;
3632 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3636 /* Clear WFI global state. Do this before finding about new
3637 threads and inferiors, and setting the current inferior.
3638 Otherwise we would clear the proceed status of the current
3639 inferior when we want its stop_soon state to be preserved
3640 (see notice_new_inferior). */
3641 init_wait_for_inferior ();
3643 /* In non-stop, we will either get an "OK", meaning that there
3644 are no stopped threads at this time; or, a regular stop
3645 reply. In the latter case, there may be more than one thread
3646 stopped --- we pull them all out using the vStopped
3648 if (strcmp (rs->buf, "OK") != 0)
3650 struct notif_client *notif = ¬if_client_stop;
3652 /* remote_notif_get_pending_replies acks this one, and gets
3654 rs->notif_state->pending_event[notif_client_stop.id]
3655 = remote_notif_parse (notif, rs->buf);
3656 remote_notif_get_pending_events (notif);
3658 /* Make sure that threads that were stopped remain
3660 iterate_over_threads (set_stop_requested_callback, NULL);
3663 if (target_can_async_p ())
3666 if (thread_count () == 0)
3669 error (_("The target is not running (try extended-remote?)"));
3671 /* We're connected, but not running. Drop out before we
3672 call start_remote. */
3673 rs->starting_up = 0;
3677 /* Let the stub know that we want it to return the thread. */
3679 /* Force the stub to choose a thread. */
3680 set_general_thread (null_ptid);
3683 inferior_ptid = remote_current_thread (minus_one_ptid);
3684 if (ptid_equal (inferior_ptid, minus_one_ptid))
3685 error (_("remote didn't report the current thread in non-stop mode"));
3687 get_offsets (); /* Get text, data & bss offsets. */
3689 /* In non-stop mode, any cached wait status will be stored in
3690 the stop reply queue. */
3691 gdb_assert (wait_status == NULL);
3693 /* Report all signals during attach/startup. */
3694 remote_pass_signals (target, 0, NULL);
3697 /* If we connected to a live target, do some additional setup. */
3698 if (target_has_execution)
3700 if (symfile_objfile) /* No use without a symbol-file. */
3701 remote_check_symbols ();
3704 /* Possibly the target has been engaged in a trace run started
3705 previously; find out where things are at. */
3706 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3708 struct uploaded_tp *uploaded_tps = NULL;
3710 if (current_trace_status ()->running)
3711 printf_filtered (_("Trace is already running on the target.\n"));
3713 remote_upload_tracepoints (target, &uploaded_tps);
3715 merge_uploaded_tracepoints (&uploaded_tps);
3718 /* The thread and inferior lists are now synchronized with the
3719 target, our symbols have been relocated, and we're merged the
3720 target's tracepoints with ours. We're done with basic start
3722 rs->starting_up = 0;
3724 /* Maybe breakpoints are global and need to be inserted now. */
3725 if (breakpoints_should_be_inserted_now ())
3726 insert_breakpoints ();
3729 /* Open a connection to a remote debugger.
3730 NAME is the filename used for communication. */
3733 remote_open (const char *name, int from_tty)
3735 remote_open_1 (name, from_tty, &remote_ops, 0);
3738 /* Open a connection to a remote debugger using the extended
3739 remote gdb protocol. NAME is the filename used for communication. */
3742 extended_remote_open (const char *name, int from_tty)
3744 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3747 /* Reset all packets back to "unknown support". Called when opening a
3748 new connection to a remote target. */
3751 reset_all_packet_configs_support (void)
3755 for (i = 0; i < PACKET_MAX; i++)
3756 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3759 /* Initialize all packet configs. */
3762 init_all_packet_configs (void)
3766 for (i = 0; i < PACKET_MAX; i++)
3768 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3769 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3773 /* Symbol look-up. */
3776 remote_check_symbols (void)
3778 struct remote_state *rs = get_remote_state ();
3779 char *msg, *reply, *tmp;
3780 struct bound_minimal_symbol sym;
3783 /* The remote side has no concept of inferiors that aren't running
3784 yet, it only knows about running processes. If we're connected
3785 but our current inferior is not running, we should not invite the
3786 remote target to request symbol lookups related to its
3787 (unrelated) current process. */
3788 if (!target_has_execution)
3791 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3794 /* Make sure the remote is pointing at the right process. Note
3795 there's no way to select "no process". */
3796 set_general_process ();
3798 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3799 because we need both at the same time. */
3800 msg = alloca (get_remote_packet_size ());
3802 /* Invite target to request symbol lookups. */
3804 putpkt ("qSymbol::");
3805 getpkt (&rs->buf, &rs->buf_size, 0);
3806 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3809 while (startswith (reply, "qSymbol:"))
3811 struct bound_minimal_symbol sym;
3814 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3816 sym = lookup_minimal_symbol (msg, NULL, NULL);
3817 if (sym.minsym == NULL)
3818 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3821 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3822 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
3824 /* If this is a function address, return the start of code
3825 instead of any data function descriptor. */
3826 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3830 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3831 phex_nz (sym_addr, addr_size), &reply[8]);
3835 getpkt (&rs->buf, &rs->buf_size, 0);
3840 static struct serial *
3841 remote_serial_open (const char *name)
3843 static int udp_warning = 0;
3845 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3846 of in ser-tcp.c, because it is the remote protocol assuming that the
3847 serial connection is reliable and not the serial connection promising
3849 if (!udp_warning && startswith (name, "udp:"))
3851 warning (_("The remote protocol may be unreliable over UDP.\n"
3852 "Some events may be lost, rendering further debugging "
3857 return serial_open (name);
3860 /* Inform the target of our permission settings. The permission flags
3861 work without this, but if the target knows the settings, it can do
3862 a couple things. First, it can add its own check, to catch cases
3863 that somehow manage to get by the permissions checks in target
3864 methods. Second, if the target is wired to disallow particular
3865 settings (for instance, a system in the field that is not set up to
3866 be able to stop at a breakpoint), it can object to any unavailable
3870 remote_set_permissions (struct target_ops *self)
3872 struct remote_state *rs = get_remote_state ();
3874 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3875 "WriteReg:%x;WriteMem:%x;"
3876 "InsertBreak:%x;InsertTrace:%x;"
3877 "InsertFastTrace:%x;Stop:%x",
3878 may_write_registers, may_write_memory,
3879 may_insert_breakpoints, may_insert_tracepoints,
3880 may_insert_fast_tracepoints, may_stop);
3882 getpkt (&rs->buf, &rs->buf_size, 0);
3884 /* If the target didn't like the packet, warn the user. Do not try
3885 to undo the user's settings, that would just be maddening. */
3886 if (strcmp (rs->buf, "OK") != 0)
3887 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3890 /* This type describes each known response to the qSupported
3892 struct protocol_feature
3894 /* The name of this protocol feature. */
3897 /* The default for this protocol feature. */
3898 enum packet_support default_support;
3900 /* The function to call when this feature is reported, or after
3901 qSupported processing if the feature is not supported.
3902 The first argument points to this structure. The second
3903 argument indicates whether the packet requested support be
3904 enabled, disabled, or probed (or the default, if this function
3905 is being called at the end of processing and this feature was
3906 not reported). The third argument may be NULL; if not NULL, it
3907 is a NUL-terminated string taken from the packet following
3908 this feature's name and an equals sign. */
3909 void (*func) (const struct protocol_feature *, enum packet_support,
3912 /* The corresponding packet for this feature. Only used if
3913 FUNC is remote_supported_packet. */
3918 remote_supported_packet (const struct protocol_feature *feature,
3919 enum packet_support support,
3920 const char *argument)
3924 warning (_("Remote qSupported response supplied an unexpected value for"
3925 " \"%s\"."), feature->name);
3929 remote_protocol_packets[feature->packet].support = support;
3933 remote_packet_size (const struct protocol_feature *feature,
3934 enum packet_support support, const char *value)
3936 struct remote_state *rs = get_remote_state ();
3941 if (support != PACKET_ENABLE)
3944 if (value == NULL || *value == '\0')
3946 warning (_("Remote target reported \"%s\" without a size."),
3952 packet_size = strtol (value, &value_end, 16);
3953 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3955 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3956 feature->name, value);
3960 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3962 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3963 packet_size, MAX_REMOTE_PACKET_SIZE);
3964 packet_size = MAX_REMOTE_PACKET_SIZE;
3967 /* Record the new maximum packet size. */
3968 rs->explicit_packet_size = packet_size;
3971 static const struct protocol_feature remote_protocol_features[] = {
3972 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3973 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3974 PACKET_qXfer_auxv },
3975 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
3976 PACKET_qXfer_exec_file },
3977 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3978 PACKET_qXfer_features },
3979 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3980 PACKET_qXfer_libraries },
3981 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3982 PACKET_qXfer_libraries_svr4 },
3983 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3984 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
3985 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3986 PACKET_qXfer_memory_map },
3987 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3988 PACKET_qXfer_spu_read },
3989 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3990 PACKET_qXfer_spu_write },
3991 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3992 PACKET_qXfer_osdata },
3993 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3994 PACKET_qXfer_threads },
3995 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3996 PACKET_qXfer_traceframe_info },
3997 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3998 PACKET_QPassSignals },
3999 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4000 PACKET_QProgramSignals },
4001 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4002 PACKET_QStartNoAckMode },
4003 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4004 PACKET_multiprocess_feature },
4005 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4006 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4007 PACKET_qXfer_siginfo_read },
4008 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4009 PACKET_qXfer_siginfo_write },
4010 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4011 PACKET_ConditionalTracepoints },
4012 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4013 PACKET_ConditionalBreakpoints },
4014 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4015 PACKET_BreakpointCommands },
4016 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4017 PACKET_FastTracepoints },
4018 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4019 PACKET_StaticTracepoints },
4020 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4021 PACKET_InstallInTrace},
4022 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4023 PACKET_DisconnectedTracing_feature },
4024 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4026 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4028 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4029 PACKET_TracepointSource },
4030 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4032 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4033 PACKET_EnableDisableTracepoints_feature },
4034 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4035 PACKET_qXfer_fdpic },
4036 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4038 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4039 PACKET_QDisableRandomization },
4040 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4041 { "QTBuffer:size", PACKET_DISABLE,
4042 remote_supported_packet, PACKET_QTBuffer_size},
4043 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4044 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4045 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4046 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4047 PACKET_qXfer_btrace },
4048 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4049 PACKET_qXfer_btrace_conf },
4050 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4051 PACKET_Qbtrace_conf_bts_size },
4052 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4053 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4056 static char *remote_support_xml;
4058 /* Register string appended to "xmlRegisters=" in qSupported query. */
4061 register_remote_support_xml (const char *xml)
4063 #if defined(HAVE_LIBEXPAT)
4064 if (remote_support_xml == NULL)
4065 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4068 char *copy = xstrdup (remote_support_xml + 13);
4069 char *p = strtok (copy, ",");
4073 if (strcmp (p, xml) == 0)
4080 while ((p = strtok (NULL, ",")) != NULL);
4083 remote_support_xml = reconcat (remote_support_xml,
4084 remote_support_xml, ",", xml,
4091 remote_query_supported_append (char *msg, const char *append)
4094 return reconcat (msg, msg, ";", append, (char *) NULL);
4096 return xstrdup (append);
4100 remote_query_supported (void)
4102 struct remote_state *rs = get_remote_state ();
4105 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4107 /* The packet support flags are handled differently for this packet
4108 than for most others. We treat an error, a disabled packet, and
4109 an empty response identically: any features which must be reported
4110 to be used will be automatically disabled. An empty buffer
4111 accomplishes this, since that is also the representation for a list
4112 containing no features. */
4115 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4118 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4120 q = remote_query_supported_append (q, "multiprocess+");
4122 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4123 q = remote_query_supported_append (q, "swbreak+");
4124 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4125 q = remote_query_supported_append (q, "hwbreak+");
4127 if (remote_support_xml)
4128 q = remote_query_supported_append (q, remote_support_xml);
4130 q = remote_query_supported_append (q, "qRelocInsn+");
4132 q = reconcat (q, "qSupported:", q, (char *) NULL);
4135 do_cleanups (old_chain);
4137 getpkt (&rs->buf, &rs->buf_size, 0);
4139 /* If an error occured, warn, but do not return - just reset the
4140 buffer to empty and go on to disable features. */
4141 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4144 warning (_("Remote failure reply: %s"), rs->buf);
4149 memset (seen, 0, sizeof (seen));
4154 enum packet_support is_supported;
4155 char *p, *end, *name_end, *value;
4157 /* First separate out this item from the rest of the packet. If
4158 there's another item after this, we overwrite the separator
4159 (terminated strings are much easier to work with). */
4161 end = strchr (p, ';');
4164 end = p + strlen (p);
4174 warning (_("empty item in \"qSupported\" response"));
4179 name_end = strchr (p, '=');
4182 /* This is a name=value entry. */
4183 is_supported = PACKET_ENABLE;
4184 value = name_end + 1;
4193 is_supported = PACKET_ENABLE;
4197 is_supported = PACKET_DISABLE;
4201 is_supported = PACKET_SUPPORT_UNKNOWN;
4205 warning (_("unrecognized item \"%s\" "
4206 "in \"qSupported\" response"), p);
4212 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4213 if (strcmp (remote_protocol_features[i].name, p) == 0)
4215 const struct protocol_feature *feature;
4218 feature = &remote_protocol_features[i];
4219 feature->func (feature, is_supported, value);
4224 /* If we increased the packet size, make sure to increase the global
4225 buffer size also. We delay this until after parsing the entire
4226 qSupported packet, because this is the same buffer we were
4228 if (rs->buf_size < rs->explicit_packet_size)
4230 rs->buf_size = rs->explicit_packet_size;
4231 rs->buf = xrealloc (rs->buf, rs->buf_size);
4234 /* Handle the defaults for unmentioned features. */
4235 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4238 const struct protocol_feature *feature;
4240 feature = &remote_protocol_features[i];
4241 feature->func (feature, feature->default_support, NULL);
4245 /* Remove any of the remote.c targets from target stack. Upper targets depend
4246 on it so remove them first. */
4249 remote_unpush_target (void)
4251 pop_all_targets_above (process_stratum - 1);
4255 remote_open_1 (const char *name, int from_tty,
4256 struct target_ops *target, int extended_p)
4258 struct remote_state *rs = get_remote_state ();
4261 error (_("To open a remote debug connection, you need to specify what\n"
4262 "serial device is attached to the remote system\n"
4263 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4265 /* See FIXME above. */
4266 if (!target_async_permitted)
4267 wait_forever_enabled_p = 1;
4269 /* If we're connected to a running target, target_preopen will kill it.
4270 Ask this question first, before target_preopen has a chance to kill
4272 if (rs->remote_desc != NULL && !have_inferiors ())
4275 && !query (_("Already connected to a remote target. Disconnect? ")))
4276 error (_("Still connected."));
4279 /* Here the possibly existing remote target gets unpushed. */
4280 target_preopen (from_tty);
4282 /* Make sure we send the passed signals list the next time we resume. */
4283 xfree (rs->last_pass_packet);
4284 rs->last_pass_packet = NULL;
4286 /* Make sure we send the program signals list the next time we
4288 xfree (rs->last_program_signals_packet);
4289 rs->last_program_signals_packet = NULL;
4291 remote_fileio_reset ();
4292 reopen_exec_file ();
4295 rs->remote_desc = remote_serial_open (name);
4296 if (!rs->remote_desc)
4297 perror_with_name (name);
4299 if (baud_rate != -1)
4301 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4303 /* The requested speed could not be set. Error out to
4304 top level after closing remote_desc. Take care to
4305 set remote_desc to NULL to avoid closing remote_desc
4307 serial_close (rs->remote_desc);
4308 rs->remote_desc = NULL;
4309 perror_with_name (name);
4313 serial_setparity (rs->remote_desc, serial_parity);
4314 serial_raw (rs->remote_desc);
4316 /* If there is something sitting in the buffer we might take it as a
4317 response to a command, which would be bad. */
4318 serial_flush_input (rs->remote_desc);
4322 puts_filtered ("Remote debugging using ");
4323 puts_filtered (name);
4324 puts_filtered ("\n");
4326 push_target (target); /* Switch to using remote target now. */
4328 /* Register extra event sources in the event loop. */
4329 remote_async_inferior_event_token
4330 = create_async_event_handler (remote_async_inferior_event_handler,
4332 rs->notif_state = remote_notif_state_allocate ();
4334 /* Reset the target state; these things will be queried either by
4335 remote_query_supported or as they are needed. */
4336 reset_all_packet_configs_support ();
4337 rs->cached_wait_status = 0;
4338 rs->explicit_packet_size = 0;
4340 rs->extended = extended_p;
4341 rs->waiting_for_stop_reply = 0;
4342 rs->ctrlc_pending_p = 0;
4344 rs->general_thread = not_sent_ptid;
4345 rs->continue_thread = not_sent_ptid;
4346 rs->remote_traceframe_number = -1;
4348 /* Probe for ability to use "ThreadInfo" query, as required. */
4349 rs->use_threadinfo_query = 1;
4350 rs->use_threadextra_query = 1;
4352 if (target_async_permitted)
4354 /* With this target we start out by owning the terminal. */
4355 remote_async_terminal_ours_p = 1;
4357 /* FIXME: cagney/1999-09-23: During the initial connection it is
4358 assumed that the target is already ready and able to respond to
4359 requests. Unfortunately remote_start_remote() eventually calls
4360 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4361 around this. Eventually a mechanism that allows
4362 wait_for_inferior() to expect/get timeouts will be
4364 wait_forever_enabled_p = 0;
4367 /* First delete any symbols previously loaded from shared libraries. */
4368 no_shared_libraries (NULL, 0);
4371 init_thread_list ();
4373 /* Start the remote connection. If error() or QUIT, discard this
4374 target (we'd otherwise be in an inconsistent state) and then
4375 propogate the error on up the exception chain. This ensures that
4376 the caller doesn't stumble along blindly assuming that the
4377 function succeeded. The CLI doesn't have this problem but other
4378 UI's, such as MI do.
4380 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4381 this function should return an error indication letting the
4382 caller restore the previous state. Unfortunately the command
4383 ``target remote'' is directly wired to this function making that
4384 impossible. On a positive note, the CLI side of this problem has
4385 been fixed - the function set_cmd_context() makes it possible for
4386 all the ``target ....'' commands to share a common callback
4387 function. See cli-dump.c. */
4392 remote_start_remote (from_tty, target, extended_p);
4394 CATCH (ex, RETURN_MASK_ALL)
4396 /* Pop the partially set up target - unless something else did
4397 already before throwing the exception. */
4398 if (rs->remote_desc != NULL)
4399 remote_unpush_target ();
4400 if (target_async_permitted)
4401 wait_forever_enabled_p = 1;
4402 throw_exception (ex);
4407 remote_btrace_reset ();
4409 if (target_async_permitted)
4410 wait_forever_enabled_p = 1;
4413 /* This takes a program previously attached to and detaches it. After
4414 this is done, GDB can be used to debug some other program. We
4415 better not have left any breakpoints in the target program or it'll
4416 die when it hits one. */
4419 remote_detach_1 (const char *args, int from_tty, int extended)
4421 int pid = ptid_get_pid (inferior_ptid);
4422 struct remote_state *rs = get_remote_state ();
4425 error (_("Argument given to \"detach\" when remotely debugging."));
4427 if (!target_has_execution)
4428 error (_("No process to detach from."));
4432 char *exec_file = get_exec_file (0);
4433 if (exec_file == NULL)
4435 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4436 target_pid_to_str (pid_to_ptid (pid)));
4437 gdb_flush (gdb_stdout);
4440 /* Tell the remote target to detach. */
4441 if (remote_multi_process_p (rs))
4442 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4444 strcpy (rs->buf, "D");
4447 getpkt (&rs->buf, &rs->buf_size, 0);
4449 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4451 else if (rs->buf[0] == '\0')
4452 error (_("Remote doesn't know how to detach"));
4454 error (_("Can't detach process."));
4456 if (from_tty && !extended)
4457 puts_filtered (_("Ending remote debugging.\n"));
4459 target_mourn_inferior ();
4463 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4465 remote_detach_1 (args, from_tty, 0);
4469 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4471 remote_detach_1 (args, from_tty, 1);
4474 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4477 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4480 error (_("Argument given to \"disconnect\" when remotely debugging."));
4482 /* Make sure we unpush even the extended remote targets; mourn
4483 won't do it. So call remote_mourn directly instead of
4484 target_mourn_inferior. */
4485 remote_mourn (target);
4488 puts_filtered ("Ending remote debugging.\n");
4491 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4492 be chatty about it. */
4495 extended_remote_attach (struct target_ops *target, const char *args,
4498 struct remote_state *rs = get_remote_state ();
4500 char *wait_status = NULL;
4502 pid = parse_pid_to_attach (args);
4504 /* Remote PID can be freely equal to getpid, do not check it here the same
4505 way as in other targets. */
4507 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4508 error (_("This target does not support attaching to a process"));
4512 char *exec_file = get_exec_file (0);
4515 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4516 target_pid_to_str (pid_to_ptid (pid)));
4518 printf_unfiltered (_("Attaching to %s\n"),
4519 target_pid_to_str (pid_to_ptid (pid)));
4521 gdb_flush (gdb_stdout);
4524 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4526 getpkt (&rs->buf, &rs->buf_size, 0);
4528 switch (packet_ok (rs->buf,
4529 &remote_protocol_packets[PACKET_vAttach]))
4534 /* Save the reply for later. */
4535 wait_status = alloca (strlen (rs->buf) + 1);
4536 strcpy (wait_status, rs->buf);
4538 else if (strcmp (rs->buf, "OK") != 0)
4539 error (_("Attaching to %s failed with: %s"),
4540 target_pid_to_str (pid_to_ptid (pid)),
4543 case PACKET_UNKNOWN:
4544 error (_("This target does not support attaching to a process"));
4546 error (_("Attaching to %s failed"),
4547 target_pid_to_str (pid_to_ptid (pid)));
4550 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
4552 inferior_ptid = pid_to_ptid (pid);
4556 struct thread_info *thread;
4558 /* Get list of threads. */
4559 remote_update_thread_list (target);
4561 thread = first_thread_of_process (pid);
4563 inferior_ptid = thread->ptid;
4565 inferior_ptid = pid_to_ptid (pid);
4567 /* Invalidate our notion of the remote current thread. */
4568 record_currthread (rs, minus_one_ptid);
4572 /* Now, if we have thread information, update inferior_ptid. */
4573 inferior_ptid = remote_current_thread (inferior_ptid);
4575 /* Add the main thread to the thread list. */
4576 add_thread_silent (inferior_ptid);
4579 /* Next, if the target can specify a description, read it. We do
4580 this before anything involving memory or registers. */
4581 target_find_description ();
4585 /* Use the previously fetched status. */
4586 gdb_assert (wait_status != NULL);
4588 if (target_can_async_p ())
4590 struct notif_event *reply
4591 = remote_notif_parse (¬if_client_stop, wait_status);
4593 push_stop_reply ((struct stop_reply *) reply);
4599 gdb_assert (wait_status != NULL);
4600 strcpy (rs->buf, wait_status);
4601 rs->cached_wait_status = 1;
4605 gdb_assert (wait_status == NULL);
4608 /* Implementation of the to_post_attach method. */
4611 extended_remote_post_attach (struct target_ops *ops, int pid)
4613 /* In certain cases GDB might not have had the chance to start
4614 symbol lookup up until now. This could happen if the debugged
4615 binary is not using shared libraries, the vsyscall page is not
4616 present (on Linux) and the binary itself hadn't changed since the
4617 debugging process was started. */
4618 if (symfile_objfile != NULL)
4619 remote_check_symbols();
4623 /* Check for the availability of vCont. This function should also check
4627 remote_vcont_probe (struct remote_state *rs)
4631 strcpy (rs->buf, "vCont?");
4633 getpkt (&rs->buf, &rs->buf_size, 0);
4636 /* Make sure that the features we assume are supported. */
4637 if (startswith (buf, "vCont"))
4640 int support_s, support_S, support_c, support_C;
4646 rs->supports_vCont.t = 0;
4647 rs->supports_vCont.r = 0;
4648 while (p && *p == ';')
4651 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4653 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4655 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4657 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4659 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4660 rs->supports_vCont.t = 1;
4661 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4662 rs->supports_vCont.r = 1;
4664 p = strchr (p, ';');
4667 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4668 BUF will make packet_ok disable the packet. */
4669 if (!support_s || !support_S || !support_c || !support_C)
4673 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4676 /* Helper function for building "vCont" resumptions. Write a
4677 resumption to P. ENDP points to one-passed-the-end of the buffer
4678 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4679 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4680 resumed thread should be single-stepped and/or signalled. If PTID
4681 equals minus_one_ptid, then all threads are resumed; if PTID
4682 represents a process, then all threads of the process are resumed;
4683 the thread to be stepped and/or signalled is given in the global
4687 append_resumption (char *p, char *endp,
4688 ptid_t ptid, int step, enum gdb_signal siggnal)
4690 struct remote_state *rs = get_remote_state ();
4692 if (step && siggnal != GDB_SIGNAL_0)
4693 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4695 /* GDB is willing to range step. */
4696 && use_range_stepping
4697 /* Target supports range stepping. */
4698 && rs->supports_vCont.r
4699 /* We don't currently support range stepping multiple
4700 threads with a wildcard (though the protocol allows it,
4701 so stubs shouldn't make an active effort to forbid
4703 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4705 struct thread_info *tp;
4707 if (ptid_equal (ptid, minus_one_ptid))
4709 /* If we don't know about the target thread's tid, then
4710 we're resuming magic_null_ptid (see caller). */
4711 tp = find_thread_ptid (magic_null_ptid);
4714 tp = find_thread_ptid (ptid);
4715 gdb_assert (tp != NULL);
4717 if (tp->control.may_range_step)
4719 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4721 p += xsnprintf (p, endp - p, ";r%s,%s",
4722 phex_nz (tp->control.step_range_start,
4724 phex_nz (tp->control.step_range_end,
4728 p += xsnprintf (p, endp - p, ";s");
4731 p += xsnprintf (p, endp - p, ";s");
4732 else if (siggnal != GDB_SIGNAL_0)
4733 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4735 p += xsnprintf (p, endp - p, ";c");
4737 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4741 /* All (-1) threads of process. */
4742 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4744 p += xsnprintf (p, endp - p, ":");
4745 p = write_ptid (p, endp, nptid);
4747 else if (!ptid_equal (ptid, minus_one_ptid))
4749 p += xsnprintf (p, endp - p, ":");
4750 p = write_ptid (p, endp, ptid);
4756 /* Append a vCont continue-with-signal action for threads that have a
4757 non-zero stop signal. */
4760 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4762 struct thread_info *thread;
4764 ALL_NON_EXITED_THREADS (thread)
4765 if (ptid_match (thread->ptid, ptid)
4766 && !ptid_equal (inferior_ptid, thread->ptid)
4767 && thread->suspend.stop_signal != GDB_SIGNAL_0)
4769 p = append_resumption (p, endp, thread->ptid,
4770 0, thread->suspend.stop_signal);
4771 thread->suspend.stop_signal = GDB_SIGNAL_0;
4777 /* Resume the remote inferior by using a "vCont" packet. The thread
4778 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4779 resumed thread should be single-stepped and/or signalled. If PTID
4780 equals minus_one_ptid, then all threads are resumed; the thread to
4781 be stepped and/or signalled is given in the global INFERIOR_PTID.
4782 This function returns non-zero iff it resumes the inferior.
4784 This function issues a strict subset of all possible vCont commands at the
4788 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4790 struct remote_state *rs = get_remote_state ();
4794 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4795 remote_vcont_probe (rs);
4797 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
4801 endp = rs->buf + get_remote_packet_size ();
4803 /* If we could generate a wider range of packets, we'd have to worry
4804 about overflowing BUF. Should there be a generic
4805 "multi-part-packet" packet? */
4807 p += xsnprintf (p, endp - p, "vCont");
4809 if (ptid_equal (ptid, magic_null_ptid))
4811 /* MAGIC_NULL_PTID means that we don't have any active threads,
4812 so we don't have any TID numbers the inferior will
4813 understand. Make sure to only send forms that do not specify
4815 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4817 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4819 /* Resume all threads (of all processes, or of a single
4820 process), with preference for INFERIOR_PTID. This assumes
4821 inferior_ptid belongs to the set of all threads we are about
4823 if (step || siggnal != GDB_SIGNAL_0)
4825 /* Step inferior_ptid, with or without signal. */
4826 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4829 /* Also pass down any pending signaled resumption for other
4830 threads not the current. */
4831 p = append_pending_thread_resumptions (p, endp, ptid);
4833 /* And continue others without a signal. */
4834 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4838 /* Scheduler locking; resume only PTID. */
4839 append_resumption (p, endp, ptid, step, siggnal);
4842 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4847 /* In non-stop, the stub replies to vCont with "OK". The stop
4848 reply will be reported asynchronously by means of a `%Stop'
4850 getpkt (&rs->buf, &rs->buf_size, 0);
4851 if (strcmp (rs->buf, "OK") != 0)
4852 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4858 /* Tell the remote machine to resume. */
4861 remote_resume (struct target_ops *ops,
4862 ptid_t ptid, int step, enum gdb_signal siggnal)
4864 struct remote_state *rs = get_remote_state ();
4867 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4868 (explained in remote-notif.c:handle_notification) so
4869 remote_notif_process is not called. We need find a place where
4870 it is safe to start a 'vNotif' sequence. It is good to do it
4871 before resuming inferior, because inferior was stopped and no RSP
4872 traffic at that moment. */
4874 remote_notif_process (rs->notif_state, ¬if_client_stop);
4876 rs->last_sent_signal = siggnal;
4877 rs->last_sent_step = step;
4879 /* The vCont packet doesn't need to specify threads via Hc. */
4880 /* No reverse support (yet) for vCont. */
4881 if (execution_direction != EXEC_REVERSE)
4882 if (remote_vcont_resume (ptid, step, siggnal))
4885 /* All other supported resume packets do use Hc, so set the continue
4887 if (ptid_equal (ptid, minus_one_ptid))
4888 set_continue_thread (any_thread_ptid);
4890 set_continue_thread (ptid);
4893 if (execution_direction == EXEC_REVERSE)
4895 /* We don't pass signals to the target in reverse exec mode. */
4896 if (info_verbose && siggnal != GDB_SIGNAL_0)
4897 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4900 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
4901 error (_("Remote reverse-step not supported."));
4902 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
4903 error (_("Remote reverse-continue not supported."));
4905 strcpy (buf, step ? "bs" : "bc");
4907 else if (siggnal != GDB_SIGNAL_0)
4909 buf[0] = step ? 'S' : 'C';
4910 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4911 buf[2] = tohex (((int) siggnal) & 0xf);
4915 strcpy (buf, step ? "s" : "c");
4920 /* We are about to start executing the inferior, let's register it
4921 with the event loop. NOTE: this is the one place where all the
4922 execution commands end up. We could alternatively do this in each
4923 of the execution commands in infcmd.c. */
4924 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4925 into infcmd.c in order to allow inferior function calls to work
4926 NOT asynchronously. */
4927 if (target_can_async_p ())
4930 /* We've just told the target to resume. The remote server will
4931 wait for the inferior to stop, and then send a stop reply. In
4932 the mean time, we can't start another command/query ourselves
4933 because the stub wouldn't be ready to process it. This applies
4934 only to the base all-stop protocol, however. In non-stop (which
4935 only supports vCont), the stub replies with an "OK", and is
4936 immediate able to process further serial input. */
4938 rs->waiting_for_stop_reply = 1;
4942 /* Set up the signal handler for SIGINT, while the target is
4943 executing, ovewriting the 'regular' SIGINT signal handler. */
4945 async_initialize_sigint_signal_handler (void)
4947 signal (SIGINT, async_handle_remote_sigint);
4950 /* Signal handler for SIGINT, while the target is executing. */
4952 async_handle_remote_sigint (int sig)
4954 signal (sig, async_handle_remote_sigint_twice);
4955 /* Note we need to go through gdb_call_async_signal_handler in order
4956 to wake up the event loop on Windows. */
4957 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
4960 /* Signal handler for SIGINT, installed after SIGINT has already been
4961 sent once. It will take effect the second time that the user sends
4964 async_handle_remote_sigint_twice (int sig)
4966 signal (sig, async_handle_remote_sigint);
4967 /* See note in async_handle_remote_sigint. */
4968 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
4971 /* Perform the real interruption of the target execution, in response
4974 async_remote_interrupt (gdb_client_data arg)
4977 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
4979 target_stop (inferior_ptid);
4982 /* Perform interrupt, if the first attempt did not succeed. Just give
4983 up on the target alltogether. */
4985 async_remote_interrupt_twice (gdb_client_data arg)
4988 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
4993 /* Reinstall the usual SIGINT handlers, after the target has
4996 async_cleanup_sigint_signal_handler (void *dummy)
4998 signal (SIGINT, handle_sigint);
5001 /* Send ^C to target to halt it. Target will respond, and send us a
5003 static void (*ofunc) (int);
5005 /* The command line interface's stop routine. This function is installed
5006 as a signal handler for SIGINT. The first time a user requests a
5007 stop, we call remote_stop to send a break or ^C. If there is no
5008 response from the target (it didn't stop when the user requested it),
5009 we ask the user if he'd like to detach from the target. */
5011 sync_remote_interrupt (int signo)
5013 /* If this doesn't work, try more severe steps. */
5014 signal (signo, sync_remote_interrupt_twice);
5016 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5019 /* The user typed ^C twice. */
5022 sync_remote_interrupt_twice (int signo)
5024 signal (signo, ofunc);
5025 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5026 signal (signo, sync_remote_interrupt);
5029 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5030 thread, all threads of a remote process, or all threads of all
5034 remote_stop_ns (ptid_t ptid)
5036 struct remote_state *rs = get_remote_state ();
5038 char *endp = rs->buf + get_remote_packet_size ();
5040 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5041 remote_vcont_probe (rs);
5043 if (!rs->supports_vCont.t)
5044 error (_("Remote server does not support stopping threads"));
5046 if (ptid_equal (ptid, minus_one_ptid)
5047 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5048 p += xsnprintf (p, endp - p, "vCont;t");
5053 p += xsnprintf (p, endp - p, "vCont;t:");
5055 if (ptid_is_pid (ptid))
5056 /* All (-1) threads of process. */
5057 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5060 /* Small optimization: if we already have a stop reply for
5061 this thread, no use in telling the stub we want this
5063 if (peek_stop_reply (ptid))
5069 write_ptid (p, endp, nptid);
5072 /* In non-stop, we get an immediate OK reply. The stop reply will
5073 come in asynchronously by notification. */
5075 getpkt (&rs->buf, &rs->buf_size, 0);
5076 if (strcmp (rs->buf, "OK") != 0)
5077 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5080 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5081 remote target. It is undefined which thread of which process
5082 reports the stop. */
5085 remote_stop_as (ptid_t ptid)
5087 struct remote_state *rs = get_remote_state ();
5089 rs->ctrlc_pending_p = 1;
5091 /* If the inferior is stopped already, but the core didn't know
5092 about it yet, just ignore the request. The cached wait status
5093 will be collected in remote_wait. */
5094 if (rs->cached_wait_status)
5097 /* Send interrupt_sequence to remote target. */
5098 send_interrupt_sequence ();
5101 /* This is the generic stop called via the target vector. When a target
5102 interrupt is requested, either by the command line or the GUI, we
5103 will eventually end up here. */
5106 remote_stop (struct target_ops *self, ptid_t ptid)
5109 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5112 remote_stop_ns (ptid);
5114 remote_stop_as (ptid);
5117 /* Ask the user what to do when an interrupt is received. */
5120 interrupt_query (void)
5122 target_terminal_ours ();
5124 if (target_is_async_p ())
5126 signal (SIGINT, handle_sigint);
5131 if (query (_("Interrupted while waiting for the program.\n\
5132 Give up (and stop debugging it)? ")))
5134 remote_unpush_target ();
5139 target_terminal_inferior ();
5142 /* Enable/disable target terminal ownership. Most targets can use
5143 terminal groups to control terminal ownership. Remote targets are
5144 different in that explicit transfer of ownership to/from GDB/target
5148 remote_terminal_inferior (struct target_ops *self)
5150 if (!target_async_permitted)
5151 /* Nothing to do. */
5154 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5155 idempotent. The event-loop GDB talking to an asynchronous target
5156 with a synchronous command calls this function from both
5157 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5158 transfer the terminal to the target when it shouldn't this guard
5160 if (!remote_async_terminal_ours_p)
5162 delete_file_handler (input_fd);
5163 remote_async_terminal_ours_p = 0;
5164 async_initialize_sigint_signal_handler ();
5165 /* NOTE: At this point we could also register our selves as the
5166 recipient of all input. Any characters typed could then be
5167 passed on down to the target. */
5171 remote_terminal_ours (struct target_ops *self)
5173 if (!target_async_permitted)
5174 /* Nothing to do. */
5177 /* See FIXME in remote_terminal_inferior. */
5178 if (remote_async_terminal_ours_p)
5180 async_cleanup_sigint_signal_handler (NULL);
5181 add_file_handler (input_fd, stdin_event_handler, 0);
5182 remote_async_terminal_ours_p = 1;
5186 remote_console_output (char *msg)
5190 for (p = msg; p[0] && p[1]; p += 2)
5193 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5197 fputs_unfiltered (tb, gdb_stdtarg);
5199 gdb_flush (gdb_stdtarg);
5202 typedef struct cached_reg
5205 gdb_byte data[MAX_REGISTER_SIZE];
5208 DEF_VEC_O(cached_reg_t);
5210 typedef struct stop_reply
5212 struct notif_event base;
5214 /* The identifier of the thread about this event */
5217 /* The remote state this event is associated with. When the remote
5218 connection, represented by a remote_state object, is closed,
5219 all the associated stop_reply events should be released. */
5220 struct remote_state *rs;
5222 struct target_waitstatus ws;
5224 /* Expedited registers. This makes remote debugging a bit more
5225 efficient for those targets that provide critical registers as
5226 part of their normal status mechanism (as another roundtrip to
5227 fetch them is avoided). */
5228 VEC(cached_reg_t) *regcache;
5230 enum target_stop_reason stop_reason;
5232 CORE_ADDR watch_data_address;
5237 DECLARE_QUEUE_P (stop_reply_p);
5238 DEFINE_QUEUE_P (stop_reply_p);
5239 /* The list of already fetched and acknowledged stop events. This
5240 queue is used for notification Stop, and other notifications
5241 don't need queue for their events, because the notification events
5242 of Stop can't be consumed immediately, so that events should be
5243 queued first, and be consumed by remote_wait_{ns,as} one per
5244 time. Other notifications can consume their events immediately,
5245 so queue is not needed for them. */
5246 static QUEUE (stop_reply_p) *stop_reply_queue;
5249 stop_reply_xfree (struct stop_reply *r)
5251 notif_event_xfree ((struct notif_event *) r);
5255 remote_notif_stop_parse (struct notif_client *self, char *buf,
5256 struct notif_event *event)
5258 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5262 remote_notif_stop_ack (struct notif_client *self, char *buf,
5263 struct notif_event *event)
5265 struct stop_reply *stop_reply = (struct stop_reply *) event;
5268 putpkt ((char *) self->ack_command);
5270 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5271 /* We got an unknown stop reply. */
5272 error (_("Unknown stop reply"));
5274 push_stop_reply (stop_reply);
5278 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5280 /* We can't get pending events in remote_notif_process for
5281 notification stop, and we have to do this in remote_wait_ns
5282 instead. If we fetch all queued events from stub, remote stub
5283 may exit and we have no chance to process them back in
5285 mark_async_event_handler (remote_async_inferior_event_token);
5290 stop_reply_dtr (struct notif_event *event)
5292 struct stop_reply *r = (struct stop_reply *) event;
5294 VEC_free (cached_reg_t, r->regcache);
5297 static struct notif_event *
5298 remote_notif_stop_alloc_reply (void)
5300 struct notif_event *r
5301 = (struct notif_event *) XNEW (struct stop_reply);
5303 r->dtr = stop_reply_dtr;
5308 /* A client of notification Stop. */
5310 struct notif_client notif_client_stop =
5314 remote_notif_stop_parse,
5315 remote_notif_stop_ack,
5316 remote_notif_stop_can_get_pending_events,
5317 remote_notif_stop_alloc_reply,
5321 /* A parameter to pass data in and out. */
5323 struct queue_iter_param
5326 struct stop_reply *output;
5329 /* Remove stop replies in the queue if its pid is equal to the given
5333 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5334 QUEUE_ITER (stop_reply_p) *iter,
5338 struct queue_iter_param *param = data;
5339 struct inferior *inf = param->input;
5341 if (ptid_get_pid (event->ptid) == inf->pid)
5343 stop_reply_xfree (event);
5344 QUEUE_remove_elem (stop_reply_p, q, iter);
5350 /* Discard all pending stop replies of inferior INF. */
5353 discard_pending_stop_replies (struct inferior *inf)
5356 struct queue_iter_param param;
5357 struct stop_reply *reply;
5358 struct remote_state *rs = get_remote_state ();
5359 struct remote_notif_state *rns = rs->notif_state;
5361 /* This function can be notified when an inferior exists. When the
5362 target is not remote, the notification state is NULL. */
5363 if (rs->remote_desc == NULL)
5366 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5368 /* Discard the in-flight notification. */
5369 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5371 stop_reply_xfree (reply);
5372 rns->pending_event[notif_client_stop.id] = NULL;
5376 param.output = NULL;
5377 /* Discard the stop replies we have already pulled with
5379 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5380 remove_stop_reply_for_inferior, ¶m);
5383 /* If its remote state is equal to the given remote state,
5384 remove EVENT from the stop reply queue. */
5387 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5388 QUEUE_ITER (stop_reply_p) *iter,
5392 struct queue_iter_param *param = data;
5393 struct remote_state *rs = param->input;
5395 if (event->rs == rs)
5397 stop_reply_xfree (event);
5398 QUEUE_remove_elem (stop_reply_p, q, iter);
5404 /* Discard the stop replies for RS in stop_reply_queue. */
5407 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5409 struct queue_iter_param param;
5412 param.output = NULL;
5413 /* Discard the stop replies we have already pulled with
5415 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5416 remove_stop_reply_of_remote_state, ¶m);
5419 /* A parameter to pass data in and out. */
5422 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5423 QUEUE_ITER (stop_reply_p) *iter,
5427 struct queue_iter_param *param = data;
5428 ptid_t *ptid = param->input;
5430 if (ptid_match (event->ptid, *ptid))
5432 param->output = event;
5433 QUEUE_remove_elem (stop_reply_p, q, iter);
5440 /* Remove the first reply in 'stop_reply_queue' which matches
5443 static struct stop_reply *
5444 remote_notif_remove_queued_reply (ptid_t ptid)
5446 struct queue_iter_param param;
5448 param.input = &ptid;
5449 param.output = NULL;
5451 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5452 remote_notif_remove_once_on_match, ¶m);
5454 fprintf_unfiltered (gdb_stdlog,
5455 "notif: discard queued event: 'Stop' in %s\n",
5456 target_pid_to_str (ptid));
5458 return param.output;
5461 /* Look for a queued stop reply belonging to PTID. If one is found,
5462 remove it from the queue, and return it. Returns NULL if none is
5463 found. If there are still queued events left to process, tell the
5464 event loop to get back to target_wait soon. */
5466 static struct stop_reply *
5467 queued_stop_reply (ptid_t ptid)
5469 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5471 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5472 /* There's still at least an event left. */
5473 mark_async_event_handler (remote_async_inferior_event_token);
5478 /* Push a fully parsed stop reply in the stop reply queue. Since we
5479 know that we now have at least one queued event left to pass to the
5480 core side, tell the event loop to get back to target_wait soon. */
5483 push_stop_reply (struct stop_reply *new_event)
5485 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5488 fprintf_unfiltered (gdb_stdlog,
5489 "notif: push 'Stop' %s to queue %d\n",
5490 target_pid_to_str (new_event->ptid),
5491 QUEUE_length (stop_reply_p,
5494 mark_async_event_handler (remote_async_inferior_event_token);
5498 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5499 QUEUE_ITER (stop_reply_p) *iter,
5500 struct stop_reply *event,
5503 ptid_t *ptid = data;
5505 return !(ptid_equal (*ptid, event->ptid)
5506 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5509 /* Returns true if we have a stop reply for PTID. */
5512 peek_stop_reply (ptid_t ptid)
5514 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5515 stop_reply_match_ptid_and_ws, &ptid);
5518 /* Skip PACKET until the next semi-colon (or end of string). */
5521 skip_to_semicolon (char *p)
5523 while (*p != '\0' && *p != ';')
5528 /* Parse the stop reply in BUF. Either the function succeeds, and the
5529 result is stored in EVENT, or throws an error. */
5532 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5534 struct remote_arch_state *rsa = get_remote_arch_state ();
5538 event->ptid = null_ptid;
5539 event->rs = get_remote_state ();
5540 event->ws.kind = TARGET_WAITKIND_IGNORE;
5541 event->ws.value.integer = 0;
5542 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5543 event->regcache = NULL;
5548 case 'T': /* Status with PC, SP, FP, ... */
5549 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5550 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5552 n... = register number
5553 r... = register contents
5556 p = &buf[3]; /* after Txx */
5562 p1 = strchr (p, ':');
5564 error (_("Malformed packet(a) (missing colon): %s\n\
5568 error (_("Malformed packet(a) (missing register number): %s\n\
5572 /* Some "registers" are actually extended stop information.
5573 Note if you're adding a new entry here: GDB 7.9 and
5574 earlier assume that all register "numbers" that start
5575 with an hex digit are real register numbers. Make sure
5576 the server only sends such a packet if it knows the
5577 client understands it. */
5579 if (strncmp (p, "thread", p1 - p) == 0)
5580 event->ptid = read_ptid (++p1, &p);
5581 else if ((strncmp (p, "watch", p1 - p) == 0)
5582 || (strncmp (p, "rwatch", p1 - p) == 0)
5583 || (strncmp (p, "awatch", p1 - p) == 0))
5585 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
5586 p = unpack_varlen_hex (++p1, &addr);
5587 event->watch_data_address = (CORE_ADDR) addr;
5589 else if (strncmp (p, "swbreak", p1 - p) == 0)
5591 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5593 /* Make sure the stub doesn't forget to indicate support
5595 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5596 error (_("Unexpected swbreak stop reason"));
5598 /* The value part is documented as "must be empty",
5599 though we ignore it, in case we ever decide to make
5600 use of it in a backward compatible way. */
5601 p = skip_to_semicolon (p1 + 1);
5603 else if (strncmp (p, "hwbreak", p1 - p) == 0)
5605 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5607 /* Make sure the stub doesn't forget to indicate support
5609 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5610 error (_("Unexpected hwbreak stop reason"));
5613 p = skip_to_semicolon (p1 + 1);
5615 else if (strncmp (p, "library", p1 - p) == 0)
5617 event->ws.kind = TARGET_WAITKIND_LOADED;
5618 p = skip_to_semicolon (p1 + 1);
5620 else if (strncmp (p, "replaylog", p1 - p) == 0)
5622 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5623 /* p1 will indicate "begin" or "end", but it makes
5624 no difference for now, so ignore it. */
5625 p = skip_to_semicolon (p1 + 1);
5627 else if (strncmp (p, "core", p1 - p) == 0)
5631 p = unpack_varlen_hex (++p1, &c);
5639 /* Maybe a real ``P'' register number. */
5640 p_temp = unpack_varlen_hex (p, &pnum);
5641 /* If the first invalid character is the colon, we got a
5642 register number. Otherwise, it's an unknown stop
5646 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5647 cached_reg_t cached_reg;
5650 error (_("Remote sent bad register number %s: %s\n\
5652 hex_string (pnum), p, buf);
5654 cached_reg.num = reg->regnum;
5657 fieldsize = hex2bin (p, cached_reg.data,
5658 register_size (target_gdbarch (),
5661 if (fieldsize < register_size (target_gdbarch (),
5663 warning (_("Remote reply is too short: %s"), buf);
5665 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5669 /* Not a number. Silently skip unknown optional
5671 p = skip_to_semicolon (p1 + 1);
5676 error (_("Remote register badly formatted: %s\nhere: %s"),
5681 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5685 case 'S': /* Old style status, just signal only. */
5689 event->ws.kind = TARGET_WAITKIND_STOPPED;
5690 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5691 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5692 event->ws.value.sig = (enum gdb_signal) sig;
5694 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5697 case 'W': /* Target exited. */
5704 /* GDB used to accept only 2 hex chars here. Stubs should
5705 only send more if they detect GDB supports multi-process
5707 p = unpack_varlen_hex (&buf[1], &value);
5711 /* The remote process exited. */
5712 event->ws.kind = TARGET_WAITKIND_EXITED;
5713 event->ws.value.integer = value;
5717 /* The remote process exited with a signal. */
5718 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5719 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5720 event->ws.value.sig = (enum gdb_signal) value;
5722 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5725 /* If no process is specified, assume inferior_ptid. */
5726 pid = ptid_get_pid (inferior_ptid);
5735 else if (startswith (p, "process:"))
5739 p += sizeof ("process:") - 1;
5740 unpack_varlen_hex (p, &upid);
5744 error (_("unknown stop reply packet: %s"), buf);
5747 error (_("unknown stop reply packet: %s"), buf);
5748 event->ptid = pid_to_ptid (pid);
5753 if (non_stop && ptid_equal (event->ptid, null_ptid))
5754 error (_("No process or thread specified in stop reply: %s"), buf);
5757 /* When the stub wants to tell GDB about a new notification reply, it
5758 sends a notification (%Stop, for example). Those can come it at
5759 any time, hence, we have to make sure that any pending
5760 putpkt/getpkt sequence we're making is finished, before querying
5761 the stub for more events with the corresponding ack command
5762 (vStopped, for example). E.g., if we started a vStopped sequence
5763 immediately upon receiving the notification, something like this
5771 1.6) <-- (registers reply to step #1.3)
5773 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5776 To solve this, whenever we parse a %Stop notification successfully,
5777 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5778 doing whatever we were doing:
5784 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5785 2.5) <-- (registers reply to step #2.3)
5787 Eventualy after step #2.5, we return to the event loop, which
5788 notices there's an event on the
5789 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5790 associated callback --- the function below. At this point, we're
5791 always safe to start a vStopped sequence. :
5794 2.7) <-- T05 thread:2
5800 remote_notif_get_pending_events (struct notif_client *nc)
5802 struct remote_state *rs = get_remote_state ();
5804 if (rs->notif_state->pending_event[nc->id] != NULL)
5807 fprintf_unfiltered (gdb_stdlog,
5808 "notif: process: '%s' ack pending event\n",
5812 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5813 rs->notif_state->pending_event[nc->id] = NULL;
5817 getpkt (&rs->buf, &rs->buf_size, 0);
5818 if (strcmp (rs->buf, "OK") == 0)
5821 remote_notif_ack (nc, rs->buf);
5827 fprintf_unfiltered (gdb_stdlog,
5828 "notif: process: '%s' no pending reply\n",
5833 /* Called when it is decided that STOP_REPLY holds the info of the
5834 event that is to be returned to the core. This function always
5835 destroys STOP_REPLY. */
5838 process_stop_reply (struct stop_reply *stop_reply,
5839 struct target_waitstatus *status)
5843 *status = stop_reply->ws;
5844 ptid = stop_reply->ptid;
5846 /* If no thread/process was reported by the stub, assume the current
5848 if (ptid_equal (ptid, null_ptid))
5849 ptid = inferior_ptid;
5851 if (status->kind != TARGET_WAITKIND_EXITED
5852 && status->kind != TARGET_WAITKIND_SIGNALLED)
5854 struct remote_state *rs = get_remote_state ();
5856 /* Expedited registers. */
5857 if (stop_reply->regcache)
5859 struct regcache *regcache
5860 = get_thread_arch_regcache (ptid, target_gdbarch ());
5865 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5867 regcache_raw_supply (regcache, reg->num, reg->data);
5868 VEC_free (cached_reg_t, stop_reply->regcache);
5871 rs->stop_reason = stop_reply->stop_reason;
5872 rs->remote_watch_data_address = stop_reply->watch_data_address;
5874 remote_notice_new_inferior (ptid, 0);
5875 demand_private_info (ptid)->core = stop_reply->core;
5878 stop_reply_xfree (stop_reply);
5882 /* The non-stop mode version of target_wait. */
5885 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5887 struct remote_state *rs = get_remote_state ();
5888 struct stop_reply *stop_reply;
5892 /* If in non-stop mode, get out of getpkt even if a
5893 notification is received. */
5895 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5896 0 /* forever */, &is_notif);
5899 if (ret != -1 && !is_notif)
5902 case 'E': /* Error of some sort. */
5903 /* We're out of sync with the target now. Did it continue
5904 or not? We can't tell which thread it was in non-stop,
5905 so just ignore this. */
5906 warning (_("Remote failure reply: %s"), rs->buf);
5908 case 'O': /* Console output. */
5909 remote_console_output (rs->buf + 1);
5912 warning (_("Invalid remote reply: %s"), rs->buf);
5916 /* Acknowledge a pending stop reply that may have arrived in the
5918 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
5919 remote_notif_get_pending_events (¬if_client_stop);
5921 /* If indeed we noticed a stop reply, we're done. */
5922 stop_reply = queued_stop_reply (ptid);
5923 if (stop_reply != NULL)
5924 return process_stop_reply (stop_reply, status);
5926 /* Still no event. If we're just polling for an event, then
5927 return to the event loop. */
5928 if (options & TARGET_WNOHANG)
5930 status->kind = TARGET_WAITKIND_IGNORE;
5931 return minus_one_ptid;
5934 /* Otherwise do a blocking wait. */
5935 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5936 1 /* forever */, &is_notif);
5940 /* Wait until the remote machine stops, then return, storing status in
5941 STATUS just as `wait' would. */
5944 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5946 struct remote_state *rs = get_remote_state ();
5947 ptid_t event_ptid = null_ptid;
5949 struct stop_reply *stop_reply;
5953 status->kind = TARGET_WAITKIND_IGNORE;
5954 status->value.integer = 0;
5956 stop_reply = queued_stop_reply (ptid);
5957 if (stop_reply != NULL)
5958 return process_stop_reply (stop_reply, status);
5960 if (rs->cached_wait_status)
5961 /* Use the cached wait status, but only once. */
5962 rs->cached_wait_status = 0;
5968 if (!target_is_async_p ())
5970 ofunc = signal (SIGINT, sync_remote_interrupt);
5971 /* If the user hit C-c before this packet, or between packets,
5972 pretend that it was hit right here. */
5973 if (check_quit_flag ())
5976 sync_remote_interrupt (SIGINT);
5980 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5981 _never_ wait for ever -> test on target_is_async_p().
5982 However, before we do that we need to ensure that the caller
5983 knows how to take the target into/out of async mode. */
5984 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5985 wait_forever_enabled_p, &is_notif);
5987 if (!target_is_async_p ())
5988 signal (SIGINT, ofunc);
5990 /* GDB gets a notification. Return to core as this event is
5992 if (ret != -1 && is_notif)
5993 return minus_one_ptid;
5998 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6000 /* We got something. */
6001 rs->waiting_for_stop_reply = 0;
6003 /* Assume that the target has acknowledged Ctrl-C unless we receive
6004 an 'F' or 'O' packet. */
6005 if (buf[0] != 'F' && buf[0] != 'O')
6006 rs->ctrlc_pending_p = 0;
6010 case 'E': /* Error of some sort. */
6011 /* We're out of sync with the target now. Did it continue or
6012 not? Not is more likely, so report a stop. */
6013 warning (_("Remote failure reply: %s"), buf);
6014 status->kind = TARGET_WAITKIND_STOPPED;
6015 status->value.sig = GDB_SIGNAL_0;
6017 case 'F': /* File-I/O request. */
6018 remote_fileio_request (buf, rs->ctrlc_pending_p);
6019 rs->ctrlc_pending_p = 0;
6021 case 'T': case 'S': case 'X': case 'W':
6023 struct stop_reply *stop_reply
6024 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6027 event_ptid = process_stop_reply (stop_reply, status);
6030 case 'O': /* Console output. */
6031 remote_console_output (buf + 1);
6033 /* The target didn't really stop; keep waiting. */
6034 rs->waiting_for_stop_reply = 1;
6038 if (rs->last_sent_signal != GDB_SIGNAL_0)
6040 /* Zero length reply means that we tried 'S' or 'C' and the
6041 remote system doesn't support it. */
6042 target_terminal_ours_for_output ();
6044 ("Can't send signals to this remote system. %s not sent.\n",
6045 gdb_signal_to_name (rs->last_sent_signal));
6046 rs->last_sent_signal = GDB_SIGNAL_0;
6047 target_terminal_inferior ();
6049 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6050 putpkt ((char *) buf);
6052 /* We just told the target to resume, so a stop reply is in
6054 rs->waiting_for_stop_reply = 1;
6057 /* else fallthrough */
6059 warning (_("Invalid remote reply: %s"), buf);
6061 rs->waiting_for_stop_reply = 1;
6065 if (status->kind == TARGET_WAITKIND_IGNORE)
6067 /* Nothing interesting happened. If we're doing a non-blocking
6068 poll, we're done. Otherwise, go back to waiting. */
6069 if (options & TARGET_WNOHANG)
6070 return minus_one_ptid;
6074 else if (status->kind != TARGET_WAITKIND_EXITED
6075 && status->kind != TARGET_WAITKIND_SIGNALLED)
6077 if (!ptid_equal (event_ptid, null_ptid))
6078 record_currthread (rs, event_ptid);
6080 event_ptid = inferior_ptid;
6083 /* A process exit. Invalidate our notion of current thread. */
6084 record_currthread (rs, minus_one_ptid);
6089 /* Wait until the remote machine stops, then return, storing status in
6090 STATUS just as `wait' would. */
6093 remote_wait (struct target_ops *ops,
6094 ptid_t ptid, struct target_waitstatus *status, int options)
6099 event_ptid = remote_wait_ns (ptid, status, options);
6101 event_ptid = remote_wait_as (ptid, status, options);
6103 if (target_is_async_p ())
6105 /* If there are are events left in the queue tell the event loop
6107 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6108 mark_async_event_handler (remote_async_inferior_event_token);
6114 /* Fetch a single register using a 'p' packet. */
6117 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6119 struct remote_state *rs = get_remote_state ();
6121 char regp[MAX_REGISTER_SIZE];
6124 if (packet_support (PACKET_p) == PACKET_DISABLE)
6127 if (reg->pnum == -1)
6132 p += hexnumstr (p, reg->pnum);
6135 getpkt (&rs->buf, &rs->buf_size, 0);
6139 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6143 case PACKET_UNKNOWN:
6146 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6147 gdbarch_register_name (get_regcache_arch (regcache),
6152 /* If this register is unfetchable, tell the regcache. */
6155 regcache_raw_supply (regcache, reg->regnum, NULL);
6159 /* Otherwise, parse and supply the value. */
6165 error (_("fetch_register_using_p: early buf termination"));
6167 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6170 regcache_raw_supply (regcache, reg->regnum, regp);
6174 /* Fetch the registers included in the target's 'g' packet. */
6177 send_g_packet (void)
6179 struct remote_state *rs = get_remote_state ();
6182 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6183 remote_send (&rs->buf, &rs->buf_size);
6185 /* We can get out of synch in various cases. If the first character
6186 in the buffer is not a hex character, assume that has happened
6187 and try to fetch another packet to read. */
6188 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6189 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6190 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6191 && rs->buf[0] != 'x') /* New: unavailable register value. */
6194 fprintf_unfiltered (gdb_stdlog,
6195 "Bad register packet; fetching a new packet\n");
6196 getpkt (&rs->buf, &rs->buf_size, 0);
6199 buf_len = strlen (rs->buf);
6201 /* Sanity check the received packet. */
6202 if (buf_len % 2 != 0)
6203 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6209 process_g_packet (struct regcache *regcache)
6211 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6212 struct remote_state *rs = get_remote_state ();
6213 struct remote_arch_state *rsa = get_remote_arch_state ();
6218 buf_len = strlen (rs->buf);
6220 /* Further sanity checks, with knowledge of the architecture. */
6221 if (buf_len > 2 * rsa->sizeof_g_packet)
6222 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6224 /* Save the size of the packet sent to us by the target. It is used
6225 as a heuristic when determining the max size of packets that the
6226 target can safely receive. */
6227 if (rsa->actual_register_packet_size == 0)
6228 rsa->actual_register_packet_size = buf_len;
6230 /* If this is smaller than we guessed the 'g' packet would be,
6231 update our records. A 'g' reply that doesn't include a register's
6232 value implies either that the register is not available, or that
6233 the 'p' packet must be used. */
6234 if (buf_len < 2 * rsa->sizeof_g_packet)
6236 rsa->sizeof_g_packet = buf_len / 2;
6238 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6240 if (rsa->regs[i].pnum == -1)
6243 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6244 rsa->regs[i].in_g_packet = 0;
6246 rsa->regs[i].in_g_packet = 1;
6250 regs = alloca (rsa->sizeof_g_packet);
6252 /* Unimplemented registers read as all bits zero. */
6253 memset (regs, 0, rsa->sizeof_g_packet);
6255 /* Reply describes registers byte by byte, each byte encoded as two
6256 hex characters. Suck them all up, then supply them to the
6257 register cacheing/storage mechanism. */
6260 for (i = 0; i < rsa->sizeof_g_packet; i++)
6262 if (p[0] == 0 || p[1] == 0)
6263 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6264 internal_error (__FILE__, __LINE__,
6265 _("unexpected end of 'g' packet reply"));
6267 if (p[0] == 'x' && p[1] == 'x')
6268 regs[i] = 0; /* 'x' */
6270 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6274 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6276 struct packet_reg *r = &rsa->regs[i];
6280 if (r->offset * 2 >= strlen (rs->buf))
6281 /* This shouldn't happen - we adjusted in_g_packet above. */
6282 internal_error (__FILE__, __LINE__,
6283 _("unexpected end of 'g' packet reply"));
6284 else if (rs->buf[r->offset * 2] == 'x')
6286 gdb_assert (r->offset * 2 < strlen (rs->buf));
6287 /* The register isn't available, mark it as such (at
6288 the same time setting the value to zero). */
6289 regcache_raw_supply (regcache, r->regnum, NULL);
6292 regcache_raw_supply (regcache, r->regnum,
6299 fetch_registers_using_g (struct regcache *regcache)
6302 process_g_packet (regcache);
6305 /* Make the remote selected traceframe match GDB's selected
6309 set_remote_traceframe (void)
6312 struct remote_state *rs = get_remote_state ();
6314 if (rs->remote_traceframe_number == get_traceframe_number ())
6317 /* Avoid recursion, remote_trace_find calls us again. */
6318 rs->remote_traceframe_number = get_traceframe_number ();
6320 newnum = target_trace_find (tfind_number,
6321 get_traceframe_number (), 0, 0, NULL);
6323 /* Should not happen. If it does, all bets are off. */
6324 if (newnum != get_traceframe_number ())
6325 warning (_("could not set remote traceframe"));
6329 remote_fetch_registers (struct target_ops *ops,
6330 struct regcache *regcache, int regnum)
6332 struct remote_arch_state *rsa = get_remote_arch_state ();
6335 set_remote_traceframe ();
6336 set_general_thread (inferior_ptid);
6340 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6342 gdb_assert (reg != NULL);
6344 /* If this register might be in the 'g' packet, try that first -
6345 we are likely to read more than one register. If this is the
6346 first 'g' packet, we might be overly optimistic about its
6347 contents, so fall back to 'p'. */
6348 if (reg->in_g_packet)
6350 fetch_registers_using_g (regcache);
6351 if (reg->in_g_packet)
6355 if (fetch_register_using_p (regcache, reg))
6358 /* This register is not available. */
6359 regcache_raw_supply (regcache, reg->regnum, NULL);
6364 fetch_registers_using_g (regcache);
6366 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6367 if (!rsa->regs[i].in_g_packet)
6368 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6370 /* This register is not available. */
6371 regcache_raw_supply (regcache, i, NULL);
6375 /* Prepare to store registers. Since we may send them all (using a
6376 'G' request), we have to read out the ones we don't want to change
6380 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6382 struct remote_arch_state *rsa = get_remote_arch_state ();
6384 gdb_byte buf[MAX_REGISTER_SIZE];
6386 /* Make sure the entire registers array is valid. */
6387 switch (packet_support (PACKET_P))
6389 case PACKET_DISABLE:
6390 case PACKET_SUPPORT_UNKNOWN:
6391 /* Make sure all the necessary registers are cached. */
6392 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6393 if (rsa->regs[i].in_g_packet)
6394 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6401 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6402 packet was not recognized. */
6405 store_register_using_P (const struct regcache *regcache,
6406 struct packet_reg *reg)
6408 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6409 struct remote_state *rs = get_remote_state ();
6410 /* Try storing a single register. */
6411 char *buf = rs->buf;
6412 gdb_byte regp[MAX_REGISTER_SIZE];
6415 if (packet_support (PACKET_P) == PACKET_DISABLE)
6418 if (reg->pnum == -1)
6421 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6422 p = buf + strlen (buf);
6423 regcache_raw_collect (regcache, reg->regnum, regp);
6424 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6426 getpkt (&rs->buf, &rs->buf_size, 0);
6428 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6433 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6434 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6435 case PACKET_UNKNOWN:
6438 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6442 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6443 contents of the register cache buffer. FIXME: ignores errors. */
6446 store_registers_using_G (const struct regcache *regcache)
6448 struct remote_state *rs = get_remote_state ();
6449 struct remote_arch_state *rsa = get_remote_arch_state ();
6453 /* Extract all the registers in the regcache copying them into a
6458 regs = alloca (rsa->sizeof_g_packet);
6459 memset (regs, 0, rsa->sizeof_g_packet);
6460 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6462 struct packet_reg *r = &rsa->regs[i];
6465 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6469 /* Command describes registers byte by byte,
6470 each byte encoded as two hex characters. */
6473 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6475 bin2hex (regs, p, rsa->sizeof_g_packet);
6477 getpkt (&rs->buf, &rs->buf_size, 0);
6478 if (packet_check_result (rs->buf) == PACKET_ERROR)
6479 error (_("Could not write registers; remote failure reply '%s'"),
6483 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6484 of the register cache buffer. FIXME: ignores errors. */
6487 remote_store_registers (struct target_ops *ops,
6488 struct regcache *regcache, int regnum)
6490 struct remote_arch_state *rsa = get_remote_arch_state ();
6493 set_remote_traceframe ();
6494 set_general_thread (inferior_ptid);
6498 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6500 gdb_assert (reg != NULL);
6502 /* Always prefer to store registers using the 'P' packet if
6503 possible; we often change only a small number of registers.
6504 Sometimes we change a larger number; we'd need help from a
6505 higher layer to know to use 'G'. */
6506 if (store_register_using_P (regcache, reg))
6509 /* For now, don't complain if we have no way to write the
6510 register. GDB loses track of unavailable registers too
6511 easily. Some day, this may be an error. We don't have
6512 any way to read the register, either... */
6513 if (!reg->in_g_packet)
6516 store_registers_using_G (regcache);
6520 store_registers_using_G (regcache);
6522 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6523 if (!rsa->regs[i].in_g_packet)
6524 if (!store_register_using_P (regcache, &rsa->regs[i]))
6525 /* See above for why we do not issue an error here. */
6530 /* Return the number of hex digits in num. */
6533 hexnumlen (ULONGEST num)
6537 for (i = 0; num != 0; i++)
6543 /* Set BUF to the minimum number of hex digits representing NUM. */
6546 hexnumstr (char *buf, ULONGEST num)
6548 int len = hexnumlen (num);
6550 return hexnumnstr (buf, num, len);
6554 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6557 hexnumnstr (char *buf, ULONGEST num, int width)
6563 for (i = width - 1; i >= 0; i--)
6565 buf[i] = "0123456789abcdef"[(num & 0xf)];
6572 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6575 remote_address_masked (CORE_ADDR addr)
6577 unsigned int address_size = remote_address_size;
6579 /* If "remoteaddresssize" was not set, default to target address size. */
6581 address_size = gdbarch_addr_bit (target_gdbarch ());
6583 if (address_size > 0
6584 && address_size < (sizeof (ULONGEST) * 8))
6586 /* Only create a mask when that mask can safely be constructed
6587 in a ULONGEST variable. */
6590 mask = (mask << address_size) - 1;
6596 /* Determine whether the remote target supports binary downloading.
6597 This is accomplished by sending a no-op memory write of zero length
6598 to the target at the specified address. It does not suffice to send
6599 the whole packet, since many stubs strip the eighth bit and
6600 subsequently compute a wrong checksum, which causes real havoc with
6603 NOTE: This can still lose if the serial line is not eight-bit
6604 clean. In cases like this, the user should clear "remote
6608 check_binary_download (CORE_ADDR addr)
6610 struct remote_state *rs = get_remote_state ();
6612 switch (packet_support (PACKET_X))
6614 case PACKET_DISABLE:
6618 case PACKET_SUPPORT_UNKNOWN:
6624 p += hexnumstr (p, (ULONGEST) addr);
6626 p += hexnumstr (p, (ULONGEST) 0);
6630 putpkt_binary (rs->buf, (int) (p - rs->buf));
6631 getpkt (&rs->buf, &rs->buf_size, 0);
6633 if (rs->buf[0] == '\0')
6636 fprintf_unfiltered (gdb_stdlog,
6637 "binary downloading NOT "
6638 "supported by target\n");
6639 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6644 fprintf_unfiltered (gdb_stdlog,
6645 "binary downloading supported by target\n");
6646 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6653 /* Write memory data directly to the remote machine.
6654 This does not inform the data cache; the data cache uses this.
6655 HEADER is the starting part of the packet.
6656 MEMADDR is the address in the remote memory space.
6657 MYADDR is the address of the buffer in our space.
6658 LEN is the number of bytes.
6659 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6660 should send data as binary ('X'), or hex-encoded ('M').
6662 The function creates packet of the form
6663 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6665 where encoding of <DATA> is termined by PACKET_FORMAT.
6667 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6670 Return the transferred status, error or OK (an
6671 'enum target_xfer_status' value). Save the number of bytes
6672 transferred in *XFERED_LEN. Only transfer a single packet. */
6674 static enum target_xfer_status
6675 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6676 const gdb_byte *myaddr, ULONGEST len,
6677 ULONGEST *xfered_len, char packet_format,
6680 struct remote_state *rs = get_remote_state ();
6690 if (packet_format != 'X' && packet_format != 'M')
6691 internal_error (__FILE__, __LINE__,
6692 _("remote_write_bytes_aux: bad packet format"));
6695 return TARGET_XFER_EOF;
6697 payload_size = get_memory_write_packet_size ();
6699 /* The packet buffer will be large enough for the payload;
6700 get_memory_packet_size ensures this. */
6703 /* Compute the size of the actual payload by subtracting out the
6704 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6706 payload_size -= strlen ("$,:#NN");
6708 /* The comma won't be used. */
6710 header_length = strlen (header);
6711 payload_size -= header_length;
6712 payload_size -= hexnumlen (memaddr);
6714 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6716 strcat (rs->buf, header);
6717 p = rs->buf + strlen (header);
6719 /* Compute a best guess of the number of bytes actually transfered. */
6720 if (packet_format == 'X')
6722 /* Best guess at number of bytes that will fit. */
6723 todo = min (len, payload_size);
6725 payload_size -= hexnumlen (todo);
6726 todo = min (todo, payload_size);
6730 /* Num bytes that will fit. */
6731 todo = min (len, payload_size / 2);
6733 payload_size -= hexnumlen (todo);
6734 todo = min (todo, payload_size / 2);
6738 internal_error (__FILE__, __LINE__,
6739 _("minimum packet size too small to write data"));
6741 /* If we already need another packet, then try to align the end
6742 of this packet to a useful boundary. */
6743 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6744 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6746 /* Append "<memaddr>". */
6747 memaddr = remote_address_masked (memaddr);
6748 p += hexnumstr (p, (ULONGEST) memaddr);
6755 /* Append <len>. Retain the location/size of <len>. It may need to
6756 be adjusted once the packet body has been created. */
6758 plenlen = hexnumstr (p, (ULONGEST) todo);
6766 /* Append the packet body. */
6767 if (packet_format == 'X')
6769 /* Binary mode. Send target system values byte by byte, in
6770 increasing byte addresses. Only escape certain critical
6772 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6773 &nr_bytes, payload_size);
6775 /* If not all TODO bytes fit, then we'll need another packet. Make
6776 a second try to keep the end of the packet aligned. Don't do
6777 this if the packet is tiny. */
6778 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6782 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6784 if (new_nr_bytes != nr_bytes)
6785 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6786 (gdb_byte *) p, &nr_bytes,
6790 p += payload_length;
6791 if (use_length && nr_bytes < todo)
6793 /* Escape chars have filled up the buffer prematurely,
6794 and we have actually sent fewer bytes than planned.
6795 Fix-up the length field of the packet. Use the same
6796 number of characters as before. */
6797 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6798 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6803 /* Normal mode: Send target system values byte by byte, in
6804 increasing byte addresses. Each byte is encoded as a two hex
6806 nr_bytes = bin2hex (myaddr, p, todo);
6810 putpkt_binary (rs->buf, (int) (p - rs->buf));
6811 getpkt (&rs->buf, &rs->buf_size, 0);
6813 if (rs->buf[0] == 'E')
6814 return TARGET_XFER_E_IO;
6816 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6817 fewer bytes than we'd planned. */
6818 *xfered_len = (ULONGEST) nr_bytes;
6819 return TARGET_XFER_OK;
6822 /* Write memory data directly to the remote machine.
6823 This does not inform the data cache; the data cache uses this.
6824 MEMADDR is the address in the remote memory space.
6825 MYADDR is the address of the buffer in our space.
6826 LEN is the number of bytes.
6828 Return the transferred status, error or OK (an
6829 'enum target_xfer_status' value). Save the number of bytes
6830 transferred in *XFERED_LEN. Only transfer a single packet. */
6832 static enum target_xfer_status
6833 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6834 ULONGEST *xfered_len)
6836 char *packet_format = 0;
6838 /* Check whether the target supports binary download. */
6839 check_binary_download (memaddr);
6841 switch (packet_support (PACKET_X))
6844 packet_format = "X";
6846 case PACKET_DISABLE:
6847 packet_format = "M";
6849 case PACKET_SUPPORT_UNKNOWN:
6850 internal_error (__FILE__, __LINE__,
6851 _("remote_write_bytes: bad internal state"));
6853 internal_error (__FILE__, __LINE__, _("bad switch"));
6856 return remote_write_bytes_aux (packet_format,
6857 memaddr, myaddr, len, xfered_len,
6858 packet_format[0], 1);
6861 /* Read memory data directly from the remote machine.
6862 This does not use the data cache; the data cache uses this.
6863 MEMADDR is the address in the remote memory space.
6864 MYADDR is the address of the buffer in our space.
6865 LEN is the number of bytes.
6867 Return the transferred status, error or OK (an
6868 'enum target_xfer_status' value). Save the number of bytes
6869 transferred in *XFERED_LEN. */
6871 static enum target_xfer_status
6872 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6873 ULONGEST *xfered_len)
6875 struct remote_state *rs = get_remote_state ();
6876 int max_buf_size; /* Max size of packet output buffer. */
6881 max_buf_size = get_memory_read_packet_size ();
6882 /* The packet buffer will be large enough for the payload;
6883 get_memory_packet_size ensures this. */
6885 /* Number if bytes that will fit. */
6886 todo = min (len, max_buf_size / 2);
6888 /* Construct "m"<memaddr>","<len>". */
6889 memaddr = remote_address_masked (memaddr);
6892 p += hexnumstr (p, (ULONGEST) memaddr);
6894 p += hexnumstr (p, (ULONGEST) todo);
6897 getpkt (&rs->buf, &rs->buf_size, 0);
6898 if (rs->buf[0] == 'E'
6899 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6900 && rs->buf[3] == '\0')
6901 return TARGET_XFER_E_IO;
6902 /* Reply describes memory byte by byte, each byte encoded as two hex
6905 i = hex2bin (p, myaddr, todo);
6906 /* Return what we have. Let higher layers handle partial reads. */
6907 *xfered_len = (ULONGEST) i;
6908 return TARGET_XFER_OK;
6911 /* Using the set of read-only target sections of remote, read live
6914 For interface/parameters/return description see target.h,
6917 static enum target_xfer_status
6918 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6919 ULONGEST memaddr, ULONGEST len,
6920 ULONGEST *xfered_len)
6922 struct target_section *secp;
6923 struct target_section_table *table;
6925 secp = target_section_by_addr (ops, memaddr);
6927 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6928 secp->the_bfd_section)
6931 struct target_section *p;
6932 ULONGEST memend = memaddr + len;
6934 table = target_get_section_table (ops);
6936 for (p = table->sections; p < table->sections_end; p++)
6938 if (memaddr >= p->addr)
6940 if (memend <= p->endaddr)
6942 /* Entire transfer is within this section. */
6943 return remote_read_bytes_1 (memaddr, readbuf, len,
6946 else if (memaddr >= p->endaddr)
6948 /* This section ends before the transfer starts. */
6953 /* This section overlaps the transfer. Just do half. */
6954 len = p->endaddr - memaddr;
6955 return remote_read_bytes_1 (memaddr, readbuf, len,
6962 return TARGET_XFER_EOF;
6965 /* Similar to remote_read_bytes_1, but it reads from the remote stub
6966 first if the requested memory is unavailable in traceframe.
6967 Otherwise, fall back to remote_read_bytes_1. */
6969 static enum target_xfer_status
6970 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6971 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
6974 return TARGET_XFER_EOF;
6976 if (get_traceframe_number () != -1)
6978 VEC(mem_range_s) *available;
6980 /* If we fail to get the set of available memory, then the
6981 target does not support querying traceframe info, and so we
6982 attempt reading from the traceframe anyway (assuming the
6983 target implements the old QTro packet then). */
6984 if (traceframe_available_memory (&available, memaddr, len))
6986 struct cleanup *old_chain;
6988 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6990 if (VEC_empty (mem_range_s, available)
6991 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6993 enum target_xfer_status res;
6995 /* Don't read into the traceframe's available
6997 if (!VEC_empty (mem_range_s, available))
6999 LONGEST oldlen = len;
7001 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7002 gdb_assert (len <= oldlen);
7005 do_cleanups (old_chain);
7007 /* This goes through the topmost target again. */
7008 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7010 if (res == TARGET_XFER_OK)
7011 return TARGET_XFER_OK;
7014 /* No use trying further, we know some memory starting
7015 at MEMADDR isn't available. */
7017 return TARGET_XFER_UNAVAILABLE;
7021 /* Don't try to read more than how much is available, in
7022 case the target implements the deprecated QTro packet to
7023 cater for older GDBs (the target's knowledge of read-only
7024 sections may be outdated by now). */
7025 len = VEC_index (mem_range_s, available, 0)->length;
7027 do_cleanups (old_chain);
7031 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
7036 /* Sends a packet with content determined by the printf format string
7037 FORMAT and the remaining arguments, then gets the reply. Returns
7038 whether the packet was a success, a failure, or unknown. */
7040 static enum packet_result remote_send_printf (const char *format, ...)
7041 ATTRIBUTE_PRINTF (1, 2);
7043 static enum packet_result
7044 remote_send_printf (const char *format, ...)
7046 struct remote_state *rs = get_remote_state ();
7047 int max_size = get_remote_packet_size ();
7050 va_start (ap, format);
7053 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7054 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7056 if (putpkt (rs->buf) < 0)
7057 error (_("Communication problem with target."));
7060 getpkt (&rs->buf, &rs->buf_size, 0);
7062 return packet_check_result (rs->buf);
7066 restore_remote_timeout (void *p)
7068 int value = *(int *)p;
7070 remote_timeout = value;
7073 /* Flash writing can take quite some time. We'll set
7074 effectively infinite timeout for flash operations.
7075 In future, we'll need to decide on a better approach. */
7076 static const int remote_flash_timeout = 1000;
7079 remote_flash_erase (struct target_ops *ops,
7080 ULONGEST address, LONGEST length)
7082 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7083 int saved_remote_timeout = remote_timeout;
7084 enum packet_result ret;
7085 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7086 &saved_remote_timeout);
7088 remote_timeout = remote_flash_timeout;
7090 ret = remote_send_printf ("vFlashErase:%s,%s",
7091 phex (address, addr_size),
7095 case PACKET_UNKNOWN:
7096 error (_("Remote target does not support flash erase"));
7098 error (_("Error erasing flash with vFlashErase packet"));
7103 do_cleanups (back_to);
7106 static enum target_xfer_status
7107 remote_flash_write (struct target_ops *ops, ULONGEST address,
7108 ULONGEST length, ULONGEST *xfered_len,
7109 const gdb_byte *data)
7111 int saved_remote_timeout = remote_timeout;
7112 enum target_xfer_status ret;
7113 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7114 &saved_remote_timeout);
7116 remote_timeout = remote_flash_timeout;
7117 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7119 do_cleanups (back_to);
7125 remote_flash_done (struct target_ops *ops)
7127 int saved_remote_timeout = remote_timeout;
7129 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7130 &saved_remote_timeout);
7132 remote_timeout = remote_flash_timeout;
7133 ret = remote_send_printf ("vFlashDone");
7134 do_cleanups (back_to);
7138 case PACKET_UNKNOWN:
7139 error (_("Remote target does not support vFlashDone"));
7141 error (_("Error finishing flash operation"));
7148 remote_files_info (struct target_ops *ignore)
7150 puts_filtered ("Debugging a target over a serial line.\n");
7153 /* Stuff for dealing with the packets which are part of this protocol.
7154 See comment at top of file for details. */
7156 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7157 error to higher layers. Called when a serial error is detected.
7158 The exception message is STRING, followed by a colon and a blank,
7159 the system error message for errno at function entry and final dot
7160 for output compatibility with throw_perror_with_name. */
7163 unpush_and_perror (const char *string)
7165 int saved_errno = errno;
7167 remote_unpush_target ();
7168 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7169 safe_strerror (saved_errno));
7172 /* Read a single character from the remote end. */
7175 readchar (int timeout)
7178 struct remote_state *rs = get_remote_state ();
7180 ch = serial_readchar (rs->remote_desc, timeout);
7185 switch ((enum serial_rc) ch)
7188 remote_unpush_target ();
7189 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7192 unpush_and_perror (_("Remote communication error. "
7193 "Target disconnected."));
7195 case SERIAL_TIMEOUT:
7201 /* Wrapper for serial_write that closes the target and throws if
7205 remote_serial_write (const char *str, int len)
7207 struct remote_state *rs = get_remote_state ();
7209 if (serial_write (rs->remote_desc, str, len))
7211 unpush_and_perror (_("Remote communication error. "
7212 "Target disconnected."));
7216 /* Send the command in *BUF to the remote machine, and read the reply
7217 into *BUF. Report an error if we get an error reply. Resize
7218 *BUF using xrealloc if necessary to hold the result, and update
7222 remote_send (char **buf,
7226 getpkt (buf, sizeof_buf, 0);
7228 if ((*buf)[0] == 'E')
7229 error (_("Remote failure reply: %s"), *buf);
7232 /* Return a pointer to an xmalloc'ed string representing an escaped
7233 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7234 etc. The caller is responsible for releasing the returned
7238 escape_buffer (const char *buf, int n)
7240 struct cleanup *old_chain;
7241 struct ui_file *stb;
7244 stb = mem_fileopen ();
7245 old_chain = make_cleanup_ui_file_delete (stb);
7247 fputstrn_unfiltered (buf, n, '\\', stb);
7248 str = ui_file_xstrdup (stb, NULL);
7249 do_cleanups (old_chain);
7253 /* Display a null-terminated packet on stdout, for debugging, using C
7257 print_packet (const char *buf)
7259 puts_filtered ("\"");
7260 fputstr_filtered (buf, '"', gdb_stdout);
7261 puts_filtered ("\"");
7265 putpkt (const char *buf)
7267 return putpkt_binary (buf, strlen (buf));
7270 /* Send a packet to the remote machine, with error checking. The data
7271 of the packet is in BUF. The string in BUF can be at most
7272 get_remote_packet_size () - 5 to account for the $, # and checksum,
7273 and for a possible /0 if we are debugging (remote_debug) and want
7274 to print the sent packet as a string. */
7277 putpkt_binary (const char *buf, int cnt)
7279 struct remote_state *rs = get_remote_state ();
7281 unsigned char csum = 0;
7282 char *buf2 = alloca (cnt + 6);
7289 /* Catch cases like trying to read memory or listing threads while
7290 we're waiting for a stop reply. The remote server wouldn't be
7291 ready to handle this request, so we'd hang and timeout. We don't
7292 have to worry about this in synchronous mode, because in that
7293 case it's not possible to issue a command while the target is
7294 running. This is not a problem in non-stop mode, because in that
7295 case, the stub is always ready to process serial input. */
7296 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7298 error (_("Cannot execute this command while the target is running.\n"
7299 "Use the \"interrupt\" command to stop the target\n"
7300 "and then try again."));
7303 /* We're sending out a new packet. Make sure we don't look at a
7304 stale cached response. */
7305 rs->cached_wait_status = 0;
7307 /* Copy the packet into buffer BUF2, encapsulating it
7308 and giving it a checksum. */
7313 for (i = 0; i < cnt; i++)
7319 *p++ = tohex ((csum >> 4) & 0xf);
7320 *p++ = tohex (csum & 0xf);
7322 /* Send it over and over until we get a positive ack. */
7326 int started_error_output = 0;
7330 struct cleanup *old_chain;
7334 str = escape_buffer (buf2, p - buf2);
7335 old_chain = make_cleanup (xfree, str);
7336 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7337 gdb_flush (gdb_stdlog);
7338 do_cleanups (old_chain);
7340 remote_serial_write (buf2, p - buf2);
7342 /* If this is a no acks version of the remote protocol, send the
7343 packet and move on. */
7347 /* Read until either a timeout occurs (-2) or '+' is read.
7348 Handle any notification that arrives in the mean time. */
7351 ch = readchar (remote_timeout);
7359 case SERIAL_TIMEOUT:
7362 if (started_error_output)
7364 putchar_unfiltered ('\n');
7365 started_error_output = 0;
7374 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7378 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7380 case SERIAL_TIMEOUT:
7384 break; /* Retransmit buffer. */
7388 fprintf_unfiltered (gdb_stdlog,
7389 "Packet instead of Ack, ignoring it\n");
7390 /* It's probably an old response sent because an ACK
7391 was lost. Gobble up the packet and ack it so it
7392 doesn't get retransmitted when we resend this
7395 remote_serial_write ("+", 1);
7396 continue; /* Now, go look for +. */
7403 /* If we got a notification, handle it, and go back to looking
7405 /* We've found the start of a notification. Now
7406 collect the data. */
7407 val = read_frame (&rs->buf, &rs->buf_size);
7412 struct cleanup *old_chain;
7415 str = escape_buffer (rs->buf, val);
7416 old_chain = make_cleanup (xfree, str);
7417 fprintf_unfiltered (gdb_stdlog,
7418 " Notification received: %s\n",
7420 do_cleanups (old_chain);
7422 handle_notification (rs->notif_state, rs->buf);
7423 /* We're in sync now, rewait for the ack. */
7430 if (!started_error_output)
7432 started_error_output = 1;
7433 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7435 fputc_unfiltered (ch & 0177, gdb_stdlog);
7436 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7445 if (!started_error_output)
7447 started_error_output = 1;
7448 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7450 fputc_unfiltered (ch & 0177, gdb_stdlog);
7454 break; /* Here to retransmit. */
7458 /* This is wrong. If doing a long backtrace, the user should be
7459 able to get out next time we call QUIT, without anything as
7460 violent as interrupt_query. If we want to provide a way out of
7461 here without getting to the next QUIT, it should be based on
7462 hitting ^C twice as in remote_wait. */
7473 /* Come here after finding the start of a frame when we expected an
7474 ack. Do our best to discard the rest of this packet. */
7483 c = readchar (remote_timeout);
7486 case SERIAL_TIMEOUT:
7487 /* Nothing we can do. */
7490 /* Discard the two bytes of checksum and stop. */
7491 c = readchar (remote_timeout);
7493 c = readchar (remote_timeout);
7496 case '*': /* Run length encoding. */
7497 /* Discard the repeat count. */
7498 c = readchar (remote_timeout);
7503 /* A regular character. */
7509 /* Come here after finding the start of the frame. Collect the rest
7510 into *BUF, verifying the checksum, length, and handling run-length
7511 compression. NUL terminate the buffer. If there is not enough room,
7512 expand *BUF using xrealloc.
7514 Returns -1 on error, number of characters in buffer (ignoring the
7515 trailing NULL) on success. (could be extended to return one of the
7516 SERIAL status indications). */
7519 read_frame (char **buf_p,
7526 struct remote_state *rs = get_remote_state ();
7533 c = readchar (remote_timeout);
7536 case SERIAL_TIMEOUT:
7538 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7542 fputs_filtered ("Saw new packet start in middle of old one\n",
7544 return -1; /* Start a new packet, count retries. */
7547 unsigned char pktcsum;
7553 check_0 = readchar (remote_timeout);
7555 check_1 = readchar (remote_timeout);
7557 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7560 fputs_filtered ("Timeout in checksum, retrying\n",
7564 else if (check_0 < 0 || check_1 < 0)
7567 fputs_filtered ("Communication error in checksum\n",
7572 /* Don't recompute the checksum; with no ack packets we
7573 don't have any way to indicate a packet retransmission
7578 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7579 if (csum == pktcsum)
7584 struct cleanup *old_chain;
7587 str = escape_buffer (buf, bc);
7588 old_chain = make_cleanup (xfree, str);
7589 fprintf_unfiltered (gdb_stdlog,
7590 "Bad checksum, sentsum=0x%x, "
7591 "csum=0x%x, buf=%s\n",
7592 pktcsum, csum, str);
7593 do_cleanups (old_chain);
7595 /* Number of characters in buffer ignoring trailing
7599 case '*': /* Run length encoding. */
7604 c = readchar (remote_timeout);
7606 repeat = c - ' ' + 3; /* Compute repeat count. */
7608 /* The character before ``*'' is repeated. */
7610 if (repeat > 0 && repeat <= 255 && bc > 0)
7612 if (bc + repeat - 1 >= *sizeof_buf - 1)
7614 /* Make some more room in the buffer. */
7615 *sizeof_buf += repeat;
7616 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7620 memset (&buf[bc], buf[bc - 1], repeat);
7626 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7630 if (bc >= *sizeof_buf - 1)
7632 /* Make some more room in the buffer. */
7634 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7645 /* Read a packet from the remote machine, with error checking, and
7646 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7647 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7648 rather than timing out; this is used (in synchronous mode) to wait
7649 for a target that is is executing user code to stop. */
7650 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7651 don't have to change all the calls to getpkt to deal with the
7652 return value, because at the moment I don't know what the right
7653 thing to do it for those. */
7661 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7665 /* Read a packet from the remote machine, with error checking, and
7666 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7667 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7668 rather than timing out; this is used (in synchronous mode) to wait
7669 for a target that is is executing user code to stop. If FOREVER ==
7670 0, this function is allowed to time out gracefully and return an
7671 indication of this to the caller. Otherwise return the number of
7672 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7673 enough reason to return to the caller. *IS_NOTIF is an output
7674 boolean that indicates whether *BUF holds a notification or not
7675 (a regular packet). */
7678 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7679 int expecting_notif, int *is_notif)
7681 struct remote_state *rs = get_remote_state ();
7687 /* We're reading a new response. Make sure we don't look at a
7688 previously cached response. */
7689 rs->cached_wait_status = 0;
7691 strcpy (*buf, "timeout");
7694 timeout = watchdog > 0 ? watchdog : -1;
7695 else if (expecting_notif)
7696 timeout = 0; /* There should already be a char in the buffer. If
7699 timeout = remote_timeout;
7703 /* Process any number of notifications, and then return when
7707 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
7709 for (tries = 1; tries <= MAX_TRIES; tries++)
7711 /* This can loop forever if the remote side sends us
7712 characters continuously, but if it pauses, we'll get
7713 SERIAL_TIMEOUT from readchar because of timeout. Then
7714 we'll count that as a retry.
7716 Note that even when forever is set, we will only wait
7717 forever prior to the start of a packet. After that, we
7718 expect characters to arrive at a brisk pace. They should
7719 show up within remote_timeout intervals. */
7721 c = readchar (timeout);
7722 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7724 if (c == SERIAL_TIMEOUT)
7726 if (expecting_notif)
7727 return -1; /* Don't complain, it's normal to not get
7728 anything in this case. */
7730 if (forever) /* Watchdog went off? Kill the target. */
7733 remote_unpush_target ();
7734 throw_error (TARGET_CLOSE_ERROR,
7735 _("Watchdog timeout has expired. "
7736 "Target detached."));
7739 fputs_filtered ("Timed out.\n", gdb_stdlog);
7743 /* We've found the start of a packet or notification.
7744 Now collect the data. */
7745 val = read_frame (buf, sizeof_buf);
7750 remote_serial_write ("-", 1);
7753 if (tries > MAX_TRIES)
7755 /* We have tried hard enough, and just can't receive the
7756 packet/notification. Give up. */
7757 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7759 /* Skip the ack char if we're in no-ack mode. */
7760 if (!rs->noack_mode)
7761 remote_serial_write ("+", 1);
7765 /* If we got an ordinary packet, return that to our caller. */
7770 struct cleanup *old_chain;
7773 str = escape_buffer (*buf, val);
7774 old_chain = make_cleanup (xfree, str);
7775 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7776 do_cleanups (old_chain);
7779 /* Skip the ack char if we're in no-ack mode. */
7780 if (!rs->noack_mode)
7781 remote_serial_write ("+", 1);
7782 if (is_notif != NULL)
7787 /* If we got a notification, handle it, and go back to looking
7791 gdb_assert (c == '%');
7795 struct cleanup *old_chain;
7798 str = escape_buffer (*buf, val);
7799 old_chain = make_cleanup (xfree, str);
7800 fprintf_unfiltered (gdb_stdlog,
7801 " Notification received: %s\n",
7803 do_cleanups (old_chain);
7805 if (is_notif != NULL)
7808 handle_notification (rs->notif_state, *buf);
7810 /* Notifications require no acknowledgement. */
7812 if (expecting_notif)
7819 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7821 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7825 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7828 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7834 remote_kill (struct target_ops *ops)
7837 /* Catch errors so the user can quit from gdb even when we
7838 aren't on speaking terms with the remote system. */
7843 CATCH (ex, RETURN_MASK_ERROR)
7845 if (ex.error == TARGET_CLOSE_ERROR)
7847 /* If we got an (EOF) error that caused the target
7848 to go away, then we're done, that's what we wanted.
7849 "k" is susceptible to cause a premature EOF, given
7850 that the remote server isn't actually required to
7851 reply to "k", and it can happen that it doesn't
7852 even get to reply ACK to the "k". */
7856 /* Otherwise, something went wrong. We didn't actually kill
7857 the target. Just propagate the exception, and let the
7858 user or higher layers decide what to do. */
7859 throw_exception (ex);
7863 /* We've killed the remote end, we get to mourn it. Since this is
7864 target remote, single-process, mourning the inferior also
7865 unpushes remote_ops. */
7866 target_mourn_inferior ();
7870 remote_vkill (int pid, struct remote_state *rs)
7872 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
7875 /* Tell the remote target to detach. */
7876 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7878 getpkt (&rs->buf, &rs->buf_size, 0);
7880 switch (packet_ok (rs->buf,
7881 &remote_protocol_packets[PACKET_vKill]))
7887 case PACKET_UNKNOWN:
7890 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7895 extended_remote_kill (struct target_ops *ops)
7898 int pid = ptid_get_pid (inferior_ptid);
7899 struct remote_state *rs = get_remote_state ();
7901 res = remote_vkill (pid, rs);
7902 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7904 /* Don't try 'k' on a multi-process aware stub -- it has no way
7905 to specify the pid. */
7909 getpkt (&rs->buf, &rs->buf_size, 0);
7910 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7913 /* Don't wait for it to die. I'm not really sure it matters whether
7914 we do or not. For the existing stubs, kill is a noop. */
7920 error (_("Can't kill process"));
7922 target_mourn_inferior ();
7926 remote_mourn (struct target_ops *target)
7928 unpush_target (target);
7930 /* remote_close takes care of doing most of the clean up. */
7931 generic_mourn_inferior ();
7935 extended_remote_mourn (struct target_ops *target)
7937 struct remote_state *rs = get_remote_state ();
7939 /* In case we got here due to an error, but we're going to stay
7941 rs->waiting_for_stop_reply = 0;
7943 /* If the current general thread belonged to the process we just
7944 detached from or has exited, the remote side current general
7945 thread becomes undefined. Considering a case like this:
7947 - We just got here due to a detach.
7948 - The process that we're detaching from happens to immediately
7949 report a global breakpoint being hit in non-stop mode, in the
7950 same thread we had selected before.
7951 - GDB attaches to this process again.
7952 - This event happens to be the next event we handle.
7954 GDB would consider that the current general thread didn't need to
7955 be set on the stub side (with Hg), since for all it knew,
7956 GENERAL_THREAD hadn't changed.
7958 Notice that although in all-stop mode, the remote server always
7959 sets the current thread to the thread reporting the stop event,
7960 that doesn't happen in non-stop mode; in non-stop, the stub *must
7961 not* change the current thread when reporting a breakpoint hit,
7962 due to the decoupling of event reporting and event handling.
7964 To keep things simple, we always invalidate our notion of the
7966 record_currthread (rs, minus_one_ptid);
7968 /* Unlike "target remote", we do not want to unpush the target; then
7969 the next time the user says "run", we won't be connected. */
7971 /* Call common code to mark the inferior as not running. */
7972 generic_mourn_inferior ();
7974 if (!have_inferiors ())
7976 if (!remote_multi_process_p (rs))
7978 /* Check whether the target is running now - some remote stubs
7979 automatically restart after kill. */
7981 getpkt (&rs->buf, &rs->buf_size, 0);
7983 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7985 /* Assume that the target has been restarted. Set
7986 inferior_ptid so that bits of core GDB realizes
7987 there's something here, e.g., so that the user can
7988 say "kill" again. */
7989 inferior_ptid = magic_null_ptid;
7996 extended_remote_supports_disable_randomization (struct target_ops *self)
7998 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8002 extended_remote_disable_randomization (int val)
8004 struct remote_state *rs = get_remote_state ();
8007 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8010 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8012 error (_("Target does not support QDisableRandomization."));
8013 if (strcmp (reply, "OK") != 0)
8014 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8018 extended_remote_run (char *args)
8020 struct remote_state *rs = get_remote_state ();
8023 /* If the user has disabled vRun support, or we have detected that
8024 support is not available, do not try it. */
8025 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8028 strcpy (rs->buf, "vRun;");
8029 len = strlen (rs->buf);
8031 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8032 error (_("Remote file name too long for run packet"));
8033 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8034 strlen (remote_exec_file));
8036 gdb_assert (args != NULL);
8039 struct cleanup *back_to;
8043 argv = gdb_buildargv (args);
8044 back_to = make_cleanup_freeargv (argv);
8045 for (i = 0; argv[i] != NULL; i++)
8047 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8048 error (_("Argument list too long for run packet"));
8049 rs->buf[len++] = ';';
8050 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8053 do_cleanups (back_to);
8056 rs->buf[len++] = '\0';
8059 getpkt (&rs->buf, &rs->buf_size, 0);
8061 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8064 /* We have a wait response. All is well. */
8066 case PACKET_UNKNOWN:
8069 if (remote_exec_file[0] == '\0')
8070 error (_("Running the default executable on the remote target failed; "
8071 "try \"set remote exec-file\"?"));
8073 error (_("Running \"%s\" on the remote target failed"),
8076 gdb_assert_not_reached (_("bad switch"));
8080 /* In the extended protocol we want to be able to do things like
8081 "run" and have them basically work as expected. So we need
8082 a special create_inferior function. We support changing the
8083 executable file and the command line arguments, but not the
8087 extended_remote_create_inferior (struct target_ops *ops,
8088 char *exec_file, char *args,
8089 char **env, int from_tty)
8093 struct remote_state *rs = get_remote_state ();
8095 /* If running asynchronously, register the target file descriptor
8096 with the event loop. */
8097 if (target_can_async_p ())
8100 /* Disable address space randomization if requested (and supported). */
8101 if (extended_remote_supports_disable_randomization (ops))
8102 extended_remote_disable_randomization (disable_randomization);
8104 /* Now restart the remote server. */
8105 run_worked = extended_remote_run (args) != -1;
8108 /* vRun was not supported. Fail if we need it to do what the
8110 if (remote_exec_file[0])
8111 error (_("Remote target does not support \"set remote exec-file\""));
8113 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8115 /* Fall back to "R". */
8116 extended_remote_restart ();
8119 if (!have_inferiors ())
8121 /* Clean up from the last time we ran, before we mark the target
8122 running again. This will mark breakpoints uninserted, and
8123 get_offsets may insert breakpoints. */
8124 init_thread_list ();
8125 init_wait_for_inferior ();
8128 /* vRun's success return is a stop reply. */
8129 stop_reply = run_worked ? rs->buf : NULL;
8130 add_current_inferior_and_thread (stop_reply);
8132 /* Get updated offsets, if the stub uses qOffsets. */
8137 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8138 the list of conditions (in agent expression bytecode format), if any, the
8139 target needs to evaluate. The output is placed into the packet buffer
8140 started from BUF and ended at BUF_END. */
8143 remote_add_target_side_condition (struct gdbarch *gdbarch,
8144 struct bp_target_info *bp_tgt, char *buf,
8147 struct agent_expr *aexpr = NULL;
8150 char *buf_start = buf;
8152 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8155 buf += strlen (buf);
8156 xsnprintf (buf, buf_end - buf, "%s", ";");
8159 /* Send conditions to the target and free the vector. */
8161 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8164 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8165 buf += strlen (buf);
8166 for (i = 0; i < aexpr->len; ++i)
8167 buf = pack_hex_byte (buf, aexpr->buf[i]);
8174 remote_add_target_side_commands (struct gdbarch *gdbarch,
8175 struct bp_target_info *bp_tgt, char *buf)
8177 struct agent_expr *aexpr = NULL;
8180 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8183 buf += strlen (buf);
8185 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8186 buf += strlen (buf);
8188 /* Concatenate all the agent expressions that are commands into the
8191 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8194 sprintf (buf, "X%x,", aexpr->len);
8195 buf += strlen (buf);
8196 for (i = 0; i < aexpr->len; ++i)
8197 buf = pack_hex_byte (buf, aexpr->buf[i]);
8202 /* Insert a breakpoint. On targets that have software breakpoint
8203 support, we ask the remote target to do the work; on targets
8204 which don't, we insert a traditional memory breakpoint. */
8207 remote_insert_breakpoint (struct target_ops *ops,
8208 struct gdbarch *gdbarch,
8209 struct bp_target_info *bp_tgt)
8211 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8212 If it succeeds, then set the support to PACKET_ENABLE. If it
8213 fails, and the user has explicitly requested the Z support then
8214 report an error, otherwise, mark it disabled and go on. */
8216 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8218 CORE_ADDR addr = bp_tgt->reqstd_address;
8219 struct remote_state *rs;
8222 struct condition_list *cond = NULL;
8224 /* Make sure the remote is pointing at the right process, if
8226 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8227 set_general_process ();
8229 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8231 rs = get_remote_state ();
8233 endbuf = rs->buf + get_remote_packet_size ();
8238 addr = (ULONGEST) remote_address_masked (addr);
8239 p += hexnumstr (p, addr);
8240 xsnprintf (p, endbuf - p, ",%d", bpsize);
8242 if (remote_supports_cond_breakpoints (ops))
8243 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8245 if (remote_can_run_breakpoint_commands (ops))
8246 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8249 getpkt (&rs->buf, &rs->buf_size, 0);
8251 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8256 bp_tgt->placed_address = addr;
8257 bp_tgt->placed_size = bpsize;
8259 case PACKET_UNKNOWN:
8264 /* If this breakpoint has target-side commands but this stub doesn't
8265 support Z0 packets, throw error. */
8266 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8267 throw_error (NOT_SUPPORTED_ERROR, _("\
8268 Target doesn't support breakpoints that have target side commands."));
8270 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8274 remote_remove_breakpoint (struct target_ops *ops,
8275 struct gdbarch *gdbarch,
8276 struct bp_target_info *bp_tgt)
8278 CORE_ADDR addr = bp_tgt->placed_address;
8279 struct remote_state *rs = get_remote_state ();
8281 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8284 char *endbuf = rs->buf + get_remote_packet_size ();
8286 /* Make sure the remote is pointing at the right process, if
8288 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8289 set_general_process ();
8295 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8296 p += hexnumstr (p, addr);
8297 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8300 getpkt (&rs->buf, &rs->buf_size, 0);
8302 return (rs->buf[0] == 'E');
8305 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8309 watchpoint_to_Z_packet (int type)
8314 return Z_PACKET_WRITE_WP;
8317 return Z_PACKET_READ_WP;
8320 return Z_PACKET_ACCESS_WP;
8323 internal_error (__FILE__, __LINE__,
8324 _("hw_bp_to_z: bad watchpoint type %d"), type);
8329 remote_insert_watchpoint (struct target_ops *self,
8330 CORE_ADDR addr, int len, int type,
8331 struct expression *cond)
8333 struct remote_state *rs = get_remote_state ();
8334 char *endbuf = rs->buf + get_remote_packet_size ();
8336 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8338 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8341 /* Make sure the remote is pointing at the right process, if
8343 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8344 set_general_process ();
8346 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8347 p = strchr (rs->buf, '\0');
8348 addr = remote_address_masked (addr);
8349 p += hexnumstr (p, (ULONGEST) addr);
8350 xsnprintf (p, endbuf - p, ",%x", len);
8353 getpkt (&rs->buf, &rs->buf_size, 0);
8355 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8359 case PACKET_UNKNOWN:
8364 internal_error (__FILE__, __LINE__,
8365 _("remote_insert_watchpoint: reached end of function"));
8369 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8370 CORE_ADDR start, int length)
8372 CORE_ADDR diff = remote_address_masked (addr - start);
8374 return diff < length;
8379 remote_remove_watchpoint (struct target_ops *self,
8380 CORE_ADDR addr, int len, int type,
8381 struct expression *cond)
8383 struct remote_state *rs = get_remote_state ();
8384 char *endbuf = rs->buf + get_remote_packet_size ();
8386 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8388 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8391 /* Make sure the remote is pointing at the right process, if
8393 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8394 set_general_process ();
8396 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8397 p = strchr (rs->buf, '\0');
8398 addr = remote_address_masked (addr);
8399 p += hexnumstr (p, (ULONGEST) addr);
8400 xsnprintf (p, endbuf - p, ",%x", len);
8402 getpkt (&rs->buf, &rs->buf_size, 0);
8404 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8407 case PACKET_UNKNOWN:
8412 internal_error (__FILE__, __LINE__,
8413 _("remote_remove_watchpoint: reached end of function"));
8417 int remote_hw_watchpoint_limit = -1;
8418 int remote_hw_watchpoint_length_limit = -1;
8419 int remote_hw_breakpoint_limit = -1;
8422 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8423 CORE_ADDR addr, int len)
8425 if (remote_hw_watchpoint_length_limit == 0)
8427 else if (remote_hw_watchpoint_length_limit < 0)
8429 else if (len <= remote_hw_watchpoint_length_limit)
8436 remote_check_watch_resources (struct target_ops *self,
8437 int type, int cnt, int ot)
8439 if (type == bp_hardware_breakpoint)
8441 if (remote_hw_breakpoint_limit == 0)
8443 else if (remote_hw_breakpoint_limit < 0)
8445 else if (cnt <= remote_hw_breakpoint_limit)
8450 if (remote_hw_watchpoint_limit == 0)
8452 else if (remote_hw_watchpoint_limit < 0)
8456 else if (cnt <= remote_hw_watchpoint_limit)
8462 /* The to_stopped_by_sw_breakpoint method of target remote. */
8465 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8467 struct remote_state *rs = get_remote_state ();
8469 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8472 /* The to_supports_stopped_by_sw_breakpoint method of target
8476 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8478 struct remote_state *rs = get_remote_state ();
8480 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8483 /* The to_stopped_by_hw_breakpoint method of target remote. */
8486 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8488 struct remote_state *rs = get_remote_state ();
8490 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8493 /* The to_supports_stopped_by_hw_breakpoint method of target
8497 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8499 struct remote_state *rs = get_remote_state ();
8501 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8505 remote_stopped_by_watchpoint (struct target_ops *ops)
8507 struct remote_state *rs = get_remote_state ();
8509 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
8513 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8515 struct remote_state *rs = get_remote_state ();
8518 if (remote_stopped_by_watchpoint (target))
8520 *addr_p = rs->remote_watch_data_address;
8529 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8530 struct bp_target_info *bp_tgt)
8532 CORE_ADDR addr = bp_tgt->reqstd_address;
8533 struct remote_state *rs;
8538 /* The length field should be set to the size of a breakpoint
8539 instruction, even though we aren't inserting one ourselves. */
8541 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8543 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8546 /* Make sure the remote is pointing at the right process, if
8548 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8549 set_general_process ();
8551 rs = get_remote_state ();
8553 endbuf = rs->buf + get_remote_packet_size ();
8559 addr = remote_address_masked (addr);
8560 p += hexnumstr (p, (ULONGEST) addr);
8561 xsnprintf (p, endbuf - p, ",%x", bpsize);
8563 if (remote_supports_cond_breakpoints (self))
8564 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8566 if (remote_can_run_breakpoint_commands (self))
8567 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8570 getpkt (&rs->buf, &rs->buf_size, 0);
8572 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8575 if (rs->buf[1] == '.')
8577 message = strchr (rs->buf + 2, '.');
8579 error (_("Remote failure reply: %s"), message + 1);
8582 case PACKET_UNKNOWN:
8585 bp_tgt->placed_address = addr;
8586 bp_tgt->placed_size = bpsize;
8589 internal_error (__FILE__, __LINE__,
8590 _("remote_insert_hw_breakpoint: reached end of function"));
8595 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8596 struct bp_target_info *bp_tgt)
8599 struct remote_state *rs = get_remote_state ();
8601 char *endbuf = rs->buf + get_remote_packet_size ();
8603 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8606 /* Make sure the remote is pointing at the right process, if
8608 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8609 set_general_process ();
8615 addr = remote_address_masked (bp_tgt->placed_address);
8616 p += hexnumstr (p, (ULONGEST) addr);
8617 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8620 getpkt (&rs->buf, &rs->buf_size, 0);
8622 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8625 case PACKET_UNKNOWN:
8630 internal_error (__FILE__, __LINE__,
8631 _("remote_remove_hw_breakpoint: reached end of function"));
8634 /* Verify memory using the "qCRC:" request. */
8637 remote_verify_memory (struct target_ops *ops,
8638 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8640 struct remote_state *rs = get_remote_state ();
8641 unsigned long host_crc, target_crc;
8644 /* It doesn't make sense to use qCRC if the remote target is
8645 connected but not running. */
8646 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8648 enum packet_result result;
8650 /* Make sure the remote is pointing at the right process. */
8651 set_general_process ();
8653 /* FIXME: assumes lma can fit into long. */
8654 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8655 (long) lma, (long) size);
8658 /* Be clever; compute the host_crc before waiting for target
8660 host_crc = xcrc32 (data, size, 0xffffffff);
8662 getpkt (&rs->buf, &rs->buf_size, 0);
8664 result = packet_ok (rs->buf,
8665 &remote_protocol_packets[PACKET_qCRC]);
8666 if (result == PACKET_ERROR)
8668 else if (result == PACKET_OK)
8670 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8671 target_crc = target_crc * 16 + fromhex (*tmp);
8673 return (host_crc == target_crc);
8677 return simple_verify_memory (ops, data, lma, size);
8680 /* compare-sections command
8682 With no arguments, compares each loadable section in the exec bfd
8683 with the same memory range on the target, and reports mismatches.
8684 Useful for verifying the image on the target against the exec file. */
8687 compare_sections_command (char *args, int from_tty)
8690 struct cleanup *old_chain;
8692 const char *sectname;
8701 error (_("command cannot be used without an exec file"));
8703 /* Make sure the remote is pointing at the right process. */
8704 set_general_process ();
8706 if (args != NULL && strcmp (args, "-r") == 0)
8712 for (s = exec_bfd->sections; s; s = s->next)
8714 if (!(s->flags & SEC_LOAD))
8715 continue; /* Skip non-loadable section. */
8717 if (read_only && (s->flags & SEC_READONLY) == 0)
8718 continue; /* Skip writeable sections */
8720 size = bfd_get_section_size (s);
8722 continue; /* Skip zero-length section. */
8724 sectname = bfd_get_section_name (exec_bfd, s);
8725 if (args && strcmp (args, sectname) != 0)
8726 continue; /* Not the section selected by user. */
8728 matched = 1; /* Do this section. */
8731 sectdata = xmalloc (size);
8732 old_chain = make_cleanup (xfree, sectdata);
8733 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8735 res = target_verify_memory (sectdata, lma, size);
8738 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8739 paddress (target_gdbarch (), lma),
8740 paddress (target_gdbarch (), lma + size));
8742 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8743 paddress (target_gdbarch (), lma),
8744 paddress (target_gdbarch (), lma + size));
8746 printf_filtered ("matched.\n");
8749 printf_filtered ("MIS-MATCHED!\n");
8753 do_cleanups (old_chain);
8756 warning (_("One or more sections of the target image does not match\n\
8757 the loaded file\n"));
8758 if (args && !matched)
8759 printf_filtered (_("No loaded section named '%s'.\n"), args);
8762 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8763 into remote target. The number of bytes written to the remote
8764 target is returned, or -1 for error. */
8766 static enum target_xfer_status
8767 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8768 const char *annex, const gdb_byte *writebuf,
8769 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
8770 struct packet_config *packet)
8774 struct remote_state *rs = get_remote_state ();
8775 int max_size = get_memory_write_packet_size ();
8777 if (packet->support == PACKET_DISABLE)
8778 return TARGET_XFER_E_IO;
8780 /* Insert header. */
8781 i = snprintf (rs->buf, max_size,
8782 "qXfer:%s:write:%s:%s:",
8783 object_name, annex ? annex : "",
8784 phex_nz (offset, sizeof offset));
8785 max_size -= (i + 1);
8787 /* Escape as much data as fits into rs->buf. */
8788 buf_len = remote_escape_output
8789 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8791 if (putpkt_binary (rs->buf, i + buf_len) < 0
8792 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8793 || packet_ok (rs->buf, packet) != PACKET_OK)
8794 return TARGET_XFER_E_IO;
8796 unpack_varlen_hex (rs->buf, &n);
8799 return TARGET_XFER_OK;
8802 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8803 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8804 number of bytes read is returned, or 0 for EOF, or -1 for error.
8805 The number of bytes read may be less than LEN without indicating an
8806 EOF. PACKET is checked and updated to indicate whether the remote
8807 target supports this object. */
8809 static enum target_xfer_status
8810 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8812 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8813 ULONGEST *xfered_len,
8814 struct packet_config *packet)
8816 struct remote_state *rs = get_remote_state ();
8817 LONGEST i, n, packet_len;
8819 if (packet->support == PACKET_DISABLE)
8820 return TARGET_XFER_E_IO;
8822 /* Check whether we've cached an end-of-object packet that matches
8824 if (rs->finished_object)
8826 if (strcmp (object_name, rs->finished_object) == 0
8827 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8828 && offset == rs->finished_offset)
8829 return TARGET_XFER_EOF;
8832 /* Otherwise, we're now reading something different. Discard
8834 xfree (rs->finished_object);
8835 xfree (rs->finished_annex);
8836 rs->finished_object = NULL;
8837 rs->finished_annex = NULL;
8840 /* Request only enough to fit in a single packet. The actual data
8841 may not, since we don't know how much of it will need to be escaped;
8842 the target is free to respond with slightly less data. We subtract
8843 five to account for the response type and the protocol frame. */
8844 n = min (get_remote_packet_size () - 5, len);
8845 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8846 object_name, annex ? annex : "",
8847 phex_nz (offset, sizeof offset),
8848 phex_nz (n, sizeof n));
8849 i = putpkt (rs->buf);
8851 return TARGET_XFER_E_IO;
8854 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8855 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8856 return TARGET_XFER_E_IO;
8858 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8859 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8861 /* 'm' means there is (or at least might be) more data after this
8862 batch. That does not make sense unless there's at least one byte
8863 of data in this reply. */
8864 if (rs->buf[0] == 'm' && packet_len == 1)
8865 error (_("Remote qXfer reply contained no data."));
8867 /* Got some data. */
8868 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8869 packet_len - 1, readbuf, n);
8871 /* 'l' is an EOF marker, possibly including a final block of data,
8872 or possibly empty. If we have the final block of a non-empty
8873 object, record this fact to bypass a subsequent partial read. */
8874 if (rs->buf[0] == 'l' && offset + i > 0)
8876 rs->finished_object = xstrdup (object_name);
8877 rs->finished_annex = xstrdup (annex ? annex : "");
8878 rs->finished_offset = offset + i;
8882 return TARGET_XFER_EOF;
8886 return TARGET_XFER_OK;
8890 static enum target_xfer_status
8891 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8892 const char *annex, gdb_byte *readbuf,
8893 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8894 ULONGEST *xfered_len)
8896 struct remote_state *rs;
8901 set_remote_traceframe ();
8902 set_general_thread (inferior_ptid);
8904 rs = get_remote_state ();
8906 /* Handle memory using the standard memory routines. */
8907 if (object == TARGET_OBJECT_MEMORY)
8909 /* If the remote target is connected but not running, we should
8910 pass this request down to a lower stratum (e.g. the executable
8912 if (!target_has_execution)
8913 return TARGET_XFER_EOF;
8915 if (writebuf != NULL)
8916 return remote_write_bytes (offset, writebuf, len, xfered_len);
8918 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
8921 /* Handle SPU memory using qxfer packets. */
8922 if (object == TARGET_OBJECT_SPU)
8925 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8926 xfered_len, &remote_protocol_packets
8927 [PACKET_qXfer_spu_read]);
8929 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8930 xfered_len, &remote_protocol_packets
8931 [PACKET_qXfer_spu_write]);
8934 /* Handle extra signal info using qxfer packets. */
8935 if (object == TARGET_OBJECT_SIGNAL_INFO)
8938 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8939 xfered_len, &remote_protocol_packets
8940 [PACKET_qXfer_siginfo_read]);
8942 return remote_write_qxfer (ops, "siginfo", annex,
8943 writebuf, offset, len, xfered_len,
8944 &remote_protocol_packets
8945 [PACKET_qXfer_siginfo_write]);
8948 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8951 return remote_read_qxfer (ops, "statictrace", annex,
8952 readbuf, offset, len, xfered_len,
8953 &remote_protocol_packets
8954 [PACKET_qXfer_statictrace_read]);
8956 return TARGET_XFER_E_IO;
8959 /* Only handle flash writes. */
8960 if (writebuf != NULL)
8966 case TARGET_OBJECT_FLASH:
8967 return remote_flash_write (ops, offset, len, xfered_len,
8971 return TARGET_XFER_E_IO;
8975 /* Map pre-existing objects onto letters. DO NOT do this for new
8976 objects!!! Instead specify new query packets. */
8979 case TARGET_OBJECT_AVR:
8983 case TARGET_OBJECT_AUXV:
8984 gdb_assert (annex == NULL);
8985 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8987 &remote_protocol_packets[PACKET_qXfer_auxv]);
8989 case TARGET_OBJECT_AVAILABLE_FEATURES:
8990 return remote_read_qxfer
8991 (ops, "features", annex, readbuf, offset, len, xfered_len,
8992 &remote_protocol_packets[PACKET_qXfer_features]);
8994 case TARGET_OBJECT_LIBRARIES:
8995 return remote_read_qxfer
8996 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
8997 &remote_protocol_packets[PACKET_qXfer_libraries]);
8999 case TARGET_OBJECT_LIBRARIES_SVR4:
9000 return remote_read_qxfer
9001 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9002 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9004 case TARGET_OBJECT_MEMORY_MAP:
9005 gdb_assert (annex == NULL);
9006 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9008 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9010 case TARGET_OBJECT_OSDATA:
9011 /* Should only get here if we're connected. */
9012 gdb_assert (rs->remote_desc);
9013 return remote_read_qxfer
9014 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9015 &remote_protocol_packets[PACKET_qXfer_osdata]);
9017 case TARGET_OBJECT_THREADS:
9018 gdb_assert (annex == NULL);
9019 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9021 &remote_protocol_packets[PACKET_qXfer_threads]);
9023 case TARGET_OBJECT_TRACEFRAME_INFO:
9024 gdb_assert (annex == NULL);
9025 return remote_read_qxfer
9026 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9027 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9029 case TARGET_OBJECT_FDPIC:
9030 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9032 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9034 case TARGET_OBJECT_OPENVMS_UIB:
9035 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9037 &remote_protocol_packets[PACKET_qXfer_uib]);
9039 case TARGET_OBJECT_BTRACE:
9040 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9042 &remote_protocol_packets[PACKET_qXfer_btrace]);
9044 case TARGET_OBJECT_BTRACE_CONF:
9045 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9047 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9049 case TARGET_OBJECT_EXEC_FILE:
9050 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9052 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9055 return TARGET_XFER_E_IO;
9058 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9059 large enough let the caller deal with it. */
9060 if (len < get_remote_packet_size ())
9061 return TARGET_XFER_E_IO;
9062 len = get_remote_packet_size ();
9064 /* Except for querying the minimum buffer size, target must be open. */
9065 if (!rs->remote_desc)
9066 error (_("remote query is only available after target open"));
9068 gdb_assert (annex != NULL);
9069 gdb_assert (readbuf != NULL);
9075 /* We used one buffer char for the remote protocol q command and
9076 another for the query type. As the remote protocol encapsulation
9077 uses 4 chars plus one extra in case we are debugging
9078 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9081 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9083 /* Bad caller may have sent forbidden characters. */
9084 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9089 gdb_assert (annex[i] == '\0');
9091 i = putpkt (rs->buf);
9093 return TARGET_XFER_E_IO;
9095 getpkt (&rs->buf, &rs->buf_size, 0);
9096 strcpy ((char *) readbuf, rs->buf);
9098 *xfered_len = strlen ((char *) readbuf);
9099 return TARGET_XFER_OK;
9103 remote_search_memory (struct target_ops* ops,
9104 CORE_ADDR start_addr, ULONGEST search_space_len,
9105 const gdb_byte *pattern, ULONGEST pattern_len,
9106 CORE_ADDR *found_addrp)
9108 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9109 struct remote_state *rs = get_remote_state ();
9110 int max_size = get_memory_write_packet_size ();
9111 struct packet_config *packet =
9112 &remote_protocol_packets[PACKET_qSearch_memory];
9113 /* Number of packet bytes used to encode the pattern;
9114 this could be more than PATTERN_LEN due to escape characters. */
9115 int escaped_pattern_len;
9116 /* Amount of pattern that was encodable in the packet. */
9117 int used_pattern_len;
9120 ULONGEST found_addr;
9122 /* Don't go to the target if we don't have to.
9123 This is done before checking packet->support to avoid the possibility that
9124 a success for this edge case means the facility works in general. */
9125 if (pattern_len > search_space_len)
9127 if (pattern_len == 0)
9129 *found_addrp = start_addr;
9133 /* If we already know the packet isn't supported, fall back to the simple
9134 way of searching memory. */
9136 if (packet_config_support (packet) == PACKET_DISABLE)
9138 /* Target doesn't provided special support, fall back and use the
9139 standard support (copy memory and do the search here). */
9140 return simple_search_memory (ops, start_addr, search_space_len,
9141 pattern, pattern_len, found_addrp);
9144 /* Make sure the remote is pointing at the right process. */
9145 set_general_process ();
9147 /* Insert header. */
9148 i = snprintf (rs->buf, max_size,
9149 "qSearch:memory:%s;%s;",
9150 phex_nz (start_addr, addr_size),
9151 phex_nz (search_space_len, sizeof (search_space_len)));
9152 max_size -= (i + 1);
9154 /* Escape as much data as fits into rs->buf. */
9155 escaped_pattern_len =
9156 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9157 &used_pattern_len, max_size);
9159 /* Bail if the pattern is too large. */
9160 if (used_pattern_len != pattern_len)
9161 error (_("Pattern is too large to transmit to remote target."));
9163 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9164 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9165 || packet_ok (rs->buf, packet) != PACKET_OK)
9167 /* The request may not have worked because the command is not
9168 supported. If so, fall back to the simple way. */
9169 if (packet->support == PACKET_DISABLE)
9171 return simple_search_memory (ops, start_addr, search_space_len,
9172 pattern, pattern_len, found_addrp);
9177 if (rs->buf[0] == '0')
9179 else if (rs->buf[0] == '1')
9182 if (rs->buf[1] != ',')
9183 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9184 unpack_varlen_hex (rs->buf + 2, &found_addr);
9185 *found_addrp = found_addr;
9188 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9194 remote_rcmd (struct target_ops *self, const char *command,
9195 struct ui_file *outbuf)
9197 struct remote_state *rs = get_remote_state ();
9200 if (!rs->remote_desc)
9201 error (_("remote rcmd is only available after target open"));
9203 /* Send a NULL command across as an empty command. */
9204 if (command == NULL)
9207 /* The query prefix. */
9208 strcpy (rs->buf, "qRcmd,");
9209 p = strchr (rs->buf, '\0');
9211 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9212 > get_remote_packet_size ())
9213 error (_("\"monitor\" command ``%s'' is too long."), command);
9215 /* Encode the actual command. */
9216 bin2hex ((const gdb_byte *) command, p, strlen (command));
9218 if (putpkt (rs->buf) < 0)
9219 error (_("Communication problem with target."));
9221 /* get/display the response */
9226 /* XXX - see also remote_get_noisy_reply(). */
9227 QUIT; /* Allow user to bail out with ^C. */
9229 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9231 /* Timeout. Continue to (try to) read responses.
9232 This is better than stopping with an error, assuming the stub
9233 is still executing the (long) monitor command.
9234 If needed, the user can interrupt gdb using C-c, obtaining
9235 an effect similar to stop on timeout. */
9240 error (_("Target does not support this command."));
9241 if (buf[0] == 'O' && buf[1] != 'K')
9243 remote_console_output (buf + 1); /* 'O' message from stub. */
9246 if (strcmp (buf, "OK") == 0)
9248 if (strlen (buf) == 3 && buf[0] == 'E'
9249 && isdigit (buf[1]) && isdigit (buf[2]))
9251 error (_("Protocol error with Rcmd"));
9253 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9255 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9257 fputc_unfiltered (c, outbuf);
9263 static VEC(mem_region_s) *
9264 remote_memory_map (struct target_ops *ops)
9266 VEC(mem_region_s) *result = NULL;
9267 char *text = target_read_stralloc (¤t_target,
9268 TARGET_OBJECT_MEMORY_MAP, NULL);
9272 struct cleanup *back_to = make_cleanup (xfree, text);
9274 result = parse_memory_map (text);
9275 do_cleanups (back_to);
9282 packet_command (char *args, int from_tty)
9284 struct remote_state *rs = get_remote_state ();
9286 if (!rs->remote_desc)
9287 error (_("command can only be used with remote target"));
9290 error (_("remote-packet command requires packet text as argument"));
9292 puts_filtered ("sending: ");
9293 print_packet (args);
9294 puts_filtered ("\n");
9297 getpkt (&rs->buf, &rs->buf_size, 0);
9298 puts_filtered ("received: ");
9299 print_packet (rs->buf);
9300 puts_filtered ("\n");
9304 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9306 static void display_thread_info (struct gdb_ext_thread_info *info);
9308 static void threadset_test_cmd (char *cmd, int tty);
9310 static void threadalive_test (char *cmd, int tty);
9312 static void threadlist_test_cmd (char *cmd, int tty);
9314 int get_and_display_threadinfo (threadref *ref);
9316 static void threadinfo_test_cmd (char *cmd, int tty);
9318 static int thread_display_step (threadref *ref, void *context);
9320 static void threadlist_update_test_cmd (char *cmd, int tty);
9322 static void init_remote_threadtests (void);
9324 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9327 threadset_test_cmd (char *cmd, int tty)
9329 int sample_thread = SAMPLE_THREAD;
9331 printf_filtered (_("Remote threadset test\n"));
9332 set_general_thread (sample_thread);
9337 threadalive_test (char *cmd, int tty)
9339 int sample_thread = SAMPLE_THREAD;
9340 int pid = ptid_get_pid (inferior_ptid);
9341 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9343 if (remote_thread_alive (ptid))
9344 printf_filtered ("PASS: Thread alive test\n");
9346 printf_filtered ("FAIL: Thread alive test\n");
9349 void output_threadid (char *title, threadref *ref);
9352 output_threadid (char *title, threadref *ref)
9356 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9358 printf_filtered ("%s %s\n", title, (&hexid[0]));
9362 threadlist_test_cmd (char *cmd, int tty)
9365 threadref nextthread;
9366 int done, result_count;
9367 threadref threadlist[3];
9369 printf_filtered ("Remote Threadlist test\n");
9370 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9371 &result_count, &threadlist[0]))
9372 printf_filtered ("FAIL: threadlist test\n");
9375 threadref *scan = threadlist;
9376 threadref *limit = scan + result_count;
9378 while (scan < limit)
9379 output_threadid (" thread ", scan++);
9384 display_thread_info (struct gdb_ext_thread_info *info)
9386 output_threadid ("Threadid: ", &info->threadid);
9387 printf_filtered ("Name: %s\n ", info->shortname);
9388 printf_filtered ("State: %s\n", info->display);
9389 printf_filtered ("other: %s\n\n", info->more_display);
9393 get_and_display_threadinfo (threadref *ref)
9397 struct gdb_ext_thread_info threadinfo;
9399 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9400 | TAG_MOREDISPLAY | TAG_DISPLAY;
9401 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9402 display_thread_info (&threadinfo);
9407 threadinfo_test_cmd (char *cmd, int tty)
9409 int athread = SAMPLE_THREAD;
9413 int_to_threadref (&thread, athread);
9414 printf_filtered ("Remote Threadinfo test\n");
9415 if (!get_and_display_threadinfo (&thread))
9416 printf_filtered ("FAIL cannot get thread info\n");
9420 thread_display_step (threadref *ref, void *context)
9422 /* output_threadid(" threadstep ",ref); *//* simple test */
9423 return get_and_display_threadinfo (ref);
9427 threadlist_update_test_cmd (char *cmd, int tty)
9429 printf_filtered ("Remote Threadlist update test\n");
9430 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9434 init_remote_threadtests (void)
9436 add_com ("tlist", class_obscure, threadlist_test_cmd,
9437 _("Fetch and print the remote list of "
9438 "thread identifiers, one pkt only"));
9439 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9440 _("Fetch and display info about one thread"));
9441 add_com ("tset", class_obscure, threadset_test_cmd,
9442 _("Test setting to a different thread"));
9443 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9444 _("Iterate through updating all remote thread info"));
9445 add_com ("talive", class_obscure, threadalive_test,
9446 _(" Remote thread alive test "));
9451 /* Convert a thread ID to a string. Returns the string in a static
9455 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9457 static char buf[64];
9458 struct remote_state *rs = get_remote_state ();
9460 if (ptid_equal (ptid, null_ptid))
9461 return normal_pid_to_str (ptid);
9462 else if (ptid_is_pid (ptid))
9464 /* Printing an inferior target id. */
9466 /* When multi-process extensions are off, there's no way in the
9467 remote protocol to know the remote process id, if there's any
9468 at all. There's one exception --- when we're connected with
9469 target extended-remote, and we manually attached to a process
9470 with "attach PID". We don't record anywhere a flag that
9471 allows us to distinguish that case from the case of
9472 connecting with extended-remote and the stub already being
9473 attached to a process, and reporting yes to qAttached, hence
9474 no smart special casing here. */
9475 if (!remote_multi_process_p (rs))
9477 xsnprintf (buf, sizeof buf, "Remote target");
9481 return normal_pid_to_str (ptid);
9485 if (ptid_equal (magic_null_ptid, ptid))
9486 xsnprintf (buf, sizeof buf, "Thread <main>");
9487 else if (rs->extended && remote_multi_process_p (rs))
9488 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9489 ptid_get_pid (ptid), ptid_get_lwp (ptid));
9491 xsnprintf (buf, sizeof buf, "Thread %ld",
9492 ptid_get_lwp (ptid));
9497 /* Get the address of the thread local variable in OBJFILE which is
9498 stored at OFFSET within the thread local storage for thread PTID. */
9501 remote_get_thread_local_address (struct target_ops *ops,
9502 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9504 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
9506 struct remote_state *rs = get_remote_state ();
9508 char *endp = rs->buf + get_remote_packet_size ();
9509 enum packet_result result;
9511 strcpy (p, "qGetTLSAddr:");
9513 p = write_ptid (p, endp, ptid);
9515 p += hexnumstr (p, offset);
9517 p += hexnumstr (p, lm);
9521 getpkt (&rs->buf, &rs->buf_size, 0);
9522 result = packet_ok (rs->buf,
9523 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9524 if (result == PACKET_OK)
9528 unpack_varlen_hex (rs->buf, &result);
9531 else if (result == PACKET_UNKNOWN)
9532 throw_error (TLS_GENERIC_ERROR,
9533 _("Remote target doesn't support qGetTLSAddr packet"));
9535 throw_error (TLS_GENERIC_ERROR,
9536 _("Remote target failed to process qGetTLSAddr request"));
9539 throw_error (TLS_GENERIC_ERROR,
9540 _("TLS not supported or disabled on this target"));
9545 /* Provide thread local base, i.e. Thread Information Block address.
9546 Returns 1 if ptid is found and thread_local_base is non zero. */
9549 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
9551 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
9553 struct remote_state *rs = get_remote_state ();
9555 char *endp = rs->buf + get_remote_packet_size ();
9556 enum packet_result result;
9558 strcpy (p, "qGetTIBAddr:");
9560 p = write_ptid (p, endp, ptid);
9564 getpkt (&rs->buf, &rs->buf_size, 0);
9565 result = packet_ok (rs->buf,
9566 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9567 if (result == PACKET_OK)
9571 unpack_varlen_hex (rs->buf, &result);
9573 *addr = (CORE_ADDR) result;
9576 else if (result == PACKET_UNKNOWN)
9577 error (_("Remote target doesn't support qGetTIBAddr packet"));
9579 error (_("Remote target failed to process qGetTIBAddr request"));
9582 error (_("qGetTIBAddr not supported or disabled on this target"));
9587 /* Support for inferring a target description based on the current
9588 architecture and the size of a 'g' packet. While the 'g' packet
9589 can have any size (since optional registers can be left off the
9590 end), some sizes are easily recognizable given knowledge of the
9591 approximate architecture. */
9593 struct remote_g_packet_guess
9596 const struct target_desc *tdesc;
9598 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9599 DEF_VEC_O(remote_g_packet_guess_s);
9601 struct remote_g_packet_data
9603 VEC(remote_g_packet_guess_s) *guesses;
9606 static struct gdbarch_data *remote_g_packet_data_handle;
9609 remote_g_packet_data_init (struct obstack *obstack)
9611 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9615 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9616 const struct target_desc *tdesc)
9618 struct remote_g_packet_data *data
9619 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9620 struct remote_g_packet_guess new_guess, *guess;
9623 gdb_assert (tdesc != NULL);
9626 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9628 if (guess->bytes == bytes)
9629 internal_error (__FILE__, __LINE__,
9630 _("Duplicate g packet description added for size %d"),
9633 new_guess.bytes = bytes;
9634 new_guess.tdesc = tdesc;
9635 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9638 /* Return 1 if remote_read_description would do anything on this target
9639 and architecture, 0 otherwise. */
9642 remote_read_description_p (struct target_ops *target)
9644 struct remote_g_packet_data *data
9645 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9647 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9653 static const struct target_desc *
9654 remote_read_description (struct target_ops *target)
9656 struct remote_g_packet_data *data
9657 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9659 /* Do not try this during initial connection, when we do not know
9660 whether there is a running but stopped thread. */
9661 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9662 return target->beneath->to_read_description (target->beneath);
9664 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9666 struct remote_g_packet_guess *guess;
9668 int bytes = send_g_packet ();
9671 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9673 if (guess->bytes == bytes)
9674 return guess->tdesc;
9676 /* We discard the g packet. A minor optimization would be to
9677 hold on to it, and fill the register cache once we have selected
9678 an architecture, but it's too tricky to do safely. */
9681 return target->beneath->to_read_description (target->beneath);
9684 /* Remote file transfer support. This is host-initiated I/O, not
9685 target-initiated; for target-initiated, see remote-fileio.c. */
9687 /* If *LEFT is at least the length of STRING, copy STRING to
9688 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9689 decrease *LEFT. Otherwise raise an error. */
9692 remote_buffer_add_string (char **buffer, int *left, char *string)
9694 int len = strlen (string);
9697 error (_("Packet too long for target."));
9699 memcpy (*buffer, string, len);
9703 /* NUL-terminate the buffer as a convenience, if there is
9709 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9710 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9711 decrease *LEFT. Otherwise raise an error. */
9714 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9717 if (2 * len > *left)
9718 error (_("Packet too long for target."));
9720 bin2hex (bytes, *buffer, len);
9724 /* NUL-terminate the buffer as a convenience, if there is
9730 /* If *LEFT is large enough, convert VALUE to hex and add it to
9731 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9732 decrease *LEFT. Otherwise raise an error. */
9735 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9737 int len = hexnumlen (value);
9740 error (_("Packet too long for target."));
9742 hexnumstr (*buffer, value);
9746 /* NUL-terminate the buffer as a convenience, if there is
9752 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9753 value, *REMOTE_ERRNO to the remote error number or zero if none
9754 was included, and *ATTACHMENT to point to the start of the annex
9755 if any. The length of the packet isn't needed here; there may
9756 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9758 Return 0 if the packet could be parsed, -1 if it could not. If
9759 -1 is returned, the other variables may not be initialized. */
9762 remote_hostio_parse_result (char *buffer, int *retcode,
9763 int *remote_errno, char **attachment)
9770 if (buffer[0] != 'F')
9774 *retcode = strtol (&buffer[1], &p, 16);
9775 if (errno != 0 || p == &buffer[1])
9778 /* Check for ",errno". */
9782 *remote_errno = strtol (p + 1, &p2, 16);
9783 if (errno != 0 || p + 1 == p2)
9788 /* Check for ";attachment". If there is no attachment, the
9789 packet should end here. */
9792 *attachment = p + 1;
9795 else if (*p == '\0')
9801 /* Send a prepared I/O packet to the target and read its response.
9802 The prepared packet is in the global RS->BUF before this function
9803 is called, and the answer is there when we return.
9805 COMMAND_BYTES is the length of the request to send, which may include
9806 binary data. WHICH_PACKET is the packet configuration to check
9807 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9808 is set to the error number and -1 is returned. Otherwise the value
9809 returned by the function is returned.
9811 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9812 attachment is expected; an error will be reported if there's a
9813 mismatch. If one is found, *ATTACHMENT will be set to point into
9814 the packet buffer and *ATTACHMENT_LEN will be set to the
9815 attachment's length. */
9818 remote_hostio_send_command (int command_bytes, int which_packet,
9819 int *remote_errno, char **attachment,
9820 int *attachment_len)
9822 struct remote_state *rs = get_remote_state ();
9823 int ret, bytes_read;
9824 char *attachment_tmp;
9826 if (!rs->remote_desc
9827 || packet_support (which_packet) == PACKET_DISABLE)
9829 *remote_errno = FILEIO_ENOSYS;
9833 putpkt_binary (rs->buf, command_bytes);
9834 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9836 /* If it timed out, something is wrong. Don't try to parse the
9840 *remote_errno = FILEIO_EINVAL;
9844 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9847 *remote_errno = FILEIO_EINVAL;
9849 case PACKET_UNKNOWN:
9850 *remote_errno = FILEIO_ENOSYS;
9856 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9859 *remote_errno = FILEIO_EINVAL;
9863 /* Make sure we saw an attachment if and only if we expected one. */
9864 if ((attachment_tmp == NULL && attachment != NULL)
9865 || (attachment_tmp != NULL && attachment == NULL))
9867 *remote_errno = FILEIO_EINVAL;
9871 /* If an attachment was found, it must point into the packet buffer;
9872 work out how many bytes there were. */
9873 if (attachment_tmp != NULL)
9875 *attachment = attachment_tmp;
9876 *attachment_len = bytes_read - (*attachment - rs->buf);
9882 /* Return nonzero if the filesystem accessed by the target_fileio_*
9883 methods is the local filesystem, zero otherwise. */
9886 remote_filesystem_is_local (struct target_ops *self)
9891 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9892 remote file descriptor, or -1 if an error occurs (and set
9896 remote_hostio_open (struct target_ops *self,
9897 const char *filename, int flags, int mode,
9900 struct remote_state *rs = get_remote_state ();
9902 int left = get_remote_packet_size () - 1;
9904 remote_buffer_add_string (&p, &left, "vFile:open:");
9906 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9908 remote_buffer_add_string (&p, &left, ",");
9910 remote_buffer_add_int (&p, &left, flags);
9911 remote_buffer_add_string (&p, &left, ",");
9913 remote_buffer_add_int (&p, &left, mode);
9915 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9916 remote_errno, NULL, NULL);
9919 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9920 Return the number of bytes written, or -1 if an error occurs (and
9921 set *REMOTE_ERRNO). */
9924 remote_hostio_pwrite (struct target_ops *self,
9925 int fd, const gdb_byte *write_buf, int len,
9926 ULONGEST offset, int *remote_errno)
9928 struct remote_state *rs = get_remote_state ();
9930 int left = get_remote_packet_size ();
9933 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9935 remote_buffer_add_int (&p, &left, fd);
9936 remote_buffer_add_string (&p, &left, ",");
9938 remote_buffer_add_int (&p, &left, offset);
9939 remote_buffer_add_string (&p, &left, ",");
9941 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9942 get_remote_packet_size () - (p - rs->buf));
9944 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9945 remote_errno, NULL, NULL);
9948 /* Read up to LEN bytes FD on the remote target into READ_BUF
9949 Return the number of bytes read, or -1 if an error occurs (and
9950 set *REMOTE_ERRNO). */
9953 remote_hostio_pread (struct target_ops *self,
9954 int fd, gdb_byte *read_buf, int len,
9955 ULONGEST offset, int *remote_errno)
9957 struct remote_state *rs = get_remote_state ();
9960 int left = get_remote_packet_size ();
9961 int ret, attachment_len;
9964 remote_buffer_add_string (&p, &left, "vFile:pread:");
9966 remote_buffer_add_int (&p, &left, fd);
9967 remote_buffer_add_string (&p, &left, ",");
9969 remote_buffer_add_int (&p, &left, len);
9970 remote_buffer_add_string (&p, &left, ",");
9972 remote_buffer_add_int (&p, &left, offset);
9974 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9975 remote_errno, &attachment,
9981 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9983 if (read_len != ret)
9984 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9989 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9990 (and set *REMOTE_ERRNO). */
9993 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
9995 struct remote_state *rs = get_remote_state ();
9997 int left = get_remote_packet_size () - 1;
9999 remote_buffer_add_string (&p, &left, "vFile:close:");
10001 remote_buffer_add_int (&p, &left, fd);
10003 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10004 remote_errno, NULL, NULL);
10007 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
10008 occurs (and set *REMOTE_ERRNO). */
10011 remote_hostio_unlink (struct target_ops *self,
10012 const char *filename, int *remote_errno)
10014 struct remote_state *rs = get_remote_state ();
10016 int left = get_remote_packet_size () - 1;
10018 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10020 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10021 strlen (filename));
10023 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10024 remote_errno, NULL, NULL);
10027 /* Read value of symbolic link FILENAME on the remote target. Return
10028 a null-terminated string allocated via xmalloc, or NULL if an error
10029 occurs (and set *REMOTE_ERRNO). */
10032 remote_hostio_readlink (struct target_ops *self,
10033 const char *filename, int *remote_errno)
10035 struct remote_state *rs = get_remote_state ();
10038 int left = get_remote_packet_size ();
10039 int len, attachment_len;
10043 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10045 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10046 strlen (filename));
10048 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10049 remote_errno, &attachment,
10055 ret = xmalloc (len + 1);
10057 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10058 (gdb_byte *) ret, len);
10059 if (read_len != len)
10060 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10066 /* Read information about the open file FD on the remote target
10067 into ST. Return 0 on success, or -1 if an error occurs (and
10068 set *REMOTE_ERRNO). */
10071 remote_hostio_fstat (struct target_ops *self,
10072 int fd, struct stat *st,
10075 struct remote_state *rs = get_remote_state ();
10077 int left = get_remote_packet_size ();
10078 int attachment_len, ret;
10080 struct fio_stat fst;
10083 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10085 remote_buffer_add_int (&p, &left, fd);
10087 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10088 remote_errno, &attachment,
10092 if (*remote_errno != FILEIO_ENOSYS)
10095 /* Strictly we should return -1, ENOSYS here, but when
10096 "set sysroot remote:" was implemented in August 2008
10097 BFD's need for a stat function was sidestepped with
10098 this hack. This was not remedied until March 2015
10099 so we retain the previous behavior to avoid breaking
10102 Note that the memset is a March 2015 addition; older
10103 GDBs set st_size *and nothing else* so the structure
10104 would have garbage in all other fields. This might
10105 break something but retaining the previous behavior
10106 here would be just too wrong. */
10108 memset (st, 0, sizeof (struct stat));
10109 st->st_size = INT_MAX;
10113 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10114 (gdb_byte *) &fst, sizeof (fst));
10116 if (read_len != ret)
10117 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10119 if (read_len != sizeof (fst))
10120 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10121 read_len, (int) sizeof (fst));
10123 remote_fileio_to_host_stat (&fst, st);
10129 remote_fileio_errno_to_host (int errnum)
10135 case FILEIO_ENOENT:
10143 case FILEIO_EACCES:
10145 case FILEIO_EFAULT:
10149 case FILEIO_EEXIST:
10151 case FILEIO_ENODEV:
10153 case FILEIO_ENOTDIR:
10155 case FILEIO_EISDIR:
10157 case FILEIO_EINVAL:
10159 case FILEIO_ENFILE:
10161 case FILEIO_EMFILE:
10165 case FILEIO_ENOSPC:
10167 case FILEIO_ESPIPE:
10171 case FILEIO_ENOSYS:
10173 case FILEIO_ENAMETOOLONG:
10174 return ENAMETOOLONG;
10180 remote_hostio_error (int errnum)
10182 int host_error = remote_fileio_errno_to_host (errnum);
10184 if (host_error == -1)
10185 error (_("Unknown remote I/O error %d"), errnum);
10187 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10191 remote_hostio_close_cleanup (void *opaque)
10193 int fd = *(int *) opaque;
10196 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10200 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10202 struct cleanup *back_to, *close_cleanup;
10203 int retcode, fd, remote_errno, bytes, io_size;
10206 int bytes_in_buffer;
10209 struct remote_state *rs = get_remote_state ();
10211 if (!rs->remote_desc)
10212 error (_("command can only be used with remote target"));
10214 file = gdb_fopen_cloexec (local_file, "rb");
10216 perror_with_name (local_file);
10217 back_to = make_cleanup_fclose (file);
10219 fd = remote_hostio_open (find_target_at (process_stratum),
10220 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10222 0700, &remote_errno);
10224 remote_hostio_error (remote_errno);
10226 /* Send up to this many bytes at once. They won't all fit in the
10227 remote packet limit, so we'll transfer slightly fewer. */
10228 io_size = get_remote_packet_size ();
10229 buffer = xmalloc (io_size);
10230 make_cleanup (xfree, buffer);
10232 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10234 bytes_in_buffer = 0;
10237 while (bytes_in_buffer || !saw_eof)
10241 bytes = fread (buffer + bytes_in_buffer, 1,
10242 io_size - bytes_in_buffer,
10247 error (_("Error reading %s."), local_file);
10250 /* EOF. Unless there is something still in the
10251 buffer from the last iteration, we are done. */
10253 if (bytes_in_buffer == 0)
10261 bytes += bytes_in_buffer;
10262 bytes_in_buffer = 0;
10264 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10266 offset, &remote_errno);
10269 remote_hostio_error (remote_errno);
10270 else if (retcode == 0)
10271 error (_("Remote write of %d bytes returned 0!"), bytes);
10272 else if (retcode < bytes)
10274 /* Short write. Save the rest of the read data for the next
10276 bytes_in_buffer = bytes - retcode;
10277 memmove (buffer, buffer + retcode, bytes_in_buffer);
10283 discard_cleanups (close_cleanup);
10284 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10285 remote_hostio_error (remote_errno);
10288 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10289 do_cleanups (back_to);
10293 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10295 struct cleanup *back_to, *close_cleanup;
10296 int fd, remote_errno, bytes, io_size;
10300 struct remote_state *rs = get_remote_state ();
10302 if (!rs->remote_desc)
10303 error (_("command can only be used with remote target"));
10305 fd = remote_hostio_open (find_target_at (process_stratum),
10306 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10308 remote_hostio_error (remote_errno);
10310 file = gdb_fopen_cloexec (local_file, "wb");
10312 perror_with_name (local_file);
10313 back_to = make_cleanup_fclose (file);
10315 /* Send up to this many bytes at once. They won't all fit in the
10316 remote packet limit, so we'll transfer slightly fewer. */
10317 io_size = get_remote_packet_size ();
10318 buffer = xmalloc (io_size);
10319 make_cleanup (xfree, buffer);
10321 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10326 bytes = remote_hostio_pread (find_target_at (process_stratum),
10327 fd, buffer, io_size, offset, &remote_errno);
10329 /* Success, but no bytes, means end-of-file. */
10332 remote_hostio_error (remote_errno);
10336 bytes = fwrite (buffer, 1, bytes, file);
10338 perror_with_name (local_file);
10341 discard_cleanups (close_cleanup);
10342 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10343 remote_hostio_error (remote_errno);
10346 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10347 do_cleanups (back_to);
10351 remote_file_delete (const char *remote_file, int from_tty)
10353 int retcode, remote_errno;
10354 struct remote_state *rs = get_remote_state ();
10356 if (!rs->remote_desc)
10357 error (_("command can only be used with remote target"));
10359 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10360 remote_file, &remote_errno);
10362 remote_hostio_error (remote_errno);
10365 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10369 remote_put_command (char *args, int from_tty)
10371 struct cleanup *back_to;
10375 error_no_arg (_("file to put"));
10377 argv = gdb_buildargv (args);
10378 back_to = make_cleanup_freeargv (argv);
10379 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10380 error (_("Invalid parameters to remote put"));
10382 remote_file_put (argv[0], argv[1], from_tty);
10384 do_cleanups (back_to);
10388 remote_get_command (char *args, int from_tty)
10390 struct cleanup *back_to;
10394 error_no_arg (_("file to get"));
10396 argv = gdb_buildargv (args);
10397 back_to = make_cleanup_freeargv (argv);
10398 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10399 error (_("Invalid parameters to remote get"));
10401 remote_file_get (argv[0], argv[1], from_tty);
10403 do_cleanups (back_to);
10407 remote_delete_command (char *args, int from_tty)
10409 struct cleanup *back_to;
10413 error_no_arg (_("file to delete"));
10415 argv = gdb_buildargv (args);
10416 back_to = make_cleanup_freeargv (argv);
10417 if (argv[0] == NULL || argv[1] != NULL)
10418 error (_("Invalid parameters to remote delete"));
10420 remote_file_delete (argv[0], from_tty);
10422 do_cleanups (back_to);
10426 remote_command (char *args, int from_tty)
10428 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
10432 remote_can_execute_reverse (struct target_ops *self)
10434 if (packet_support (PACKET_bs) == PACKET_ENABLE
10435 || packet_support (PACKET_bc) == PACKET_ENABLE)
10442 remote_supports_non_stop (struct target_ops *self)
10448 remote_supports_disable_randomization (struct target_ops *self)
10450 /* Only supported in extended mode. */
10455 remote_supports_multi_process (struct target_ops *self)
10457 struct remote_state *rs = get_remote_state ();
10459 /* Only extended-remote handles being attached to multiple
10460 processes, even though plain remote can use the multi-process
10461 thread id extensions, so that GDB knows the target process's
10463 return rs->extended && remote_multi_process_p (rs);
10467 remote_supports_cond_tracepoints (void)
10469 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
10473 remote_supports_cond_breakpoints (struct target_ops *self)
10475 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
10479 remote_supports_fast_tracepoints (void)
10481 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
10485 remote_supports_static_tracepoints (void)
10487 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
10491 remote_supports_install_in_trace (void)
10493 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
10497 remote_supports_enable_disable_tracepoint (struct target_ops *self)
10499 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10504 remote_supports_string_tracing (struct target_ops *self)
10506 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
10510 remote_can_run_breakpoint_commands (struct target_ops *self)
10512 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
10516 remote_trace_init (struct target_ops *self)
10519 remote_get_noisy_reply (&target_buf, &target_buf_size);
10520 if (strcmp (target_buf, "OK") != 0)
10521 error (_("Target does not support this command."));
10524 static void free_actions_list (char **actions_list);
10525 static void free_actions_list_cleanup_wrapper (void *);
10527 free_actions_list_cleanup_wrapper (void *al)
10529 free_actions_list (al);
10533 free_actions_list (char **actions_list)
10537 if (actions_list == 0)
10540 for (ndx = 0; actions_list[ndx]; ndx++)
10541 xfree (actions_list[ndx]);
10543 xfree (actions_list);
10546 /* Recursive routine to walk through command list including loops, and
10547 download packets for each command. */
10550 remote_download_command_source (int num, ULONGEST addr,
10551 struct command_line *cmds)
10553 struct remote_state *rs = get_remote_state ();
10554 struct command_line *cmd;
10556 for (cmd = cmds; cmd; cmd = cmd->next)
10558 QUIT; /* Allow user to bail out with ^C. */
10559 strcpy (rs->buf, "QTDPsrc:");
10560 encode_source_string (num, addr, "cmd", cmd->line,
10561 rs->buf + strlen (rs->buf),
10562 rs->buf_size - strlen (rs->buf));
10564 remote_get_noisy_reply (&target_buf, &target_buf_size);
10565 if (strcmp (target_buf, "OK"))
10566 warning (_("Target does not support source download."));
10568 if (cmd->control_type == while_control
10569 || cmd->control_type == while_stepping_control)
10571 remote_download_command_source (num, addr, *cmd->body_list);
10573 QUIT; /* Allow user to bail out with ^C. */
10574 strcpy (rs->buf, "QTDPsrc:");
10575 encode_source_string (num, addr, "cmd", "end",
10576 rs->buf + strlen (rs->buf),
10577 rs->buf_size - strlen (rs->buf));
10579 remote_get_noisy_reply (&target_buf, &target_buf_size);
10580 if (strcmp (target_buf, "OK"))
10581 warning (_("Target does not support source download."));
10587 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
10589 #define BUF_SIZE 2048
10593 char buf[BUF_SIZE];
10594 char **tdp_actions;
10595 char **stepping_actions;
10597 struct cleanup *old_chain = NULL;
10598 struct agent_expr *aexpr;
10599 struct cleanup *aexpr_chain = NULL;
10601 struct breakpoint *b = loc->owner;
10602 struct tracepoint *t = (struct tracepoint *) b;
10604 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10605 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10607 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10610 tpaddr = loc->address;
10611 sprintf_vma (addrbuf, tpaddr);
10612 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10613 addrbuf, /* address */
10614 (b->enable_state == bp_enabled ? 'E' : 'D'),
10615 t->step_count, t->pass_count);
10616 /* Fast tracepoints are mostly handled by the target, but we can
10617 tell the target how big of an instruction block should be moved
10619 if (b->type == bp_fast_tracepoint)
10621 /* Only test for support at download time; we may not know
10622 target capabilities at definition time. */
10623 if (remote_supports_fast_tracepoints ())
10627 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10628 tpaddr, &isize, NULL))
10629 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10632 /* If it passed validation at definition but fails now,
10633 something is very wrong. */
10634 internal_error (__FILE__, __LINE__,
10635 _("Fast tracepoint not "
10636 "valid during download"));
10639 /* Fast tracepoints are functionally identical to regular
10640 tracepoints, so don't take lack of support as a reason to
10641 give up on the trace run. */
10642 warning (_("Target does not support fast tracepoints, "
10643 "downloading %d as regular tracepoint"), b->number);
10645 else if (b->type == bp_static_tracepoint)
10647 /* Only test for support at download time; we may not know
10648 target capabilities at definition time. */
10649 if (remote_supports_static_tracepoints ())
10651 struct static_tracepoint_marker marker;
10653 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10654 strcat (buf, ":S");
10656 error (_("Static tracepoint not valid during download"));
10659 /* Fast tracepoints are functionally identical to regular
10660 tracepoints, so don't take lack of support as a reason
10661 to give up on the trace run. */
10662 error (_("Target does not support static tracepoints"));
10664 /* If the tracepoint has a conditional, make it into an agent
10665 expression and append to the definition. */
10668 /* Only test support at download time, we may not know target
10669 capabilities at definition time. */
10670 if (remote_supports_cond_tracepoints ())
10672 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10673 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10674 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10676 pkt = buf + strlen (buf);
10677 for (ndx = 0; ndx < aexpr->len; ++ndx)
10678 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10680 do_cleanups (aexpr_chain);
10683 warning (_("Target does not support conditional tracepoints, "
10684 "ignoring tp %d cond"), b->number);
10687 if (b->commands || *default_collect)
10690 remote_get_noisy_reply (&target_buf, &target_buf_size);
10691 if (strcmp (target_buf, "OK"))
10692 error (_("Target does not support tracepoints."));
10694 /* do_single_steps (t); */
10697 for (ndx = 0; tdp_actions[ndx]; ndx++)
10699 QUIT; /* Allow user to bail out with ^C. */
10700 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10701 b->number, addrbuf, /* address */
10703 ((tdp_actions[ndx + 1] || stepping_actions)
10706 remote_get_noisy_reply (&target_buf,
10708 if (strcmp (target_buf, "OK"))
10709 error (_("Error on target while setting tracepoints."));
10712 if (stepping_actions)
10714 for (ndx = 0; stepping_actions[ndx]; ndx++)
10716 QUIT; /* Allow user to bail out with ^C. */
10717 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10718 b->number, addrbuf, /* address */
10719 ((ndx == 0) ? "S" : ""),
10720 stepping_actions[ndx],
10721 (stepping_actions[ndx + 1] ? "-" : ""));
10723 remote_get_noisy_reply (&target_buf,
10725 if (strcmp (target_buf, "OK"))
10726 error (_("Error on target while setting tracepoints."));
10730 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
10732 if (b->addr_string)
10734 strcpy (buf, "QTDPsrc:");
10735 encode_source_string (b->number, loc->address,
10736 "at", b->addr_string, buf + strlen (buf),
10737 2048 - strlen (buf));
10740 remote_get_noisy_reply (&target_buf, &target_buf_size);
10741 if (strcmp (target_buf, "OK"))
10742 warning (_("Target does not support source download."));
10744 if (b->cond_string)
10746 strcpy (buf, "QTDPsrc:");
10747 encode_source_string (b->number, loc->address,
10748 "cond", b->cond_string, buf + strlen (buf),
10749 2048 - strlen (buf));
10751 remote_get_noisy_reply (&target_buf, &target_buf_size);
10752 if (strcmp (target_buf, "OK"))
10753 warning (_("Target does not support source download."));
10755 remote_download_command_source (b->number, loc->address,
10756 breakpoint_commands (b));
10759 do_cleanups (old_chain);
10763 remote_can_download_tracepoint (struct target_ops *self)
10765 struct remote_state *rs = get_remote_state ();
10766 struct trace_status *ts;
10769 /* Don't try to install tracepoints until we've relocated our
10770 symbols, and fetched and merged the target's tracepoint list with
10772 if (rs->starting_up)
10775 ts = current_trace_status ();
10776 status = remote_get_trace_status (self, ts);
10778 if (status == -1 || !ts->running_known || !ts->running)
10781 /* If we are in a tracing experiment, but remote stub doesn't support
10782 installing tracepoint in trace, we have to return. */
10783 if (!remote_supports_install_in_trace ())
10791 remote_download_trace_state_variable (struct target_ops *self,
10792 struct trace_state_variable *tsv)
10794 struct remote_state *rs = get_remote_state ();
10797 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10798 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10800 p = rs->buf + strlen (rs->buf);
10801 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10802 error (_("Trace state variable name too long for tsv definition packet"));
10803 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
10806 remote_get_noisy_reply (&target_buf, &target_buf_size);
10807 if (*target_buf == '\0')
10808 error (_("Target does not support this command."));
10809 if (strcmp (target_buf, "OK") != 0)
10810 error (_("Error on target while downloading trace state variable."));
10814 remote_enable_tracepoint (struct target_ops *self,
10815 struct bp_location *location)
10817 struct remote_state *rs = get_remote_state ();
10820 sprintf_vma (addr_buf, location->address);
10821 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10822 location->owner->number, addr_buf);
10824 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10825 if (*rs->buf == '\0')
10826 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10827 if (strcmp (rs->buf, "OK") != 0)
10828 error (_("Error on target while enabling tracepoint."));
10832 remote_disable_tracepoint (struct target_ops *self,
10833 struct bp_location *location)
10835 struct remote_state *rs = get_remote_state ();
10838 sprintf_vma (addr_buf, location->address);
10839 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10840 location->owner->number, addr_buf);
10842 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10843 if (*rs->buf == '\0')
10844 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10845 if (strcmp (rs->buf, "OK") != 0)
10846 error (_("Error on target while disabling tracepoint."));
10850 remote_trace_set_readonly_regions (struct target_ops *self)
10854 bfd_size_type size;
10860 return; /* No information to give. */
10862 strcpy (target_buf, "QTro");
10863 offset = strlen (target_buf);
10864 for (s = exec_bfd->sections; s; s = s->next)
10866 char tmp1[40], tmp2[40];
10869 if ((s->flags & SEC_LOAD) == 0 ||
10870 /* (s->flags & SEC_CODE) == 0 || */
10871 (s->flags & SEC_READONLY) == 0)
10875 vma = bfd_get_section_vma (abfd, s);
10876 size = bfd_get_section_size (s);
10877 sprintf_vma (tmp1, vma);
10878 sprintf_vma (tmp2, vma + size);
10879 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10880 if (offset + sec_length + 1 > target_buf_size)
10882 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
10884 Too many sections for read-only sections definition packet."));
10887 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10889 offset += sec_length;
10893 putpkt (target_buf);
10894 getpkt (&target_buf, &target_buf_size, 0);
10899 remote_trace_start (struct target_ops *self)
10901 putpkt ("QTStart");
10902 remote_get_noisy_reply (&target_buf, &target_buf_size);
10903 if (*target_buf == '\0')
10904 error (_("Target does not support this command."));
10905 if (strcmp (target_buf, "OK") != 0)
10906 error (_("Bogus reply from target: %s"), target_buf);
10910 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
10912 /* Initialize it just to avoid a GCC false warning. */
10914 /* FIXME we need to get register block size some other way. */
10915 extern int trace_regblock_size;
10916 enum packet_result result;
10918 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
10921 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10923 putpkt ("qTStatus");
10927 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10929 CATCH (ex, RETURN_MASK_ERROR)
10931 if (ex.error != TARGET_CLOSE_ERROR)
10933 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10936 throw_exception (ex);
10940 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10942 /* If the remote target doesn't do tracing, flag it. */
10943 if (result == PACKET_UNKNOWN)
10946 /* We're working with a live target. */
10947 ts->filename = NULL;
10950 error (_("Bogus trace status reply from target: %s"), target_buf);
10952 /* Function 'parse_trace_status' sets default value of each field of
10953 'ts' at first, so we don't have to do it here. */
10954 parse_trace_status (p, ts);
10956 return ts->running;
10960 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
10961 struct uploaded_tp *utp)
10963 struct remote_state *rs = get_remote_state ();
10965 struct bp_location *loc;
10966 struct tracepoint *tp = (struct tracepoint *) bp;
10967 size_t size = get_remote_packet_size ();
10971 tp->base.hit_count = 0;
10972 tp->traceframe_usage = 0;
10973 for (loc = tp->base.loc; loc; loc = loc->next)
10975 /* If the tracepoint was never downloaded, don't go asking for
10977 if (tp->number_on_target == 0)
10979 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10980 phex_nz (loc->address, 0));
10982 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10983 if (reply && *reply)
10986 parse_tracepoint_status (reply + 1, bp, utp);
10992 utp->hit_count = 0;
10993 utp->traceframe_usage = 0;
10994 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10995 phex_nz (utp->addr, 0));
10997 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10998 if (reply && *reply)
11001 parse_tracepoint_status (reply + 1, bp, utp);
11007 remote_trace_stop (struct target_ops *self)
11010 remote_get_noisy_reply (&target_buf, &target_buf_size);
11011 if (*target_buf == '\0')
11012 error (_("Target does not support this command."));
11013 if (strcmp (target_buf, "OK") != 0)
11014 error (_("Bogus reply from target: %s"), target_buf);
11018 remote_trace_find (struct target_ops *self,
11019 enum trace_find_type type, int num,
11020 CORE_ADDR addr1, CORE_ADDR addr2,
11023 struct remote_state *rs = get_remote_state ();
11024 char *endbuf = rs->buf + get_remote_packet_size ();
11026 int target_frameno = -1, target_tracept = -1;
11028 /* Lookups other than by absolute frame number depend on the current
11029 trace selected, so make sure it is correct on the remote end
11031 if (type != tfind_number)
11032 set_remote_traceframe ();
11035 strcpy (p, "QTFrame:");
11036 p = strchr (p, '\0');
11040 xsnprintf (p, endbuf - p, "%x", num);
11043 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11046 xsnprintf (p, endbuf - p, "tdp:%x", num);
11049 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11050 phex_nz (addr2, 0));
11052 case tfind_outside:
11053 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11054 phex_nz (addr2, 0));
11057 error (_("Unknown trace find type %d"), type);
11061 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11062 if (*reply == '\0')
11063 error (_("Target does not support this command."));
11065 while (reply && *reply)
11070 target_frameno = (int) strtol (p, &reply, 16);
11072 error (_("Unable to parse trace frame number"));
11073 /* Don't update our remote traceframe number cache on failure
11074 to select a remote traceframe. */
11075 if (target_frameno == -1)
11080 target_tracept = (int) strtol (p, &reply, 16);
11082 error (_("Unable to parse tracepoint number"));
11084 case 'O': /* "OK"? */
11085 if (reply[1] == 'K' && reply[2] == '\0')
11088 error (_("Bogus reply from target: %s"), reply);
11091 error (_("Bogus reply from target: %s"), reply);
11094 *tpp = target_tracept;
11096 rs->remote_traceframe_number = target_frameno;
11097 return target_frameno;
11101 remote_get_trace_state_variable_value (struct target_ops *self,
11102 int tsvnum, LONGEST *val)
11104 struct remote_state *rs = get_remote_state ();
11108 set_remote_traceframe ();
11110 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11112 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11113 if (reply && *reply)
11117 unpack_varlen_hex (reply + 1, &uval);
11118 *val = (LONGEST) uval;
11126 remote_save_trace_data (struct target_ops *self, const char *filename)
11128 struct remote_state *rs = get_remote_state ();
11132 strcpy (p, "QTSave:");
11134 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11135 error (_("Remote file name too long for trace save packet"));
11136 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11139 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11140 if (*reply == '\0')
11141 error (_("Target does not support this command."));
11142 if (strcmp (reply, "OK") != 0)
11143 error (_("Bogus reply from target: %s"), reply);
11147 /* This is basically a memory transfer, but needs to be its own packet
11148 because we don't know how the target actually organizes its trace
11149 memory, plus we want to be able to ask for as much as possible, but
11150 not be unhappy if we don't get as much as we ask for. */
11153 remote_get_raw_trace_data (struct target_ops *self,
11154 gdb_byte *buf, ULONGEST offset, LONGEST len)
11156 struct remote_state *rs = get_remote_state ();
11162 strcpy (p, "qTBuffer:");
11164 p += hexnumstr (p, offset);
11166 p += hexnumstr (p, len);
11170 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11171 if (reply && *reply)
11173 /* 'l' by itself means we're at the end of the buffer and
11174 there is nothing more to get. */
11178 /* Convert the reply into binary. Limit the number of bytes to
11179 convert according to our passed-in buffer size, rather than
11180 what was returned in the packet; if the target is
11181 unexpectedly generous and gives us a bigger reply than we
11182 asked for, we don't want to crash. */
11183 rslt = hex2bin (target_buf, buf, len);
11187 /* Something went wrong, flag as an error. */
11192 remote_set_disconnected_tracing (struct target_ops *self, int val)
11194 struct remote_state *rs = get_remote_state ();
11196 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11200 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11202 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11203 if (*reply == '\0')
11204 error (_("Target does not support this command."));
11205 if (strcmp (reply, "OK") != 0)
11206 error (_("Bogus reply from target: %s"), reply);
11209 warning (_("Target does not support disconnected tracing."));
11213 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11215 struct thread_info *info = find_thread_ptid (ptid);
11217 if (info && info->priv)
11218 return info->priv->core;
11223 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11225 struct remote_state *rs = get_remote_state ();
11228 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11230 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11231 if (*reply == '\0')
11232 error (_("Target does not support this command."));
11233 if (strcmp (reply, "OK") != 0)
11234 error (_("Bogus reply from target: %s"), reply);
11237 static struct traceframe_info *
11238 remote_traceframe_info (struct target_ops *self)
11242 text = target_read_stralloc (¤t_target,
11243 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11246 struct traceframe_info *info;
11247 struct cleanup *back_to = make_cleanup (xfree, text);
11249 info = parse_traceframe_info (text);
11250 do_cleanups (back_to);
11257 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11258 instruction on which a fast tracepoint may be placed. Returns -1
11259 if the packet is not supported, and 0 if the minimum instruction
11260 length is unknown. */
11263 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11265 struct remote_state *rs = get_remote_state ();
11268 /* If we're not debugging a process yet, the IPA can't be
11270 if (!target_has_execution)
11273 /* Make sure the remote is pointing at the right process. */
11274 set_general_process ();
11276 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11278 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11279 if (*reply == '\0')
11283 ULONGEST min_insn_len;
11285 unpack_varlen_hex (reply, &min_insn_len);
11287 return (int) min_insn_len;
11292 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11294 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11296 struct remote_state *rs = get_remote_state ();
11297 char *buf = rs->buf;
11298 char *endbuf = rs->buf + get_remote_packet_size ();
11299 enum packet_result result;
11301 gdb_assert (val >= 0 || val == -1);
11302 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11303 /* Send -1 as literal "-1" to avoid host size dependency. */
11307 buf += hexnumstr (buf, (ULONGEST) -val);
11310 buf += hexnumstr (buf, (ULONGEST) val);
11313 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11314 result = packet_ok (rs->buf,
11315 &remote_protocol_packets[PACKET_QTBuffer_size]);
11317 if (result != PACKET_OK)
11318 warning (_("Bogus reply from target: %s"), rs->buf);
11323 remote_set_trace_notes (struct target_ops *self,
11324 const char *user, const char *notes,
11325 const char *stop_notes)
11327 struct remote_state *rs = get_remote_state ();
11329 char *buf = rs->buf;
11330 char *endbuf = rs->buf + get_remote_packet_size ();
11333 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11336 buf += xsnprintf (buf, endbuf - buf, "user:");
11337 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11343 buf += xsnprintf (buf, endbuf - buf, "notes:");
11344 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11350 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11351 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11355 /* Ensure the buffer is terminated. */
11359 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11360 if (*reply == '\0')
11363 if (strcmp (reply, "OK") != 0)
11364 error (_("Bogus reply from target: %s"), reply);
11370 remote_use_agent (struct target_ops *self, int use)
11372 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11374 struct remote_state *rs = get_remote_state ();
11376 /* If the stub supports QAgent. */
11377 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11379 getpkt (&rs->buf, &rs->buf_size, 0);
11381 if (strcmp (rs->buf, "OK") == 0)
11392 remote_can_use_agent (struct target_ops *self)
11394 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11397 struct btrace_target_info
11399 /* The ptid of the traced thread. */
11402 /* The obtained branch trace configuration. */
11403 struct btrace_config conf;
11406 /* Reset our idea of our target's btrace configuration. */
11409 remote_btrace_reset (void)
11411 struct remote_state *rs = get_remote_state ();
11413 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11416 /* Check whether the target supports branch tracing. */
11419 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
11421 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
11423 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
11428 case BTRACE_FORMAT_NONE:
11431 case BTRACE_FORMAT_BTS:
11432 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11435 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
11438 /* Synchronize the configuration with the target. */
11441 btrace_sync_conf (const struct btrace_config *conf)
11443 struct packet_config *packet;
11444 struct remote_state *rs;
11445 char *buf, *pos, *endbuf;
11447 rs = get_remote_state ();
11449 endbuf = buf + get_remote_packet_size ();
11451 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11452 if (packet_config_support (packet) == PACKET_ENABLE
11453 && conf->bts.size != rs->btrace_config.bts.size)
11456 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11460 getpkt (&buf, &rs->buf_size, 0);
11462 if (packet_ok (buf, packet) == PACKET_ERROR)
11464 if (buf[0] == 'E' && buf[1] == '.')
11465 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11467 error (_("Failed to configure the BTS buffer size."));
11470 rs->btrace_config.bts.size = conf->bts.size;
11474 /* Read the current thread's btrace configuration from the target and
11475 store it into CONF. */
11478 btrace_read_config (struct btrace_config *conf)
11482 xml = target_read_stralloc (¤t_target,
11483 TARGET_OBJECT_BTRACE_CONF, "");
11486 struct cleanup *cleanup;
11488 cleanup = make_cleanup (xfree, xml);
11489 parse_xml_btrace_conf (conf, xml);
11490 do_cleanups (cleanup);
11494 /* Enable branch tracing. */
11496 static struct btrace_target_info *
11497 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11498 const struct btrace_config *conf)
11500 struct btrace_target_info *tinfo = NULL;
11501 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11502 struct remote_state *rs = get_remote_state ();
11503 char *buf = rs->buf;
11504 char *endbuf = rs->buf + get_remote_packet_size ();
11506 if (packet_config_support (packet) != PACKET_ENABLE)
11507 error (_("Target does not support branch tracing."));
11509 btrace_sync_conf (conf);
11511 set_general_thread (ptid);
11513 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11515 getpkt (&rs->buf, &rs->buf_size, 0);
11517 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11519 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11520 error (_("Could not enable branch tracing for %s: %s"),
11521 target_pid_to_str (ptid), rs->buf + 2);
11523 error (_("Could not enable branch tracing for %s."),
11524 target_pid_to_str (ptid));
11527 tinfo = xzalloc (sizeof (*tinfo));
11528 tinfo->ptid = ptid;
11530 /* If we fail to read the configuration, we lose some information, but the
11531 tracing itself is not impacted. */
11534 btrace_read_config (&tinfo->conf);
11536 CATCH (err, RETURN_MASK_ERROR)
11538 if (err.message != NULL)
11539 warning ("%s", err.message);
11546 /* Disable branch tracing. */
11549 remote_disable_btrace (struct target_ops *self,
11550 struct btrace_target_info *tinfo)
11552 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11553 struct remote_state *rs = get_remote_state ();
11554 char *buf = rs->buf;
11555 char *endbuf = rs->buf + get_remote_packet_size ();
11557 if (packet_config_support (packet) != PACKET_ENABLE)
11558 error (_("Target does not support branch tracing."));
11560 set_general_thread (tinfo->ptid);
11562 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11564 getpkt (&rs->buf, &rs->buf_size, 0);
11566 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11568 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11569 error (_("Could not disable branch tracing for %s: %s"),
11570 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11572 error (_("Could not disable branch tracing for %s."),
11573 target_pid_to_str (tinfo->ptid));
11579 /* Teardown branch tracing. */
11582 remote_teardown_btrace (struct target_ops *self,
11583 struct btrace_target_info *tinfo)
11585 /* We must not talk to the target during teardown. */
11589 /* Read the branch trace. */
11591 static enum btrace_error
11592 remote_read_btrace (struct target_ops *self,
11593 struct btrace_data *btrace,
11594 struct btrace_target_info *tinfo,
11595 enum btrace_read_type type)
11597 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11598 struct remote_state *rs = get_remote_state ();
11599 struct cleanup *cleanup;
11603 if (packet_config_support (packet) != PACKET_ENABLE)
11604 error (_("Target does not support branch tracing."));
11606 #if !defined(HAVE_LIBEXPAT)
11607 error (_("Cannot process branch tracing result. XML parsing not supported."));
11612 case BTRACE_READ_ALL:
11615 case BTRACE_READ_NEW:
11618 case BTRACE_READ_DELTA:
11622 internal_error (__FILE__, __LINE__,
11623 _("Bad branch tracing read type: %u."),
11624 (unsigned int) type);
11627 xml = target_read_stralloc (¤t_target,
11628 TARGET_OBJECT_BTRACE, annex);
11630 return BTRACE_ERR_UNKNOWN;
11632 cleanup = make_cleanup (xfree, xml);
11633 parse_xml_btrace (btrace, xml);
11634 do_cleanups (cleanup);
11636 return BTRACE_ERR_NONE;
11639 static const struct btrace_config *
11640 remote_btrace_conf (struct target_ops *self,
11641 const struct btrace_target_info *tinfo)
11643 return &tinfo->conf;
11647 remote_augmented_libraries_svr4_read (struct target_ops *self)
11649 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11653 /* Implementation of to_load. */
11656 remote_load (struct target_ops *self, const char *name, int from_tty)
11658 generic_load (name, from_tty);
11661 /* Accepts an integer PID; returns a string representing a file that
11662 can be opened on the remote side to get the symbols for the child
11663 process. Returns NULL if the operation is not supported. */
11666 remote_pid_to_exec_file (struct target_ops *self, int pid)
11668 static char *filename = NULL;
11669 struct inferior *inf;
11670 char *annex = NULL;
11672 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
11675 if (filename != NULL)
11678 inf = find_inferior_pid (pid);
11680 internal_error (__FILE__, __LINE__,
11681 _("not currently attached to process %d"), pid);
11683 if (!inf->fake_pid_p)
11685 const int annex_size = 9;
11687 annex = alloca (annex_size);
11688 xsnprintf (annex, annex_size, "%x", pid);
11691 filename = target_read_stralloc (¤t_target,
11692 TARGET_OBJECT_EXEC_FILE, annex);
11698 init_remote_ops (void)
11700 remote_ops.to_shortname = "remote";
11701 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11702 remote_ops.to_doc =
11703 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11704 Specify the serial device it is connected to\n\
11705 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11706 remote_ops.to_open = remote_open;
11707 remote_ops.to_close = remote_close;
11708 remote_ops.to_detach = remote_detach;
11709 remote_ops.to_disconnect = remote_disconnect;
11710 remote_ops.to_resume = remote_resume;
11711 remote_ops.to_wait = remote_wait;
11712 remote_ops.to_fetch_registers = remote_fetch_registers;
11713 remote_ops.to_store_registers = remote_store_registers;
11714 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11715 remote_ops.to_files_info = remote_files_info;
11716 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11717 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11718 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
11719 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
11720 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
11721 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
11722 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11723 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11724 remote_ops.to_watchpoint_addr_within_range =
11725 remote_watchpoint_addr_within_range;
11726 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11727 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11728 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11729 remote_ops.to_region_ok_for_hw_watchpoint
11730 = remote_region_ok_for_hw_watchpoint;
11731 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11732 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11733 remote_ops.to_kill = remote_kill;
11734 remote_ops.to_load = remote_load;
11735 remote_ops.to_mourn_inferior = remote_mourn;
11736 remote_ops.to_pass_signals = remote_pass_signals;
11737 remote_ops.to_program_signals = remote_program_signals;
11738 remote_ops.to_thread_alive = remote_thread_alive;
11739 remote_ops.to_update_thread_list = remote_update_thread_list;
11740 remote_ops.to_pid_to_str = remote_pid_to_str;
11741 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11742 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11743 remote_ops.to_stop = remote_stop;
11744 remote_ops.to_xfer_partial = remote_xfer_partial;
11745 remote_ops.to_rcmd = remote_rcmd;
11746 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
11747 remote_ops.to_log_command = serial_log_command;
11748 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11749 remote_ops.to_stratum = process_stratum;
11750 remote_ops.to_has_all_memory = default_child_has_all_memory;
11751 remote_ops.to_has_memory = default_child_has_memory;
11752 remote_ops.to_has_stack = default_child_has_stack;
11753 remote_ops.to_has_registers = default_child_has_registers;
11754 remote_ops.to_has_execution = default_child_has_execution;
11755 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11756 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11757 remote_ops.to_magic = OPS_MAGIC;
11758 remote_ops.to_memory_map = remote_memory_map;
11759 remote_ops.to_flash_erase = remote_flash_erase;
11760 remote_ops.to_flash_done = remote_flash_done;
11761 remote_ops.to_read_description = remote_read_description;
11762 remote_ops.to_search_memory = remote_search_memory;
11763 remote_ops.to_can_async_p = remote_can_async_p;
11764 remote_ops.to_is_async_p = remote_is_async_p;
11765 remote_ops.to_async = remote_async;
11766 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11767 remote_ops.to_terminal_ours = remote_terminal_ours;
11768 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11769 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11770 remote_ops.to_supports_disable_randomization
11771 = remote_supports_disable_randomization;
11772 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
11773 remote_ops.to_fileio_open = remote_hostio_open;
11774 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11775 remote_ops.to_fileio_pread = remote_hostio_pread;
11776 remote_ops.to_fileio_fstat = remote_hostio_fstat;
11777 remote_ops.to_fileio_close = remote_hostio_close;
11778 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11779 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11780 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11781 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11782 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11783 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11784 remote_ops.to_trace_init = remote_trace_init;
11785 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11786 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11787 remote_ops.to_download_trace_state_variable
11788 = remote_download_trace_state_variable;
11789 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11790 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11791 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11792 remote_ops.to_trace_start = remote_trace_start;
11793 remote_ops.to_get_trace_status = remote_get_trace_status;
11794 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11795 remote_ops.to_trace_stop = remote_trace_stop;
11796 remote_ops.to_trace_find = remote_trace_find;
11797 remote_ops.to_get_trace_state_variable_value
11798 = remote_get_trace_state_variable_value;
11799 remote_ops.to_save_trace_data = remote_save_trace_data;
11800 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11801 remote_ops.to_upload_trace_state_variables
11802 = remote_upload_trace_state_variables;
11803 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11804 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11805 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11806 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11807 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11808 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11809 remote_ops.to_core_of_thread = remote_core_of_thread;
11810 remote_ops.to_verify_memory = remote_verify_memory;
11811 remote_ops.to_get_tib_address = remote_get_tib_address;
11812 remote_ops.to_set_permissions = remote_set_permissions;
11813 remote_ops.to_static_tracepoint_marker_at
11814 = remote_static_tracepoint_marker_at;
11815 remote_ops.to_static_tracepoint_markers_by_strid
11816 = remote_static_tracepoint_markers_by_strid;
11817 remote_ops.to_traceframe_info = remote_traceframe_info;
11818 remote_ops.to_use_agent = remote_use_agent;
11819 remote_ops.to_can_use_agent = remote_can_use_agent;
11820 remote_ops.to_supports_btrace = remote_supports_btrace;
11821 remote_ops.to_enable_btrace = remote_enable_btrace;
11822 remote_ops.to_disable_btrace = remote_disable_btrace;
11823 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11824 remote_ops.to_read_btrace = remote_read_btrace;
11825 remote_ops.to_btrace_conf = remote_btrace_conf;
11826 remote_ops.to_augmented_libraries_svr4_read =
11827 remote_augmented_libraries_svr4_read;
11830 /* Set up the extended remote vector by making a copy of the standard
11831 remote vector and adding to it. */
11834 init_extended_remote_ops (void)
11836 extended_remote_ops = remote_ops;
11838 extended_remote_ops.to_shortname = "extended-remote";
11839 extended_remote_ops.to_longname =
11840 "Extended remote serial target in gdb-specific protocol";
11841 extended_remote_ops.to_doc =
11842 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11843 Specify the serial device it is connected to (e.g. /dev/ttya).";
11844 extended_remote_ops.to_open = extended_remote_open;
11845 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11846 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11847 extended_remote_ops.to_detach = extended_remote_detach;
11848 extended_remote_ops.to_attach = extended_remote_attach;
11849 extended_remote_ops.to_post_attach = extended_remote_post_attach;
11850 extended_remote_ops.to_kill = extended_remote_kill;
11851 extended_remote_ops.to_supports_disable_randomization
11852 = extended_remote_supports_disable_randomization;
11856 remote_can_async_p (struct target_ops *ops)
11858 struct remote_state *rs = get_remote_state ();
11860 if (!target_async_permitted)
11861 /* We only enable async when the user specifically asks for it. */
11864 /* We're async whenever the serial device is. */
11865 return serial_can_async_p (rs->remote_desc);
11869 remote_is_async_p (struct target_ops *ops)
11871 struct remote_state *rs = get_remote_state ();
11873 if (!target_async_permitted)
11874 /* We only enable async when the user specifically asks for it. */
11877 /* We're async whenever the serial device is. */
11878 return serial_is_async_p (rs->remote_desc);
11881 /* Pass the SERIAL event on and up to the client. One day this code
11882 will be able to delay notifying the client of an event until the
11883 point where an entire packet has been received. */
11885 static serial_event_ftype remote_async_serial_handler;
11888 remote_async_serial_handler (struct serial *scb, void *context)
11890 struct remote_state *rs = context;
11892 /* Don't propogate error information up to the client. Instead let
11893 the client find out about the error by querying the target. */
11894 inferior_event_handler (INF_REG_EVENT, NULL);
11898 remote_async_inferior_event_handler (gdb_client_data data)
11900 inferior_event_handler (INF_REG_EVENT, NULL);
11904 remote_async (struct target_ops *ops, int enable)
11906 struct remote_state *rs = get_remote_state ();
11910 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11912 /* If there are pending events in the stop reply queue tell the
11913 event loop to process them. */
11914 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11915 mark_async_event_handler (remote_async_inferior_event_token);
11919 serial_async (rs->remote_desc, NULL, NULL);
11920 clear_async_event_handler (remote_async_inferior_event_token);
11925 set_remote_cmd (char *args, int from_tty)
11927 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
11931 show_remote_cmd (char *args, int from_tty)
11933 /* We can't just use cmd_show_list here, because we want to skip
11934 the redundant "show remote Z-packet" and the legacy aliases. */
11935 struct cleanup *showlist_chain;
11936 struct cmd_list_element *list = remote_show_cmdlist;
11937 struct ui_out *uiout = current_uiout;
11939 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11940 for (; list != NULL; list = list->next)
11941 if (strcmp (list->name, "Z-packet") == 0)
11943 else if (list->type == not_set_cmd)
11944 /* Alias commands are exactly like the original, except they
11945 don't have the normal type. */
11949 struct cleanup *option_chain
11950 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11952 ui_out_field_string (uiout, "name", list->name);
11953 ui_out_text (uiout, ": ");
11954 if (list->type == show_cmd)
11955 do_show_command ((char *) NULL, from_tty, list);
11957 cmd_func (list, NULL, from_tty);
11958 /* Close the tuple. */
11959 do_cleanups (option_chain);
11962 /* Close the tuple. */
11963 do_cleanups (showlist_chain);
11967 /* Function to be called whenever a new objfile (shlib) is detected. */
11969 remote_new_objfile (struct objfile *objfile)
11971 struct remote_state *rs = get_remote_state ();
11973 if (rs->remote_desc != 0) /* Have a remote connection. */
11974 remote_check_symbols ();
11977 /* Pull all the tracepoints defined on the target and create local
11978 data structures representing them. We don't want to create real
11979 tracepoints yet, we don't want to mess up the user's existing
11983 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
11985 struct remote_state *rs = get_remote_state ();
11988 /* Ask for a first packet of tracepoint definition. */
11990 getpkt (&rs->buf, &rs->buf_size, 0);
11992 while (*p && *p != 'l')
11994 parse_tracepoint_definition (p, utpp);
11995 /* Ask for another packet of tracepoint definition. */
11997 getpkt (&rs->buf, &rs->buf_size, 0);
12004 remote_upload_trace_state_variables (struct target_ops *self,
12005 struct uploaded_tsv **utsvp)
12007 struct remote_state *rs = get_remote_state ();
12010 /* Ask for a first packet of variable definition. */
12012 getpkt (&rs->buf, &rs->buf_size, 0);
12014 while (*p && *p != 'l')
12016 parse_tsv_definition (p, utsvp);
12017 /* Ask for another packet of variable definition. */
12019 getpkt (&rs->buf, &rs->buf_size, 0);
12025 /* The "set/show range-stepping" show hook. */
12028 show_range_stepping (struct ui_file *file, int from_tty,
12029 struct cmd_list_element *c,
12032 fprintf_filtered (file,
12033 _("Debugger's willingness to use range stepping "
12034 "is %s.\n"), value);
12037 /* The "set/show range-stepping" set hook. */
12040 set_range_stepping (char *ignore_args, int from_tty,
12041 struct cmd_list_element *c)
12043 struct remote_state *rs = get_remote_state ();
12045 /* Whene enabling, check whether range stepping is actually
12046 supported by the target, and warn if not. */
12047 if (use_range_stepping)
12049 if (rs->remote_desc != NULL)
12051 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12052 remote_vcont_probe (rs);
12054 if (packet_support (PACKET_vCont) == PACKET_ENABLE
12055 && rs->supports_vCont.r)
12059 warning (_("Range stepping is not supported by the current target"));
12064 _initialize_remote (void)
12066 struct remote_state *rs;
12067 struct cmd_list_element *cmd;
12068 const char *cmd_name;
12070 /* architecture specific data */
12071 remote_gdbarch_data_handle =
12072 gdbarch_data_register_post_init (init_remote_state);
12073 remote_g_packet_data_handle =
12074 gdbarch_data_register_pre_init (remote_g_packet_data_init);
12076 /* Initialize the per-target state. At the moment there is only one
12077 of these, not one per target. Only one target is active at a
12079 remote_state = new_remote_state ();
12081 init_remote_ops ();
12082 add_target (&remote_ops);
12084 init_extended_remote_ops ();
12085 add_target (&extended_remote_ops);
12087 /* Hook into new objfile notification. */
12088 observer_attach_new_objfile (remote_new_objfile);
12089 /* We're no longer interested in notification events of an inferior
12091 observer_attach_inferior_exit (discard_pending_stop_replies);
12093 /* Set up signal handlers. */
12094 async_sigint_remote_token =
12095 create_async_signal_handler (async_remote_interrupt, NULL);
12096 async_sigint_remote_twice_token =
12097 create_async_signal_handler (async_remote_interrupt_twice, NULL);
12100 init_remote_threadtests ();
12103 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
12104 /* set/show remote ... */
12106 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12107 Remote protocol specific variables\n\
12108 Configure various remote-protocol specific variables such as\n\
12109 the packets being used"),
12110 &remote_set_cmdlist, "set remote ",
12111 0 /* allow-unknown */, &setlist);
12112 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12113 Remote protocol specific variables\n\
12114 Configure various remote-protocol specific variables such as\n\
12115 the packets being used"),
12116 &remote_show_cmdlist, "show remote ",
12117 0 /* allow-unknown */, &showlist);
12119 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12120 Compare section data on target to the exec file.\n\
12121 Argument is a single section name (default: all loaded sections).\n\
12122 To compare only read-only loaded sections, specify the -r option."),
12125 add_cmd ("packet", class_maintenance, packet_command, _("\
12126 Send an arbitrary packet to a remote target.\n\
12127 maintenance packet TEXT\n\
12128 If GDB is talking to an inferior via the GDB serial protocol, then\n\
12129 this command sends the string TEXT to the inferior, and displays the\n\
12130 response packet. GDB supplies the initial `$' character, and the\n\
12131 terminating `#' character and checksum."),
12134 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12135 Set whether to send break if interrupted."), _("\
12136 Show whether to send break if interrupted."), _("\
12137 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12138 set_remotebreak, show_remotebreak,
12139 &setlist, &showlist);
12140 cmd_name = "remotebreak";
12141 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12142 deprecate_cmd (cmd, "set remote interrupt-sequence");
12143 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12144 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12145 deprecate_cmd (cmd, "show remote interrupt-sequence");
12147 add_setshow_enum_cmd ("interrupt-sequence", class_support,
12148 interrupt_sequence_modes, &interrupt_sequence_mode,
12150 Set interrupt sequence to remote target."), _("\
12151 Show interrupt sequence to remote target."), _("\
12152 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12153 NULL, show_interrupt_sequence,
12154 &remote_set_cmdlist,
12155 &remote_show_cmdlist);
12157 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12158 &interrupt_on_connect, _("\
12159 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12160 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12161 If set, interrupt sequence is sent to remote target."),
12163 &remote_set_cmdlist, &remote_show_cmdlist);
12165 /* Install commands for configuring memory read/write packets. */
12167 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12168 Set the maximum number of bytes per memory write packet (deprecated)."),
12170 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12171 Show the maximum number of bytes per memory write packet (deprecated)."),
12173 add_cmd ("memory-write-packet-size", no_class,
12174 set_memory_write_packet_size, _("\
12175 Set the maximum number of bytes per memory-write packet.\n\
12176 Specify the number of bytes in a packet or 0 (zero) for the\n\
12177 default packet size. The actual limit is further reduced\n\
12178 dependent on the target. Specify ``fixed'' to disable the\n\
12179 further restriction and ``limit'' to enable that restriction."),
12180 &remote_set_cmdlist);
12181 add_cmd ("memory-read-packet-size", no_class,
12182 set_memory_read_packet_size, _("\
12183 Set the maximum number of bytes per memory-read packet.\n\
12184 Specify the number of bytes in a packet or 0 (zero) for the\n\
12185 default packet size. The actual limit is further reduced\n\
12186 dependent on the target. Specify ``fixed'' to disable the\n\
12187 further restriction and ``limit'' to enable that restriction."),
12188 &remote_set_cmdlist);
12189 add_cmd ("memory-write-packet-size", no_class,
12190 show_memory_write_packet_size,
12191 _("Show the maximum number of bytes per memory-write packet."),
12192 &remote_show_cmdlist);
12193 add_cmd ("memory-read-packet-size", no_class,
12194 show_memory_read_packet_size,
12195 _("Show the maximum number of bytes per memory-read packet."),
12196 &remote_show_cmdlist);
12198 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12199 &remote_hw_watchpoint_limit, _("\
12200 Set the maximum number of target hardware watchpoints."), _("\
12201 Show the maximum number of target hardware watchpoints."), _("\
12202 Specify a negative limit for unlimited."),
12203 NULL, NULL, /* FIXME: i18n: The maximum
12204 number of target hardware
12205 watchpoints is %s. */
12206 &remote_set_cmdlist, &remote_show_cmdlist);
12207 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12208 &remote_hw_watchpoint_length_limit, _("\
12209 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12210 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12211 Specify a negative limit for unlimited."),
12212 NULL, NULL, /* FIXME: i18n: The maximum
12213 length (in bytes) of a target
12214 hardware watchpoint is %s. */
12215 &remote_set_cmdlist, &remote_show_cmdlist);
12216 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12217 &remote_hw_breakpoint_limit, _("\
12218 Set the maximum number of target hardware breakpoints."), _("\
12219 Show the maximum number of target hardware breakpoints."), _("\
12220 Specify a negative limit for unlimited."),
12221 NULL, NULL, /* FIXME: i18n: The maximum
12222 number of target hardware
12223 breakpoints is %s. */
12224 &remote_set_cmdlist, &remote_show_cmdlist);
12226 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12227 &remote_address_size, _("\
12228 Set the maximum size of the address (in bits) in a memory packet."), _("\
12229 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12231 NULL, /* FIXME: i18n: */
12232 &setlist, &showlist);
12234 init_all_packet_configs ();
12236 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12237 "X", "binary-download", 1);
12239 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12240 "vCont", "verbose-resume", 0);
12242 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12243 "QPassSignals", "pass-signals", 0);
12245 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12246 "QProgramSignals", "program-signals", 0);
12248 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12249 "qSymbol", "symbol-lookup", 0);
12251 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12252 "P", "set-register", 1);
12254 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12255 "p", "fetch-register", 1);
12257 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12258 "Z0", "software-breakpoint", 0);
12260 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12261 "Z1", "hardware-breakpoint", 0);
12263 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12264 "Z2", "write-watchpoint", 0);
12266 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12267 "Z3", "read-watchpoint", 0);
12269 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12270 "Z4", "access-watchpoint", 0);
12272 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12273 "qXfer:auxv:read", "read-aux-vector", 0);
12275 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
12276 "qXfer:exec-file:read", "pid-to-exec-file", 0);
12278 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12279 "qXfer:features:read", "target-features", 0);
12281 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12282 "qXfer:libraries:read", "library-info", 0);
12284 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12285 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12287 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12288 "qXfer:memory-map:read", "memory-map", 0);
12290 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12291 "qXfer:spu:read", "read-spu-object", 0);
12293 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12294 "qXfer:spu:write", "write-spu-object", 0);
12296 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12297 "qXfer:osdata:read", "osdata", 0);
12299 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12300 "qXfer:threads:read", "threads", 0);
12302 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12303 "qXfer:siginfo:read", "read-siginfo-object", 0);
12305 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12306 "qXfer:siginfo:write", "write-siginfo-object", 0);
12308 add_packet_config_cmd
12309 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12310 "qXfer:traceframe-info:read", "traceframe-info", 0);
12312 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12313 "qXfer:uib:read", "unwind-info-block", 0);
12315 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12316 "qGetTLSAddr", "get-thread-local-storage-address",
12319 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12320 "qGetTIBAddr", "get-thread-information-block-address",
12323 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12324 "bc", "reverse-continue", 0);
12326 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12327 "bs", "reverse-step", 0);
12329 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12330 "qSupported", "supported-packets", 0);
12332 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12333 "qSearch:memory", "search-memory", 0);
12335 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12336 "qTStatus", "trace-status", 0);
12338 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12339 "vFile:open", "hostio-open", 0);
12341 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12342 "vFile:pread", "hostio-pread", 0);
12344 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12345 "vFile:pwrite", "hostio-pwrite", 0);
12347 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12348 "vFile:close", "hostio-close", 0);
12350 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12351 "vFile:unlink", "hostio-unlink", 0);
12353 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12354 "vFile:readlink", "hostio-readlink", 0);
12356 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12357 "vFile:fstat", "hostio-fstat", 0);
12359 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12360 "vAttach", "attach", 0);
12362 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12365 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12366 "QStartNoAckMode", "noack", 0);
12368 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12369 "vKill", "kill", 0);
12371 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12372 "qAttached", "query-attached", 0);
12374 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12375 "ConditionalTracepoints",
12376 "conditional-tracepoints", 0);
12378 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12379 "ConditionalBreakpoints",
12380 "conditional-breakpoints", 0);
12382 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12383 "BreakpointCommands",
12384 "breakpoint-commands", 0);
12386 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12387 "FastTracepoints", "fast-tracepoints", 0);
12389 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12390 "TracepointSource", "TracepointSource", 0);
12392 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12393 "QAllow", "allow", 0);
12395 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12396 "StaticTracepoints", "static-tracepoints", 0);
12398 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12399 "InstallInTrace", "install-in-trace", 0);
12401 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12402 "qXfer:statictrace:read", "read-sdata-object", 0);
12404 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12405 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12407 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12408 "QDisableRandomization", "disable-randomization", 0);
12410 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12411 "QAgent", "agent", 0);
12413 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12414 "QTBuffer:size", "trace-buffer-size", 0);
12416 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12417 "Qbtrace:off", "disable-btrace", 0);
12419 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12420 "Qbtrace:bts", "enable-btrace", 0);
12422 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12423 "qXfer:btrace", "read-btrace", 0);
12425 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12426 "qXfer:btrace-conf", "read-btrace-conf", 0);
12428 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12429 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12431 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12432 "swbreak-feature", "swbreak-feature", 0);
12434 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12435 "hwbreak-feature", "hwbreak-feature", 0);
12437 /* Assert that we've registered "set remote foo-packet" commands
12438 for all packet configs. */
12442 for (i = 0; i < PACKET_MAX; i++)
12444 /* Ideally all configs would have a command associated. Some
12445 still don't though. */
12450 case PACKET_QNonStop:
12451 case PACKET_multiprocess_feature:
12452 case PACKET_EnableDisableTracepoints_feature:
12453 case PACKET_tracenz_feature:
12454 case PACKET_DisconnectedTracing_feature:
12455 case PACKET_augmented_libraries_svr4_read_feature:
12457 /* Additions to this list need to be well justified:
12458 pre-existing packets are OK; new packets are not. */
12466 /* This catches both forgetting to add a config command, and
12467 forgetting to remove a packet from the exception list. */
12468 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12472 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12473 Z sub-packet has its own set and show commands, but users may
12474 have sets to this variable in their .gdbinit files (or in their
12476 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12477 &remote_Z_packet_detect, _("\
12478 Set use of remote protocol `Z' packets"), _("\
12479 Show use of remote protocol `Z' packets "), _("\
12480 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12482 set_remote_protocol_Z_packet_cmd,
12483 show_remote_protocol_Z_packet_cmd,
12484 /* FIXME: i18n: Use of remote protocol
12485 `Z' packets is %s. */
12486 &remote_set_cmdlist, &remote_show_cmdlist);
12488 add_prefix_cmd ("remote", class_files, remote_command, _("\
12489 Manipulate files on the remote system\n\
12490 Transfer files to and from the remote target system."),
12491 &remote_cmdlist, "remote ",
12492 0 /* allow-unknown */, &cmdlist);
12494 add_cmd ("put", class_files, remote_put_command,
12495 _("Copy a local file to the remote system."),
12498 add_cmd ("get", class_files, remote_get_command,
12499 _("Copy a remote file to the local system."),
12502 add_cmd ("delete", class_files, remote_delete_command,
12503 _("Delete a remote file."),
12506 remote_exec_file = xstrdup ("");
12507 add_setshow_string_noescape_cmd ("exec-file", class_files,
12508 &remote_exec_file, _("\
12509 Set the remote pathname for \"run\""), _("\
12510 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12511 &remote_set_cmdlist, &remote_show_cmdlist);
12513 add_setshow_boolean_cmd ("range-stepping", class_run,
12514 &use_range_stepping, _("\
12515 Enable or disable range stepping."), _("\
12516 Show whether target-assisted range stepping is enabled."), _("\
12517 If on, and the target supports it, when stepping a source line, GDB\n\
12518 tells the target to step the corresponding range of addresses itself instead\n\
12519 of issuing multiple single-steps. This speeds up source level\n\
12520 stepping. If off, GDB always issues single-steps, even if range\n\
12521 stepping is supported by the target. The default is on."),
12522 set_range_stepping,
12523 show_range_stepping,
12527 /* Eventually initialize fileio. See fileio.c */
12528 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12530 /* Take advantage of the fact that the TID field is not used, to tag
12531 special ptids with it set to != 0. */
12532 magic_null_ptid = ptid_build (42000, -1, 1);
12533 not_sent_ptid = ptid_build (42000, -2, 1);
12534 any_thread_ptid = ptid_build (42000, 0, 1);
12536 target_buf_size = 2048;
12537 target_buf = xmalloc (target_buf_size);