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_libraries,
1256 PACKET_qXfer_libraries_svr4,
1257 PACKET_qXfer_memory_map,
1258 PACKET_qXfer_spu_read,
1259 PACKET_qXfer_spu_write,
1260 PACKET_qXfer_osdata,
1261 PACKET_qXfer_threads,
1262 PACKET_qXfer_statictrace_read,
1263 PACKET_qXfer_traceframe_info,
1269 PACKET_QPassSignals,
1270 PACKET_QProgramSignals,
1272 PACKET_qSearch_memory,
1275 PACKET_QStartNoAckMode,
1277 PACKET_qXfer_siginfo_read,
1278 PACKET_qXfer_siginfo_write,
1281 /* Support for conditional tracepoints. */
1282 PACKET_ConditionalTracepoints,
1284 /* Support for target-side breakpoint conditions. */
1285 PACKET_ConditionalBreakpoints,
1287 /* Support for target-side breakpoint commands. */
1288 PACKET_BreakpointCommands,
1290 /* Support for fast tracepoints. */
1291 PACKET_FastTracepoints,
1293 /* Support for static tracepoints. */
1294 PACKET_StaticTracepoints,
1296 /* Support for installing tracepoints while a trace experiment is
1298 PACKET_InstallInTrace,
1302 PACKET_TracepointSource,
1305 PACKET_QDisableRandomization,
1307 PACKET_QTBuffer_size,
1310 PACKET_qXfer_btrace,
1312 /* Support for the QNonStop packet. */
1315 /* Support for multi-process extensions. */
1316 PACKET_multiprocess_feature,
1318 /* Support for enabling and disabling tracepoints while a trace
1319 experiment is running. */
1320 PACKET_EnableDisableTracepoints_feature,
1322 /* Support for collecting strings using the tracenz bytecode. */
1323 PACKET_tracenz_feature,
1325 /* Support for continuing to run a trace experiment while GDB is
1327 PACKET_DisconnectedTracing_feature,
1329 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1330 PACKET_augmented_libraries_svr4_read_feature,
1332 /* Support for the qXfer:btrace-conf:read packet. */
1333 PACKET_qXfer_btrace_conf,
1335 /* Support for the Qbtrace-conf:bts:size packet. */
1336 PACKET_Qbtrace_conf_bts_size,
1338 /* Support for swbreak+ feature. */
1339 PACKET_swbreak_feature,
1341 /* Support for hwbreak+ feature. */
1342 PACKET_hwbreak_feature,
1347 static struct packet_config remote_protocol_packets[PACKET_MAX];
1349 /* Returns the packet's corresponding "set remote foo-packet" command
1350 state. See struct packet_config for more details. */
1352 static enum auto_boolean
1353 packet_set_cmd_state (int packet)
1355 return remote_protocol_packets[packet].detect;
1358 /* Returns whether a given packet or feature is supported. This takes
1359 into account the state of the corresponding "set remote foo-packet"
1360 command, which may be used to bypass auto-detection. */
1362 static enum packet_support
1363 packet_config_support (struct packet_config *config)
1365 switch (config->detect)
1367 case AUTO_BOOLEAN_TRUE:
1368 return PACKET_ENABLE;
1369 case AUTO_BOOLEAN_FALSE:
1370 return PACKET_DISABLE;
1371 case AUTO_BOOLEAN_AUTO:
1372 return config->support;
1374 gdb_assert_not_reached (_("bad switch"));
1378 /* Same as packet_config_support, but takes the packet's enum value as
1381 static enum packet_support
1382 packet_support (int packet)
1384 struct packet_config *config = &remote_protocol_packets[packet];
1386 return packet_config_support (config);
1390 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1391 struct cmd_list_element *c,
1394 struct packet_config *packet;
1396 for (packet = remote_protocol_packets;
1397 packet < &remote_protocol_packets[PACKET_MAX];
1400 if (&packet->detect == c->var)
1402 show_packet_config_cmd (packet);
1406 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1410 /* Should we try one of the 'Z' requests? */
1414 Z_PACKET_SOFTWARE_BP,
1415 Z_PACKET_HARDWARE_BP,
1422 /* For compatibility with older distributions. Provide a ``set remote
1423 Z-packet ...'' command that updates all the Z packet types. */
1425 static enum auto_boolean remote_Z_packet_detect;
1428 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1429 struct cmd_list_element *c)
1433 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1434 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1438 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1439 struct cmd_list_element *c,
1444 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1446 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1450 /* Returns true if the multi-process extensions are in effect. */
1453 remote_multi_process_p (struct remote_state *rs)
1455 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1458 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1459 static struct async_signal_handler *async_sigint_remote_twice_token;
1460 static struct async_signal_handler *async_sigint_remote_token;
1463 /* Asynchronous signal handle registered as event loop source for
1464 when we have pending events ready to be passed to the core. */
1466 static struct async_event_handler *remote_async_inferior_event_token;
1470 static ptid_t magic_null_ptid;
1471 static ptid_t not_sent_ptid;
1472 static ptid_t any_thread_ptid;
1474 /* Find out if the stub attached to PID (and hence GDB should offer to
1475 detach instead of killing it when bailing out). */
1478 remote_query_attached (int pid)
1480 struct remote_state *rs = get_remote_state ();
1481 size_t size = get_remote_packet_size ();
1483 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1486 if (remote_multi_process_p (rs))
1487 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1489 xsnprintf (rs->buf, size, "qAttached");
1492 getpkt (&rs->buf, &rs->buf_size, 0);
1494 switch (packet_ok (rs->buf,
1495 &remote_protocol_packets[PACKET_qAttached]))
1498 if (strcmp (rs->buf, "1") == 0)
1502 warning (_("Remote failure reply: %s"), rs->buf);
1504 case PACKET_UNKNOWN:
1511 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1512 has been invented by GDB, instead of reported by the target. Since
1513 we can be connected to a remote system before before knowing about
1514 any inferior, mark the target with execution when we find the first
1515 inferior. If ATTACHED is 1, then we had just attached to this
1516 inferior. If it is 0, then we just created this inferior. If it
1517 is -1, then try querying the remote stub to find out if it had
1518 attached to the inferior or not. */
1520 static struct inferior *
1521 remote_add_inferior (int fake_pid_p, int pid, int attached)
1523 struct inferior *inf;
1525 /* Check whether this process we're learning about is to be
1526 considered attached, or if is to be considered to have been
1527 spawned by the stub. */
1529 attached = remote_query_attached (pid);
1531 if (gdbarch_has_global_solist (target_gdbarch ()))
1533 /* If the target shares code across all inferiors, then every
1534 attach adds a new inferior. */
1535 inf = add_inferior (pid);
1537 /* ... and every inferior is bound to the same program space.
1538 However, each inferior may still have its own address
1540 inf->aspace = maybe_new_address_space ();
1541 inf->pspace = current_program_space;
1545 /* In the traditional debugging scenario, there's a 1-1 match
1546 between program/address spaces. We simply bind the inferior
1547 to the program space's address space. */
1548 inf = current_inferior ();
1549 inferior_appeared (inf, pid);
1552 inf->attach_flag = attached;
1553 inf->fake_pid_p = fake_pid_p;
1558 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1559 according to RUNNING. */
1562 remote_add_thread (ptid_t ptid, int running)
1564 struct remote_state *rs = get_remote_state ();
1566 /* GDB historically didn't pull threads in the initial connection
1567 setup. If the remote target doesn't even have a concept of
1568 threads (e.g., a bare-metal target), even if internally we
1569 consider that a single-threaded target, mentioning a new thread
1570 might be confusing to the user. Be silent then, preserving the
1571 age old behavior. */
1572 if (rs->starting_up)
1573 add_thread_silent (ptid);
1577 set_executing (ptid, running);
1578 set_running (ptid, running);
1581 /* Come here when we learn about a thread id from the remote target.
1582 It may be the first time we hear about such thread, so take the
1583 opportunity to add it to GDB's thread list. In case this is the
1584 first time we're noticing its corresponding inferior, add it to
1585 GDB's inferior list as well. */
1588 remote_notice_new_inferior (ptid_t currthread, int running)
1590 /* If this is a new thread, add it to GDB's thread list.
1591 If we leave it up to WFI to do this, bad things will happen. */
1593 if (in_thread_list (currthread) && is_exited (currthread))
1595 /* We're seeing an event on a thread id we knew had exited.
1596 This has to be a new thread reusing the old id. Add it. */
1597 remote_add_thread (currthread, running);
1601 if (!in_thread_list (currthread))
1603 struct inferior *inf = NULL;
1604 int pid = ptid_get_pid (currthread);
1606 if (ptid_is_pid (inferior_ptid)
1607 && pid == ptid_get_pid (inferior_ptid))
1609 /* inferior_ptid has no thread member yet. This can happen
1610 with the vAttach -> remote_wait,"TAAthread:" path if the
1611 stub doesn't support qC. This is the first stop reported
1612 after an attach, so this is the main thread. Update the
1613 ptid in the thread list. */
1614 if (in_thread_list (pid_to_ptid (pid)))
1615 thread_change_ptid (inferior_ptid, currthread);
1618 remote_add_thread (currthread, running);
1619 inferior_ptid = currthread;
1624 if (ptid_equal (magic_null_ptid, inferior_ptid))
1626 /* inferior_ptid is not set yet. This can happen with the
1627 vRun -> remote_wait,"TAAthread:" path if the stub
1628 doesn't support qC. This is the first stop reported
1629 after an attach, so this is the main thread. Update the
1630 ptid in the thread list. */
1631 thread_change_ptid (inferior_ptid, currthread);
1635 /* When connecting to a target remote, or to a target
1636 extended-remote which already was debugging an inferior, we
1637 may not know about it yet. Add it before adding its child
1638 thread, so notifications are emitted in a sensible order. */
1639 if (!in_inferior_list (ptid_get_pid (currthread)))
1641 struct remote_state *rs = get_remote_state ();
1642 int fake_pid_p = !remote_multi_process_p (rs);
1644 inf = remote_add_inferior (fake_pid_p,
1645 ptid_get_pid (currthread), -1);
1648 /* This is really a new thread. Add it. */
1649 remote_add_thread (currthread, running);
1651 /* If we found a new inferior, let the common code do whatever
1652 it needs to with it (e.g., read shared libraries, insert
1653 breakpoints), unless we're just setting up an all-stop
1657 struct remote_state *rs = get_remote_state ();
1659 if (non_stop || !rs->starting_up)
1660 notice_new_inferior (currthread, running, 0);
1665 /* Return the private thread data, creating it if necessary. */
1667 static struct private_thread_info *
1668 demand_private_info (ptid_t ptid)
1670 struct thread_info *info = find_thread_ptid (ptid);
1676 info->priv = xmalloc (sizeof (*(info->priv)));
1677 info->private_dtor = free_private_thread_info;
1678 info->priv->core = -1;
1679 info->priv->extra = 0;
1685 /* Call this function as a result of
1686 1) A halt indication (T packet) containing a thread id
1687 2) A direct query of currthread
1688 3) Successful execution of set thread */
1691 record_currthread (struct remote_state *rs, ptid_t currthread)
1693 rs->general_thread = currthread;
1696 /* If 'QPassSignals' is supported, tell the remote stub what signals
1697 it can simply pass through to the inferior without reporting. */
1700 remote_pass_signals (struct target_ops *self,
1701 int numsigs, unsigned char *pass_signals)
1703 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1705 char *pass_packet, *p;
1707 struct remote_state *rs = get_remote_state ();
1709 gdb_assert (numsigs < 256);
1710 for (i = 0; i < numsigs; i++)
1712 if (pass_signals[i])
1715 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1716 strcpy (pass_packet, "QPassSignals:");
1717 p = pass_packet + strlen (pass_packet);
1718 for (i = 0; i < numsigs; i++)
1720 if (pass_signals[i])
1723 *p++ = tohex (i >> 4);
1724 *p++ = tohex (i & 15);
1733 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1735 putpkt (pass_packet);
1736 getpkt (&rs->buf, &rs->buf_size, 0);
1737 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1738 if (rs->last_pass_packet)
1739 xfree (rs->last_pass_packet);
1740 rs->last_pass_packet = pass_packet;
1743 xfree (pass_packet);
1747 /* If 'QProgramSignals' is supported, tell the remote stub what
1748 signals it should pass through to the inferior when detaching. */
1751 remote_program_signals (struct target_ops *self,
1752 int numsigs, unsigned char *signals)
1754 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1758 struct remote_state *rs = get_remote_state ();
1760 gdb_assert (numsigs < 256);
1761 for (i = 0; i < numsigs; i++)
1766 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1767 strcpy (packet, "QProgramSignals:");
1768 p = packet + strlen (packet);
1769 for (i = 0; i < numsigs; i++)
1771 if (signal_pass_state (i))
1774 *p++ = tohex (i >> 4);
1775 *p++ = tohex (i & 15);
1784 if (!rs->last_program_signals_packet
1785 || strcmp (rs->last_program_signals_packet, packet) != 0)
1788 getpkt (&rs->buf, &rs->buf_size, 0);
1789 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1790 xfree (rs->last_program_signals_packet);
1791 rs->last_program_signals_packet = packet;
1798 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1799 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1800 thread. If GEN is set, set the general thread, if not, then set
1801 the step/continue thread. */
1803 set_thread (struct ptid ptid, int gen)
1805 struct remote_state *rs = get_remote_state ();
1806 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1807 char *buf = rs->buf;
1808 char *endbuf = rs->buf + get_remote_packet_size ();
1810 if (ptid_equal (state, ptid))
1814 *buf++ = gen ? 'g' : 'c';
1815 if (ptid_equal (ptid, magic_null_ptid))
1816 xsnprintf (buf, endbuf - buf, "0");
1817 else if (ptid_equal (ptid, any_thread_ptid))
1818 xsnprintf (buf, endbuf - buf, "0");
1819 else if (ptid_equal (ptid, minus_one_ptid))
1820 xsnprintf (buf, endbuf - buf, "-1");
1822 write_ptid (buf, endbuf, ptid);
1824 getpkt (&rs->buf, &rs->buf_size, 0);
1826 rs->general_thread = ptid;
1828 rs->continue_thread = ptid;
1832 set_general_thread (struct ptid ptid)
1834 set_thread (ptid, 1);
1838 set_continue_thread (struct ptid ptid)
1840 set_thread (ptid, 0);
1843 /* Change the remote current process. Which thread within the process
1844 ends up selected isn't important, as long as it is the same process
1845 as what INFERIOR_PTID points to.
1847 This comes from that fact that there is no explicit notion of
1848 "selected process" in the protocol. The selected process for
1849 general operations is the process the selected general thread
1853 set_general_process (void)
1855 struct remote_state *rs = get_remote_state ();
1857 /* If the remote can't handle multiple processes, don't bother. */
1858 if (!rs->extended || !remote_multi_process_p (rs))
1861 /* We only need to change the remote current thread if it's pointing
1862 at some other process. */
1863 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1864 set_general_thread (inferior_ptid);
1868 /* Return nonzero if this is the main thread that we made up ourselves
1869 to model non-threaded targets as single-threaded. */
1872 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1874 struct remote_state *rs = get_remote_state ();
1877 if (ptid_equal (ptid, magic_null_ptid))
1878 /* The main thread is always alive. */
1881 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
1882 /* The main thread is always alive. This can happen after a
1883 vAttach, if the remote side doesn't support
1890 /* Return nonzero if the thread PTID is still alive on the remote
1894 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1896 struct remote_state *rs = get_remote_state ();
1899 /* Check if this is a thread that we made up ourselves to model
1900 non-threaded targets as single-threaded. */
1901 if (remote_thread_always_alive (ops, ptid))
1905 endp = rs->buf + get_remote_packet_size ();
1908 write_ptid (p, endp, ptid);
1911 getpkt (&rs->buf, &rs->buf_size, 0);
1912 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1915 /* About these extended threadlist and threadinfo packets. They are
1916 variable length packets but, the fields within them are often fixed
1917 length. They are redundent enough to send over UDP as is the
1918 remote protocol in general. There is a matching unit test module
1921 /* WARNING: This threadref data structure comes from the remote O.S.,
1922 libstub protocol encoding, and remote.c. It is not particularly
1925 /* Right now, the internal structure is int. We want it to be bigger.
1926 Plan to fix this. */
1928 typedef int gdb_threadref; /* Internal GDB thread reference. */
1930 /* gdb_ext_thread_info is an internal GDB data structure which is
1931 equivalent to the reply of the remote threadinfo packet. */
1933 struct gdb_ext_thread_info
1935 threadref threadid; /* External form of thread reference. */
1936 int active; /* Has state interesting to GDB?
1938 char display[256]; /* Brief state display, name,
1939 blocked/suspended. */
1940 char shortname[32]; /* To be used to name threads. */
1941 char more_display[256]; /* Long info, statistics, queue depth,
1945 /* The volume of remote transfers can be limited by submitting
1946 a mask containing bits specifying the desired information.
1947 Use a union of these values as the 'selection' parameter to
1948 get_thread_info. FIXME: Make these TAG names more thread specific. */
1950 #define TAG_THREADID 1
1951 #define TAG_EXISTS 2
1952 #define TAG_DISPLAY 4
1953 #define TAG_THREADNAME 8
1954 #define TAG_MOREDISPLAY 16
1956 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1958 static char *unpack_nibble (char *buf, int *val);
1960 static char *unpack_byte (char *buf, int *value);
1962 static char *pack_int (char *buf, int value);
1964 static char *unpack_int (char *buf, int *value);
1966 static char *unpack_string (char *src, char *dest, int length);
1968 static char *pack_threadid (char *pkt, threadref *id);
1970 static char *unpack_threadid (char *inbuf, threadref *id);
1972 void int_to_threadref (threadref *id, int value);
1974 static int threadref_to_int (threadref *ref);
1976 static void copy_threadref (threadref *dest, threadref *src);
1978 static int threadmatch (threadref *dest, threadref *src);
1980 static char *pack_threadinfo_request (char *pkt, int mode,
1983 static int remote_unpack_thread_info_response (char *pkt,
1984 threadref *expectedref,
1985 struct gdb_ext_thread_info
1989 static int remote_get_threadinfo (threadref *threadid,
1990 int fieldset, /*TAG mask */
1991 struct gdb_ext_thread_info *info);
1993 static char *pack_threadlist_request (char *pkt, int startflag,
1995 threadref *nextthread);
1997 static int parse_threadlist_response (char *pkt,
1999 threadref *original_echo,
2000 threadref *resultlist,
2003 static int remote_get_threadlist (int startflag,
2004 threadref *nextthread,
2008 threadref *threadlist);
2010 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2012 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2013 void *context, int looplimit);
2015 static int remote_newthread_step (threadref *ref, void *context);
2018 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2019 buffer we're allowed to write to. Returns
2020 BUF+CHARACTERS_WRITTEN. */
2023 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2026 struct remote_state *rs = get_remote_state ();
2028 if (remote_multi_process_p (rs))
2030 pid = ptid_get_pid (ptid);
2032 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2034 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2036 tid = ptid_get_lwp (ptid);
2038 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2040 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2045 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2046 passed the last parsed char. Returns null_ptid on error. */
2049 read_ptid (char *buf, char **obuf)
2053 ULONGEST pid = 0, tid = 0;
2057 /* Multi-process ptid. */
2058 pp = unpack_varlen_hex (p + 1, &pid);
2060 error (_("invalid remote ptid: %s"), p);
2063 pp = unpack_varlen_hex (p + 1, &tid);
2066 return ptid_build (pid, tid, 0);
2069 /* No multi-process. Just a tid. */
2070 pp = unpack_varlen_hex (p, &tid);
2072 /* Since the stub is not sending a process id, then default to
2073 what's in inferior_ptid, unless it's null at this point. If so,
2074 then since there's no way to know the pid of the reported
2075 threads, use the magic number. */
2076 if (ptid_equal (inferior_ptid, null_ptid))
2077 pid = ptid_get_pid (magic_null_ptid);
2079 pid = ptid_get_pid (inferior_ptid);
2083 return ptid_build (pid, tid, 0);
2089 if (ch >= 'a' && ch <= 'f')
2090 return ch - 'a' + 10;
2091 if (ch >= '0' && ch <= '9')
2093 if (ch >= 'A' && ch <= 'F')
2094 return ch - 'A' + 10;
2099 stub_unpack_int (char *buff, int fieldlength)
2106 nibble = stubhex (*buff++);
2110 retval = retval << 4;
2116 unpack_nibble (char *buf, int *val)
2118 *val = fromhex (*buf++);
2123 unpack_byte (char *buf, int *value)
2125 *value = stub_unpack_int (buf, 2);
2130 pack_int (char *buf, int value)
2132 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2133 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2134 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2135 buf = pack_hex_byte (buf, (value & 0xff));
2140 unpack_int (char *buf, int *value)
2142 *value = stub_unpack_int (buf, 8);
2146 #if 0 /* Currently unused, uncomment when needed. */
2147 static char *pack_string (char *pkt, char *string);
2150 pack_string (char *pkt, char *string)
2155 len = strlen (string);
2157 len = 200; /* Bigger than most GDB packets, junk??? */
2158 pkt = pack_hex_byte (pkt, len);
2162 if ((ch == '\0') || (ch == '#'))
2163 ch = '*'; /* Protect encapsulation. */
2168 #endif /* 0 (unused) */
2171 unpack_string (char *src, char *dest, int length)
2180 pack_threadid (char *pkt, threadref *id)
2183 unsigned char *altid;
2185 altid = (unsigned char *) id;
2186 limit = pkt + BUF_THREAD_ID_SIZE;
2188 pkt = pack_hex_byte (pkt, *altid++);
2194 unpack_threadid (char *inbuf, threadref *id)
2197 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2200 altref = (char *) id;
2202 while (inbuf < limit)
2204 x = stubhex (*inbuf++);
2205 y = stubhex (*inbuf++);
2206 *altref++ = (x << 4) | y;
2211 /* Externally, threadrefs are 64 bits but internally, they are still
2212 ints. This is due to a mismatch of specifications. We would like
2213 to use 64bit thread references internally. This is an adapter
2217 int_to_threadref (threadref *id, int value)
2219 unsigned char *scan;
2221 scan = (unsigned char *) id;
2227 *scan++ = (value >> 24) & 0xff;
2228 *scan++ = (value >> 16) & 0xff;
2229 *scan++ = (value >> 8) & 0xff;
2230 *scan++ = (value & 0xff);
2234 threadref_to_int (threadref *ref)
2237 unsigned char *scan;
2243 value = (value << 8) | ((*scan++) & 0xff);
2248 copy_threadref (threadref *dest, threadref *src)
2251 unsigned char *csrc, *cdest;
2253 csrc = (unsigned char *) src;
2254 cdest = (unsigned char *) dest;
2261 threadmatch (threadref *dest, threadref *src)
2263 /* Things are broken right now, so just assume we got a match. */
2265 unsigned char *srcp, *destp;
2267 srcp = (char *) src;
2268 destp = (char *) dest;
2272 result &= (*srcp++ == *destp++) ? 1 : 0;
2279 threadid:1, # always request threadid
2286 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2289 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2291 *pkt++ = 'q'; /* Info Query */
2292 *pkt++ = 'P'; /* process or thread info */
2293 pkt = pack_int (pkt, mode); /* mode */
2294 pkt = pack_threadid (pkt, id); /* threadid */
2295 *pkt = '\0'; /* terminate */
2299 /* These values tag the fields in a thread info response packet. */
2300 /* Tagging the fields allows us to request specific fields and to
2301 add more fields as time goes by. */
2303 #define TAG_THREADID 1 /* Echo the thread identifier. */
2304 #define TAG_EXISTS 2 /* Is this process defined enough to
2305 fetch registers and its stack? */
2306 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2307 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2308 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2312 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2313 struct gdb_ext_thread_info *info)
2315 struct remote_state *rs = get_remote_state ();
2319 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2322 /* info->threadid = 0; FIXME: implement zero_threadref. */
2324 info->display[0] = '\0';
2325 info->shortname[0] = '\0';
2326 info->more_display[0] = '\0';
2328 /* Assume the characters indicating the packet type have been
2330 pkt = unpack_int (pkt, &mask); /* arg mask */
2331 pkt = unpack_threadid (pkt, &ref);
2334 warning (_("Incomplete response to threadinfo request."));
2335 if (!threadmatch (&ref, expectedref))
2336 { /* This is an answer to a different request. */
2337 warning (_("ERROR RMT Thread info mismatch."));
2340 copy_threadref (&info->threadid, &ref);
2342 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2344 /* Packets are terminated with nulls. */
2345 while ((pkt < limit) && mask && *pkt)
2347 pkt = unpack_int (pkt, &tag); /* tag */
2348 pkt = unpack_byte (pkt, &length); /* length */
2349 if (!(tag & mask)) /* Tags out of synch with mask. */
2351 warning (_("ERROR RMT: threadinfo tag mismatch."));
2355 if (tag == TAG_THREADID)
2359 warning (_("ERROR RMT: length of threadid is not 16."));
2363 pkt = unpack_threadid (pkt, &ref);
2364 mask = mask & ~TAG_THREADID;
2367 if (tag == TAG_EXISTS)
2369 info->active = stub_unpack_int (pkt, length);
2371 mask = mask & ~(TAG_EXISTS);
2374 warning (_("ERROR RMT: 'exists' length too long."));
2380 if (tag == TAG_THREADNAME)
2382 pkt = unpack_string (pkt, &info->shortname[0], length);
2383 mask = mask & ~TAG_THREADNAME;
2386 if (tag == TAG_DISPLAY)
2388 pkt = unpack_string (pkt, &info->display[0], length);
2389 mask = mask & ~TAG_DISPLAY;
2392 if (tag == TAG_MOREDISPLAY)
2394 pkt = unpack_string (pkt, &info->more_display[0], length);
2395 mask = mask & ~TAG_MOREDISPLAY;
2398 warning (_("ERROR RMT: unknown thread info tag."));
2399 break; /* Not a tag we know about. */
2405 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2406 struct gdb_ext_thread_info *info)
2408 struct remote_state *rs = get_remote_state ();
2411 pack_threadinfo_request (rs->buf, fieldset, threadid);
2413 getpkt (&rs->buf, &rs->buf_size, 0);
2415 if (rs->buf[0] == '\0')
2418 result = remote_unpack_thread_info_response (rs->buf + 2,
2423 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2426 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2427 threadref *nextthread)
2429 *pkt++ = 'q'; /* info query packet */
2430 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2431 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2432 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2433 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2438 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2441 parse_threadlist_response (char *pkt, int result_limit,
2442 threadref *original_echo, threadref *resultlist,
2445 struct remote_state *rs = get_remote_state ();
2447 int count, resultcount, done;
2450 /* Assume the 'q' and 'M chars have been stripped. */
2451 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2452 /* done parse past here */
2453 pkt = unpack_byte (pkt, &count); /* count field */
2454 pkt = unpack_nibble (pkt, &done);
2455 /* The first threadid is the argument threadid. */
2456 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2457 while ((count-- > 0) && (pkt < limit))
2459 pkt = unpack_threadid (pkt, resultlist++);
2460 if (resultcount++ >= result_limit)
2468 /* Fetch the next batch of threads from the remote. Returns -1 if the
2469 qL packet is not supported, 0 on error and 1 on success. */
2472 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2473 int *done, int *result_count, threadref *threadlist)
2475 struct remote_state *rs = get_remote_state ();
2478 /* Trancate result limit to be smaller than the packet size. */
2479 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2480 >= get_remote_packet_size ())
2481 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2483 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2485 getpkt (&rs->buf, &rs->buf_size, 0);
2486 if (*rs->buf == '\0')
2488 /* Packet not supported. */
2493 parse_threadlist_response (rs->buf + 2, result_limit,
2494 &rs->echo_nextthread, threadlist, done);
2496 if (!threadmatch (&rs->echo_nextthread, nextthread))
2498 /* FIXME: This is a good reason to drop the packet. */
2499 /* Possably, there is a duplicate response. */
2501 retransmit immediatly - race conditions
2502 retransmit after timeout - yes
2504 wait for packet, then exit
2506 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2507 return 0; /* I choose simply exiting. */
2509 if (*result_count <= 0)
2513 warning (_("RMT ERROR : failed to get remote thread list."));
2516 return result; /* break; */
2518 if (*result_count > result_limit)
2521 warning (_("RMT ERROR: threadlist response longer than requested."));
2527 /* Fetch the list of remote threads, with the qL packet, and call
2528 STEPFUNCTION for each thread found. Stops iterating and returns 1
2529 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2530 STEPFUNCTION returns false. If the packet is not supported,
2534 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2537 struct remote_state *rs = get_remote_state ();
2538 int done, i, result_count;
2546 if (loopcount++ > looplimit)
2549 warning (_("Remote fetch threadlist -infinite loop-."));
2552 result = remote_get_threadlist (startflag, &rs->nextthread,
2553 MAXTHREADLISTRESULTS,
2554 &done, &result_count,
2555 rs->resultthreadlist);
2558 /* Clear for later iterations. */
2560 /* Setup to resume next batch of thread references, set nextthread. */
2561 if (result_count >= 1)
2562 copy_threadref (&rs->nextthread,
2563 &rs->resultthreadlist[result_count - 1]);
2565 while (result_count--)
2567 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2577 /* A thread found on the remote target. */
2579 typedef struct thread_item
2581 /* The thread's PTID. */
2584 /* The thread's extra info. May be NULL. */
2587 /* The core the thread was running on. -1 if not known. */
2590 DEF_VEC_O(thread_item_t);
2592 /* Context passed around to the various methods listing remote
2593 threads. As new threads are found, they're added to the ITEMS
2596 struct threads_listing_context
2598 /* The threads found on the remote target. */
2599 VEC (thread_item_t) *items;
2602 /* Discard the contents of the constructed thread listing context. */
2605 clear_threads_listing_context (void *p)
2607 struct threads_listing_context *context = p;
2609 struct thread_item *item;
2611 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2612 xfree (item->extra);
2614 VEC_free (thread_item_t, context->items);
2618 remote_newthread_step (threadref *ref, void *data)
2620 struct threads_listing_context *context = data;
2621 struct thread_item item;
2622 int pid = ptid_get_pid (inferior_ptid);
2624 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2628 VEC_safe_push (thread_item_t, context->items, &item);
2630 return 1; /* continue iterator */
2633 #define CRAZY_MAX_THREADS 1000
2636 remote_current_thread (ptid_t oldpid)
2638 struct remote_state *rs = get_remote_state ();
2641 getpkt (&rs->buf, &rs->buf_size, 0);
2642 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2643 return read_ptid (&rs->buf[2], NULL);
2648 /* List remote threads using the deprecated qL packet. */
2651 remote_get_threads_with_ql (struct target_ops *ops,
2652 struct threads_listing_context *context)
2654 if (remote_threadlist_iterator (remote_newthread_step, context,
2655 CRAZY_MAX_THREADS) >= 0)
2661 #if defined(HAVE_LIBEXPAT)
2664 start_thread (struct gdb_xml_parser *parser,
2665 const struct gdb_xml_element *element,
2666 void *user_data, VEC(gdb_xml_value_s) *attributes)
2668 struct threads_listing_context *data = user_data;
2670 struct thread_item item;
2672 struct gdb_xml_value *attr;
2674 id = xml_find_attribute (attributes, "id")->value;
2675 item.ptid = read_ptid (id, NULL);
2677 attr = xml_find_attribute (attributes, "core");
2679 item.core = *(ULONGEST *) attr->value;
2685 VEC_safe_push (thread_item_t, data->items, &item);
2689 end_thread (struct gdb_xml_parser *parser,
2690 const struct gdb_xml_element *element,
2691 void *user_data, const char *body_text)
2693 struct threads_listing_context *data = user_data;
2695 if (body_text && *body_text)
2696 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2699 const struct gdb_xml_attribute thread_attributes[] = {
2700 { "id", GDB_XML_AF_NONE, NULL, NULL },
2701 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2702 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2705 const struct gdb_xml_element thread_children[] = {
2706 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2709 const struct gdb_xml_element threads_children[] = {
2710 { "thread", thread_attributes, thread_children,
2711 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2712 start_thread, end_thread },
2713 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2716 const struct gdb_xml_element threads_elements[] = {
2717 { "threads", NULL, threads_children,
2718 GDB_XML_EF_NONE, NULL, NULL },
2719 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2724 /* List remote threads using qXfer:threads:read. */
2727 remote_get_threads_with_qxfer (struct target_ops *ops,
2728 struct threads_listing_context *context)
2730 #if defined(HAVE_LIBEXPAT)
2731 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2733 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2734 struct cleanup *back_to = make_cleanup (xfree, xml);
2736 if (xml != NULL && *xml != '\0')
2738 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2739 threads_elements, xml, context);
2742 do_cleanups (back_to);
2750 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2753 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2754 struct threads_listing_context *context)
2756 struct remote_state *rs = get_remote_state ();
2758 if (rs->use_threadinfo_query)
2762 putpkt ("qfThreadInfo");
2763 getpkt (&rs->buf, &rs->buf_size, 0);
2765 if (bufp[0] != '\0') /* q packet recognized */
2767 while (*bufp++ == 'm') /* reply contains one or more TID */
2771 struct thread_item item;
2773 item.ptid = read_ptid (bufp, &bufp);
2777 VEC_safe_push (thread_item_t, context->items, &item);
2779 while (*bufp++ == ','); /* comma-separated list */
2780 putpkt ("qsThreadInfo");
2781 getpkt (&rs->buf, &rs->buf_size, 0);
2788 /* Packet not recognized. */
2789 rs->use_threadinfo_query = 0;
2796 /* Implement the to_update_thread_list function for the remote
2800 remote_update_thread_list (struct target_ops *ops)
2802 struct remote_state *rs = get_remote_state ();
2803 struct threads_listing_context context;
2804 struct cleanup *old_chain;
2807 context.items = NULL;
2808 old_chain = make_cleanup (clear_threads_listing_context, &context);
2810 /* We have a few different mechanisms to fetch the thread list. Try
2811 them all, starting with the most preferred one first, falling
2812 back to older methods. */
2813 if (remote_get_threads_with_qxfer (ops, &context)
2814 || remote_get_threads_with_qthreadinfo (ops, &context)
2815 || remote_get_threads_with_ql (ops, &context))
2818 struct thread_item *item;
2819 struct thread_info *tp, *tmp;
2823 if (VEC_empty (thread_item_t, context.items)
2824 && remote_thread_always_alive (ops, inferior_ptid))
2826 /* Some targets don't really support threads, but still
2827 reply an (empty) thread list in response to the thread
2828 listing packets, instead of replying "packet not
2829 supported". Exit early so we don't delete the main
2831 do_cleanups (old_chain);
2835 /* CONTEXT now holds the current thread list on the remote
2836 target end. Delete GDB-side threads no longer found on the
2838 ALL_NON_EXITED_THREADS_SAFE (tp, tmp)
2841 VEC_iterate (thread_item_t, context.items, i, item);
2844 if (ptid_equal (item->ptid, tp->ptid))
2848 if (i == VEC_length (thread_item_t, context.items))
2851 delete_thread (tp->ptid);
2855 /* And now add threads we don't know about yet to our list. */
2857 VEC_iterate (thread_item_t, context.items, i, item);
2860 if (!ptid_equal (item->ptid, null_ptid))
2862 struct private_thread_info *info;
2863 /* In non-stop mode, we assume new found threads are
2864 running until proven otherwise with a stop reply. In
2865 all-stop, we can only get here if all threads are
2867 int running = non_stop ? 1 : 0;
2869 remote_notice_new_inferior (item->ptid, running);
2871 info = demand_private_info (item->ptid);
2872 info->core = item->core;
2873 info->extra = item->extra;
2881 /* If no thread listing method is supported, then query whether
2882 each known thread is alive, one by one, with the T packet.
2883 If the target doesn't support threads at all, then this is a
2884 no-op. See remote_thread_alive. */
2888 do_cleanups (old_chain);
2892 * Collect a descriptive string about the given thread.
2893 * The target may say anything it wants to about the thread
2894 * (typically info about its blocked / runnable state, name, etc.).
2895 * This string will appear in the info threads display.
2897 * Optional: targets are not required to implement this function.
2901 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
2903 struct remote_state *rs = get_remote_state ();
2907 struct gdb_ext_thread_info threadinfo;
2908 static char display_buf[100]; /* arbitrary... */
2909 int n = 0; /* position in display_buf */
2911 if (rs->remote_desc == 0) /* paranoia */
2912 internal_error (__FILE__, __LINE__,
2913 _("remote_threads_extra_info"));
2915 if (ptid_equal (tp->ptid, magic_null_ptid)
2916 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
2917 /* This is the main thread which was added by GDB. The remote
2918 server doesn't know about it. */
2921 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2923 struct thread_info *info = find_thread_ptid (tp->ptid);
2925 if (info && info->priv)
2926 return info->priv->extra;
2931 if (rs->use_threadextra_query)
2934 char *endb = rs->buf + get_remote_packet_size ();
2936 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2938 write_ptid (b, endb, tp->ptid);
2941 getpkt (&rs->buf, &rs->buf_size, 0);
2942 if (rs->buf[0] != 0)
2944 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2945 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2946 display_buf [result] = '\0';
2951 /* If the above query fails, fall back to the old method. */
2952 rs->use_threadextra_query = 0;
2953 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2954 | TAG_MOREDISPLAY | TAG_DISPLAY;
2955 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
2956 if (remote_get_threadinfo (&id, set, &threadinfo))
2957 if (threadinfo.active)
2959 if (*threadinfo.shortname)
2960 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2961 " Name: %s,", threadinfo.shortname);
2962 if (*threadinfo.display)
2963 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2964 " State: %s,", threadinfo.display);
2965 if (*threadinfo.more_display)
2966 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2967 " Priority: %s", threadinfo.more_display);
2971 /* For purely cosmetic reasons, clear up trailing commas. */
2972 if (',' == display_buf[n-1])
2973 display_buf[n-1] = ' ';
2982 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
2983 struct static_tracepoint_marker *marker)
2985 struct remote_state *rs = get_remote_state ();
2988 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2990 p += hexnumstr (p, addr);
2992 getpkt (&rs->buf, &rs->buf_size, 0);
2996 error (_("Remote failure reply: %s"), p);
3000 parse_static_tracepoint_marker_definition (p, &p, marker);
3007 static VEC(static_tracepoint_marker_p) *
3008 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3011 struct remote_state *rs = get_remote_state ();
3012 VEC(static_tracepoint_marker_p) *markers = NULL;
3013 struct static_tracepoint_marker *marker = NULL;
3014 struct cleanup *old_chain;
3017 /* Ask for a first packet of static tracepoint marker
3020 getpkt (&rs->buf, &rs->buf_size, 0);
3023 error (_("Remote failure reply: %s"), p);
3025 old_chain = make_cleanup (free_current_marker, &marker);
3030 marker = XCNEW (struct static_tracepoint_marker);
3034 parse_static_tracepoint_marker_definition (p, &p, marker);
3036 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3038 VEC_safe_push (static_tracepoint_marker_p,
3044 release_static_tracepoint_marker (marker);
3045 memset (marker, 0, sizeof (*marker));
3048 while (*p++ == ','); /* comma-separated list */
3049 /* Ask for another packet of static tracepoint definition. */
3051 getpkt (&rs->buf, &rs->buf_size, 0);
3055 do_cleanups (old_chain);
3060 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3063 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3065 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3069 /* Restart the remote side; this is an extended protocol operation. */
3072 extended_remote_restart (void)
3074 struct remote_state *rs = get_remote_state ();
3076 /* Send the restart command; for reasons I don't understand the
3077 remote side really expects a number after the "R". */
3078 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3081 remote_fileio_reset ();
3084 /* Clean up connection to a remote debugger. */
3087 remote_close (struct target_ops *self)
3089 struct remote_state *rs = get_remote_state ();
3091 if (rs->remote_desc == NULL)
3092 return; /* already closed */
3094 /* Make sure we leave stdin registered in the event loop, and we
3095 don't leave the async SIGINT signal handler installed. */
3096 remote_terminal_ours (self);
3098 serial_close (rs->remote_desc);
3099 rs->remote_desc = NULL;
3101 /* We don't have a connection to the remote stub anymore. Get rid
3102 of all the inferiors and their threads we were controlling.
3103 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3104 will be unable to find the thread corresponding to (pid, 0, 0). */
3105 inferior_ptid = null_ptid;
3106 discard_all_inferiors ();
3108 /* We are closing the remote target, so we should discard
3109 everything of this target. */
3110 discard_pending_stop_replies_in_queue (rs);
3112 if (remote_async_inferior_event_token)
3113 delete_async_event_handler (&remote_async_inferior_event_token);
3115 remote_notif_state_xfree (rs->notif_state);
3117 trace_reset_local_state ();
3120 /* Query the remote side for the text, data and bss offsets. */
3125 struct remote_state *rs = get_remote_state ();
3128 int lose, num_segments = 0, do_sections, do_segments;
3129 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3130 struct section_offsets *offs;
3131 struct symfile_segment_data *data;
3133 if (symfile_objfile == NULL)
3136 putpkt ("qOffsets");
3137 getpkt (&rs->buf, &rs->buf_size, 0);
3140 if (buf[0] == '\000')
3141 return; /* Return silently. Stub doesn't support
3145 warning (_("Remote failure reply: %s"), buf);
3149 /* Pick up each field in turn. This used to be done with scanf, but
3150 scanf will make trouble if CORE_ADDR size doesn't match
3151 conversion directives correctly. The following code will work
3152 with any size of CORE_ADDR. */
3153 text_addr = data_addr = bss_addr = 0;
3157 if (startswith (ptr, "Text="))
3160 /* Don't use strtol, could lose on big values. */
3161 while (*ptr && *ptr != ';')
3162 text_addr = (text_addr << 4) + fromhex (*ptr++);
3164 if (startswith (ptr, ";Data="))
3167 while (*ptr && *ptr != ';')
3168 data_addr = (data_addr << 4) + fromhex (*ptr++);
3173 if (!lose && startswith (ptr, ";Bss="))
3176 while (*ptr && *ptr != ';')
3177 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3179 if (bss_addr != data_addr)
3180 warning (_("Target reported unsupported offsets: %s"), buf);
3185 else if (startswith (ptr, "TextSeg="))
3188 /* Don't use strtol, could lose on big values. */
3189 while (*ptr && *ptr != ';')
3190 text_addr = (text_addr << 4) + fromhex (*ptr++);
3193 if (startswith (ptr, ";DataSeg="))
3196 while (*ptr && *ptr != ';')
3197 data_addr = (data_addr << 4) + fromhex (*ptr++);
3205 error (_("Malformed response to offset query, %s"), buf);
3206 else if (*ptr != '\0')
3207 warning (_("Target reported unsupported offsets: %s"), buf);
3209 offs = ((struct section_offsets *)
3210 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3211 memcpy (offs, symfile_objfile->section_offsets,
3212 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3214 data = get_symfile_segment_data (symfile_objfile->obfd);
3215 do_segments = (data != NULL);
3216 do_sections = num_segments == 0;
3218 if (num_segments > 0)
3220 segments[0] = text_addr;
3221 segments[1] = data_addr;
3223 /* If we have two segments, we can still try to relocate everything
3224 by assuming that the .text and .data offsets apply to the whole
3225 text and data segments. Convert the offsets given in the packet
3226 to base addresses for symfile_map_offsets_to_segments. */
3227 else if (data && data->num_segments == 2)
3229 segments[0] = data->segment_bases[0] + text_addr;
3230 segments[1] = data->segment_bases[1] + data_addr;
3233 /* If the object file has only one segment, assume that it is text
3234 rather than data; main programs with no writable data are rare,
3235 but programs with no code are useless. Of course the code might
3236 have ended up in the data segment... to detect that we would need
3237 the permissions here. */
3238 else if (data && data->num_segments == 1)
3240 segments[0] = data->segment_bases[0] + text_addr;
3243 /* There's no way to relocate by segment. */
3249 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3250 offs, num_segments, segments);
3252 if (ret == 0 && !do_sections)
3253 error (_("Can not handle qOffsets TextSeg "
3254 "response with this symbol file"));
3261 free_symfile_segment_data (data);
3265 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3267 /* This is a temporary kludge to force data and bss to use the
3268 same offsets because that's what nlmconv does now. The real
3269 solution requires changes to the stub and remote.c that I
3270 don't have time to do right now. */
3272 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3273 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3276 objfile_relocate (symfile_objfile, offs);
3279 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3280 threads we know are stopped already. This is used during the
3281 initial remote connection in non-stop mode --- threads that are
3282 reported as already being stopped are left stopped. */
3285 set_stop_requested_callback (struct thread_info *thread, void *data)
3287 /* If we have a stop reply for this thread, it must be stopped. */
3288 if (peek_stop_reply (thread->ptid))
3289 set_stop_requested (thread->ptid, 1);
3294 /* Send interrupt_sequence to remote target. */
3296 send_interrupt_sequence (void)
3298 struct remote_state *rs = get_remote_state ();
3300 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3301 remote_serial_write ("\x03", 1);
3302 else if (interrupt_sequence_mode == interrupt_sequence_break)
3303 serial_send_break (rs->remote_desc);
3304 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3306 serial_send_break (rs->remote_desc);
3307 remote_serial_write ("g", 1);
3310 internal_error (__FILE__, __LINE__,
3311 _("Invalid value for interrupt_sequence_mode: %s."),
3312 interrupt_sequence_mode);
3316 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3317 and extract the PTID. Returns NULL_PTID if not found. */
3320 stop_reply_extract_thread (char *stop_reply)
3322 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3326 /* Txx r:val ; r:val (...) */
3329 /* Look for "register" named "thread". */
3334 p1 = strchr (p, ':');
3338 if (strncmp (p, "thread", p1 - p) == 0)
3339 return read_ptid (++p1, &p);
3341 p1 = strchr (p, ';');
3353 /* Determine the remote side's current thread. If we have a stop
3354 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3355 "thread" register we can extract the current thread from. If not,
3356 ask the remote which is the current thread with qC. The former
3357 method avoids a roundtrip. */
3360 get_current_thread (char *wait_status)
3364 /* Note we don't use remote_parse_stop_reply as that makes use of
3365 the target architecture, which we haven't yet fully determined at
3367 if (wait_status != NULL)
3368 ptid = stop_reply_extract_thread (wait_status);
3369 if (ptid_equal (ptid, null_ptid))
3370 ptid = remote_current_thread (inferior_ptid);
3375 /* Query the remote target for which is the current thread/process,
3376 add it to our tables, and update INFERIOR_PTID. The caller is
3377 responsible for setting the state such that the remote end is ready
3378 to return the current thread.
3380 This function is called after handling the '?' or 'vRun' packets,
3381 whose response is a stop reply from which we can also try
3382 extracting the thread. If the target doesn't support the explicit
3383 qC query, we infer the current thread from that stop reply, passed
3384 in in WAIT_STATUS, which may be NULL. */
3387 add_current_inferior_and_thread (char *wait_status)
3389 struct remote_state *rs = get_remote_state ();
3391 ptid_t ptid = null_ptid;
3393 inferior_ptid = null_ptid;
3395 /* Now, if we have thread information, update inferior_ptid. */
3396 ptid = get_current_thread (wait_status);
3398 if (!ptid_equal (ptid, null_ptid))
3400 if (!remote_multi_process_p (rs))
3403 inferior_ptid = ptid;
3407 /* Without this, some commands which require an active target
3408 (such as kill) won't work. This variable serves (at least)
3409 double duty as both the pid of the target process (if it has
3410 such), and as a flag indicating that a target is active. */
3411 inferior_ptid = magic_null_ptid;
3415 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3417 /* Add the main thread. */
3418 add_thread_silent (inferior_ptid);
3422 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3424 struct remote_state *rs = get_remote_state ();
3425 struct packet_config *noack_config;
3426 char *wait_status = NULL;
3428 immediate_quit++; /* Allow user to interrupt it. */
3431 if (interrupt_on_connect)
3432 send_interrupt_sequence ();
3434 /* Ack any packet which the remote side has already sent. */
3435 serial_write (rs->remote_desc, "+", 1);
3437 /* Signal other parts that we're going through the initial setup,
3438 and so things may not be stable yet. */
3439 rs->starting_up = 1;
3441 /* The first packet we send to the target is the optional "supported
3442 packets" request. If the target can answer this, it will tell us
3443 which later probes to skip. */
3444 remote_query_supported ();
3446 /* If the stub wants to get a QAllow, compose one and send it. */
3447 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3448 remote_set_permissions (target);
3450 /* Next, we possibly activate noack mode.
3452 If the QStartNoAckMode packet configuration is set to AUTO,
3453 enable noack mode if the stub reported a wish for it with
3456 If set to TRUE, then enable noack mode even if the stub didn't
3457 report it in qSupported. If the stub doesn't reply OK, the
3458 session ends with an error.
3460 If FALSE, then don't activate noack mode, regardless of what the
3461 stub claimed should be the default with qSupported. */
3463 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3464 if (packet_config_support (noack_config) != PACKET_DISABLE)
3466 putpkt ("QStartNoAckMode");
3467 getpkt (&rs->buf, &rs->buf_size, 0);
3468 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3474 /* Tell the remote that we are using the extended protocol. */
3476 getpkt (&rs->buf, &rs->buf_size, 0);
3479 /* Let the target know which signals it is allowed to pass down to
3481 update_signals_program_target ();
3483 /* Next, if the target can specify a description, read it. We do
3484 this before anything involving memory or registers. */
3485 target_find_description ();
3487 /* Next, now that we know something about the target, update the
3488 address spaces in the program spaces. */
3489 update_address_spaces ();
3491 /* On OSs where the list of libraries is global to all
3492 processes, we fetch them early. */
3493 if (gdbarch_has_global_solist (target_gdbarch ()))
3494 solib_add (NULL, from_tty, target, auto_solib_add);
3498 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3499 error (_("Non-stop mode requested, but remote "
3500 "does not support non-stop"));
3502 putpkt ("QNonStop:1");
3503 getpkt (&rs->buf, &rs->buf_size, 0);
3505 if (strcmp (rs->buf, "OK") != 0)
3506 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3508 /* Find about threads and processes the stub is already
3509 controlling. We default to adding them in the running state.
3510 The '?' query below will then tell us about which threads are
3512 remote_update_thread_list (target);
3514 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3516 /* Don't assume that the stub can operate in all-stop mode.
3517 Request it explicitly. */
3518 putpkt ("QNonStop:0");
3519 getpkt (&rs->buf, &rs->buf_size, 0);
3521 if (strcmp (rs->buf, "OK") != 0)
3522 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3525 /* Upload TSVs regardless of whether the target is running or not. The
3526 remote stub, such as GDBserver, may have some predefined or builtin
3527 TSVs, even if the target is not running. */
3528 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3530 struct uploaded_tsv *uploaded_tsvs = NULL;
3532 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3533 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3536 /* Check whether the target is running now. */
3538 getpkt (&rs->buf, &rs->buf_size, 0);
3544 struct inferior *inf;
3546 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3549 error (_("The target is not running (try extended-remote?)"));
3551 /* We're connected, but not running. Drop out before we
3552 call start_remote. */
3553 rs->starting_up = 0;
3558 /* Save the reply for later. */
3559 wait_status = alloca (strlen (rs->buf) + 1);
3560 strcpy (wait_status, rs->buf);
3563 /* Fetch thread list. */
3564 target_update_thread_list ();
3566 /* Let the stub know that we want it to return the thread. */
3567 set_continue_thread (minus_one_ptid);
3569 if (thread_count () == 0)
3571 /* Target has no concept of threads at all. GDB treats
3572 non-threaded target as single-threaded; add a main
3574 add_current_inferior_and_thread (wait_status);
3578 /* We have thread information; select the thread the target
3579 says should be current. If we're reconnecting to a
3580 multi-threaded program, this will ideally be the thread
3581 that last reported an event before GDB disconnected. */
3582 inferior_ptid = get_current_thread (wait_status);
3583 if (ptid_equal (inferior_ptid, null_ptid))
3585 /* Odd... The target was able to list threads, but not
3586 tell us which thread was current (no "thread"
3587 register in T stop reply?). Just pick the first
3588 thread in the thread list then. */
3589 inferior_ptid = thread_list->ptid;
3593 /* init_wait_for_inferior should be called before get_offsets in order
3594 to manage `inserted' flag in bp loc in a correct state.
3595 breakpoint_init_inferior, called from init_wait_for_inferior, set
3596 `inserted' flag to 0, while before breakpoint_re_set, called from
3597 start_remote, set `inserted' flag to 1. In the initialization of
3598 inferior, breakpoint_init_inferior should be called first, and then
3599 breakpoint_re_set can be called. If this order is broken, state of
3600 `inserted' flag is wrong, and cause some problems on breakpoint
3602 init_wait_for_inferior ();
3604 get_offsets (); /* Get text, data & bss offsets. */
3606 /* If we could not find a description using qXfer, and we know
3607 how to do it some other way, try again. This is not
3608 supported for non-stop; it could be, but it is tricky if
3609 there are no stopped threads when we connect. */
3610 if (remote_read_description_p (target)
3611 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3613 target_clear_description ();
3614 target_find_description ();
3617 /* Use the previously fetched status. */
3618 gdb_assert (wait_status != NULL);
3619 strcpy (rs->buf, wait_status);
3620 rs->cached_wait_status = 1;
3623 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3627 /* Clear WFI global state. Do this before finding about new
3628 threads and inferiors, and setting the current inferior.
3629 Otherwise we would clear the proceed status of the current
3630 inferior when we want its stop_soon state to be preserved
3631 (see notice_new_inferior). */
3632 init_wait_for_inferior ();
3634 /* In non-stop, we will either get an "OK", meaning that there
3635 are no stopped threads at this time; or, a regular stop
3636 reply. In the latter case, there may be more than one thread
3637 stopped --- we pull them all out using the vStopped
3639 if (strcmp (rs->buf, "OK") != 0)
3641 struct notif_client *notif = ¬if_client_stop;
3643 /* remote_notif_get_pending_replies acks this one, and gets
3645 rs->notif_state->pending_event[notif_client_stop.id]
3646 = remote_notif_parse (notif, rs->buf);
3647 remote_notif_get_pending_events (notif);
3649 /* Make sure that threads that were stopped remain
3651 iterate_over_threads (set_stop_requested_callback, NULL);
3654 if (target_can_async_p ())
3657 if (thread_count () == 0)
3660 error (_("The target is not running (try extended-remote?)"));
3662 /* We're connected, but not running. Drop out before we
3663 call start_remote. */
3664 rs->starting_up = 0;
3668 /* Let the stub know that we want it to return the thread. */
3670 /* Force the stub to choose a thread. */
3671 set_general_thread (null_ptid);
3674 inferior_ptid = remote_current_thread (minus_one_ptid);
3675 if (ptid_equal (inferior_ptid, minus_one_ptid))
3676 error (_("remote didn't report the current thread in non-stop mode"));
3678 get_offsets (); /* Get text, data & bss offsets. */
3680 /* In non-stop mode, any cached wait status will be stored in
3681 the stop reply queue. */
3682 gdb_assert (wait_status == NULL);
3684 /* Report all signals during attach/startup. */
3685 remote_pass_signals (target, 0, NULL);
3688 /* If we connected to a live target, do some additional setup. */
3689 if (target_has_execution)
3691 if (symfile_objfile) /* No use without a symbol-file. */
3692 remote_check_symbols ();
3695 /* Possibly the target has been engaged in a trace run started
3696 previously; find out where things are at. */
3697 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3699 struct uploaded_tp *uploaded_tps = NULL;
3701 if (current_trace_status ()->running)
3702 printf_filtered (_("Trace is already running on the target.\n"));
3704 remote_upload_tracepoints (target, &uploaded_tps);
3706 merge_uploaded_tracepoints (&uploaded_tps);
3709 /* The thread and inferior lists are now synchronized with the
3710 target, our symbols have been relocated, and we're merged the
3711 target's tracepoints with ours. We're done with basic start
3713 rs->starting_up = 0;
3715 /* Maybe breakpoints are global and need to be inserted now. */
3716 if (breakpoints_should_be_inserted_now ())
3717 insert_breakpoints ();
3720 /* Open a connection to a remote debugger.
3721 NAME is the filename used for communication. */
3724 remote_open (const char *name, int from_tty)
3726 remote_open_1 (name, from_tty, &remote_ops, 0);
3729 /* Open a connection to a remote debugger using the extended
3730 remote gdb protocol. NAME is the filename used for communication. */
3733 extended_remote_open (const char *name, int from_tty)
3735 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3738 /* Reset all packets back to "unknown support". Called when opening a
3739 new connection to a remote target. */
3742 reset_all_packet_configs_support (void)
3746 for (i = 0; i < PACKET_MAX; i++)
3747 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3750 /* Initialize all packet configs. */
3753 init_all_packet_configs (void)
3757 for (i = 0; i < PACKET_MAX; i++)
3759 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3760 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3764 /* Symbol look-up. */
3767 remote_check_symbols (void)
3769 struct remote_state *rs = get_remote_state ();
3770 char *msg, *reply, *tmp;
3771 struct bound_minimal_symbol sym;
3774 /* The remote side has no concept of inferiors that aren't running
3775 yet, it only knows about running processes. If we're connected
3776 but our current inferior is not running, we should not invite the
3777 remote target to request symbol lookups related to its
3778 (unrelated) current process. */
3779 if (!target_has_execution)
3782 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3785 /* Make sure the remote is pointing at the right process. Note
3786 there's no way to select "no process". */
3787 set_general_process ();
3789 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3790 because we need both at the same time. */
3791 msg = alloca (get_remote_packet_size ());
3793 /* Invite target to request symbol lookups. */
3795 putpkt ("qSymbol::");
3796 getpkt (&rs->buf, &rs->buf_size, 0);
3797 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3800 while (startswith (reply, "qSymbol:"))
3802 struct bound_minimal_symbol sym;
3805 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3807 sym = lookup_minimal_symbol (msg, NULL, NULL);
3808 if (sym.minsym == NULL)
3809 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3812 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3813 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
3815 /* If this is a function address, return the start of code
3816 instead of any data function descriptor. */
3817 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3821 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3822 phex_nz (sym_addr, addr_size), &reply[8]);
3826 getpkt (&rs->buf, &rs->buf_size, 0);
3831 static struct serial *
3832 remote_serial_open (const char *name)
3834 static int udp_warning = 0;
3836 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3837 of in ser-tcp.c, because it is the remote protocol assuming that the
3838 serial connection is reliable and not the serial connection promising
3840 if (!udp_warning && startswith (name, "udp:"))
3842 warning (_("The remote protocol may be unreliable over UDP.\n"
3843 "Some events may be lost, rendering further debugging "
3848 return serial_open (name);
3851 /* Inform the target of our permission settings. The permission flags
3852 work without this, but if the target knows the settings, it can do
3853 a couple things. First, it can add its own check, to catch cases
3854 that somehow manage to get by the permissions checks in target
3855 methods. Second, if the target is wired to disallow particular
3856 settings (for instance, a system in the field that is not set up to
3857 be able to stop at a breakpoint), it can object to any unavailable
3861 remote_set_permissions (struct target_ops *self)
3863 struct remote_state *rs = get_remote_state ();
3865 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3866 "WriteReg:%x;WriteMem:%x;"
3867 "InsertBreak:%x;InsertTrace:%x;"
3868 "InsertFastTrace:%x;Stop:%x",
3869 may_write_registers, may_write_memory,
3870 may_insert_breakpoints, may_insert_tracepoints,
3871 may_insert_fast_tracepoints, may_stop);
3873 getpkt (&rs->buf, &rs->buf_size, 0);
3875 /* If the target didn't like the packet, warn the user. Do not try
3876 to undo the user's settings, that would just be maddening. */
3877 if (strcmp (rs->buf, "OK") != 0)
3878 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3881 /* This type describes each known response to the qSupported
3883 struct protocol_feature
3885 /* The name of this protocol feature. */
3888 /* The default for this protocol feature. */
3889 enum packet_support default_support;
3891 /* The function to call when this feature is reported, or after
3892 qSupported processing if the feature is not supported.
3893 The first argument points to this structure. The second
3894 argument indicates whether the packet requested support be
3895 enabled, disabled, or probed (or the default, if this function
3896 is being called at the end of processing and this feature was
3897 not reported). The third argument may be NULL; if not NULL, it
3898 is a NUL-terminated string taken from the packet following
3899 this feature's name and an equals sign. */
3900 void (*func) (const struct protocol_feature *, enum packet_support,
3903 /* The corresponding packet for this feature. Only used if
3904 FUNC is remote_supported_packet. */
3909 remote_supported_packet (const struct protocol_feature *feature,
3910 enum packet_support support,
3911 const char *argument)
3915 warning (_("Remote qSupported response supplied an unexpected value for"
3916 " \"%s\"."), feature->name);
3920 remote_protocol_packets[feature->packet].support = support;
3924 remote_packet_size (const struct protocol_feature *feature,
3925 enum packet_support support, const char *value)
3927 struct remote_state *rs = get_remote_state ();
3932 if (support != PACKET_ENABLE)
3935 if (value == NULL || *value == '\0')
3937 warning (_("Remote target reported \"%s\" without a size."),
3943 packet_size = strtol (value, &value_end, 16);
3944 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3946 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3947 feature->name, value);
3951 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3953 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3954 packet_size, MAX_REMOTE_PACKET_SIZE);
3955 packet_size = MAX_REMOTE_PACKET_SIZE;
3958 /* Record the new maximum packet size. */
3959 rs->explicit_packet_size = packet_size;
3962 static const struct protocol_feature remote_protocol_features[] = {
3963 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3964 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3965 PACKET_qXfer_auxv },
3966 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3967 PACKET_qXfer_features },
3968 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3969 PACKET_qXfer_libraries },
3970 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3971 PACKET_qXfer_libraries_svr4 },
3972 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3973 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
3974 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3975 PACKET_qXfer_memory_map },
3976 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3977 PACKET_qXfer_spu_read },
3978 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3979 PACKET_qXfer_spu_write },
3980 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3981 PACKET_qXfer_osdata },
3982 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3983 PACKET_qXfer_threads },
3984 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3985 PACKET_qXfer_traceframe_info },
3986 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3987 PACKET_QPassSignals },
3988 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3989 PACKET_QProgramSignals },
3990 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3991 PACKET_QStartNoAckMode },
3992 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
3993 PACKET_multiprocess_feature },
3994 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
3995 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3996 PACKET_qXfer_siginfo_read },
3997 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3998 PACKET_qXfer_siginfo_write },
3999 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4000 PACKET_ConditionalTracepoints },
4001 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4002 PACKET_ConditionalBreakpoints },
4003 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4004 PACKET_BreakpointCommands },
4005 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4006 PACKET_FastTracepoints },
4007 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4008 PACKET_StaticTracepoints },
4009 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4010 PACKET_InstallInTrace},
4011 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4012 PACKET_DisconnectedTracing_feature },
4013 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4015 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4017 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4018 PACKET_TracepointSource },
4019 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4021 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4022 PACKET_EnableDisableTracepoints_feature },
4023 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4024 PACKET_qXfer_fdpic },
4025 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4027 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4028 PACKET_QDisableRandomization },
4029 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4030 { "QTBuffer:size", PACKET_DISABLE,
4031 remote_supported_packet, PACKET_QTBuffer_size},
4032 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4033 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4034 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4035 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4036 PACKET_qXfer_btrace },
4037 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4038 PACKET_qXfer_btrace_conf },
4039 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4040 PACKET_Qbtrace_conf_bts_size },
4041 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4042 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4045 static char *remote_support_xml;
4047 /* Register string appended to "xmlRegisters=" in qSupported query. */
4050 register_remote_support_xml (const char *xml)
4052 #if defined(HAVE_LIBEXPAT)
4053 if (remote_support_xml == NULL)
4054 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4057 char *copy = xstrdup (remote_support_xml + 13);
4058 char *p = strtok (copy, ",");
4062 if (strcmp (p, xml) == 0)
4069 while ((p = strtok (NULL, ",")) != NULL);
4072 remote_support_xml = reconcat (remote_support_xml,
4073 remote_support_xml, ",", xml,
4080 remote_query_supported_append (char *msg, const char *append)
4083 return reconcat (msg, msg, ";", append, (char *) NULL);
4085 return xstrdup (append);
4089 remote_query_supported (void)
4091 struct remote_state *rs = get_remote_state ();
4094 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4096 /* The packet support flags are handled differently for this packet
4097 than for most others. We treat an error, a disabled packet, and
4098 an empty response identically: any features which must be reported
4099 to be used will be automatically disabled. An empty buffer
4100 accomplishes this, since that is also the representation for a list
4101 containing no features. */
4104 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4107 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4109 q = remote_query_supported_append (q, "multiprocess+");
4111 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4112 q = remote_query_supported_append (q, "swbreak+");
4113 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4114 q = remote_query_supported_append (q, "hwbreak+");
4116 if (remote_support_xml)
4117 q = remote_query_supported_append (q, remote_support_xml);
4119 q = remote_query_supported_append (q, "qRelocInsn+");
4121 q = reconcat (q, "qSupported:", q, (char *) NULL);
4124 do_cleanups (old_chain);
4126 getpkt (&rs->buf, &rs->buf_size, 0);
4128 /* If an error occured, warn, but do not return - just reset the
4129 buffer to empty and go on to disable features. */
4130 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4133 warning (_("Remote failure reply: %s"), rs->buf);
4138 memset (seen, 0, sizeof (seen));
4143 enum packet_support is_supported;
4144 char *p, *end, *name_end, *value;
4146 /* First separate out this item from the rest of the packet. If
4147 there's another item after this, we overwrite the separator
4148 (terminated strings are much easier to work with). */
4150 end = strchr (p, ';');
4153 end = p + strlen (p);
4163 warning (_("empty item in \"qSupported\" response"));
4168 name_end = strchr (p, '=');
4171 /* This is a name=value entry. */
4172 is_supported = PACKET_ENABLE;
4173 value = name_end + 1;
4182 is_supported = PACKET_ENABLE;
4186 is_supported = PACKET_DISABLE;
4190 is_supported = PACKET_SUPPORT_UNKNOWN;
4194 warning (_("unrecognized item \"%s\" "
4195 "in \"qSupported\" response"), p);
4201 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4202 if (strcmp (remote_protocol_features[i].name, p) == 0)
4204 const struct protocol_feature *feature;
4207 feature = &remote_protocol_features[i];
4208 feature->func (feature, is_supported, value);
4213 /* If we increased the packet size, make sure to increase the global
4214 buffer size also. We delay this until after parsing the entire
4215 qSupported packet, because this is the same buffer we were
4217 if (rs->buf_size < rs->explicit_packet_size)
4219 rs->buf_size = rs->explicit_packet_size;
4220 rs->buf = xrealloc (rs->buf, rs->buf_size);
4223 /* Handle the defaults for unmentioned features. */
4224 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4227 const struct protocol_feature *feature;
4229 feature = &remote_protocol_features[i];
4230 feature->func (feature, feature->default_support, NULL);
4234 /* Remove any of the remote.c targets from target stack. Upper targets depend
4235 on it so remove them first. */
4238 remote_unpush_target (void)
4240 pop_all_targets_above (process_stratum - 1);
4244 remote_open_1 (const char *name, int from_tty,
4245 struct target_ops *target, int extended_p)
4247 struct remote_state *rs = get_remote_state ();
4250 error (_("To open a remote debug connection, you need to specify what\n"
4251 "serial device is attached to the remote system\n"
4252 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4254 /* See FIXME above. */
4255 if (!target_async_permitted)
4256 wait_forever_enabled_p = 1;
4258 /* If we're connected to a running target, target_preopen will kill it.
4259 Ask this question first, before target_preopen has a chance to kill
4261 if (rs->remote_desc != NULL && !have_inferiors ())
4264 && !query (_("Already connected to a remote target. Disconnect? ")))
4265 error (_("Still connected."));
4268 /* Here the possibly existing remote target gets unpushed. */
4269 target_preopen (from_tty);
4271 /* Make sure we send the passed signals list the next time we resume. */
4272 xfree (rs->last_pass_packet);
4273 rs->last_pass_packet = NULL;
4275 /* Make sure we send the program signals list the next time we
4277 xfree (rs->last_program_signals_packet);
4278 rs->last_program_signals_packet = NULL;
4280 remote_fileio_reset ();
4281 reopen_exec_file ();
4284 rs->remote_desc = remote_serial_open (name);
4285 if (!rs->remote_desc)
4286 perror_with_name (name);
4288 if (baud_rate != -1)
4290 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4292 /* The requested speed could not be set. Error out to
4293 top level after closing remote_desc. Take care to
4294 set remote_desc to NULL to avoid closing remote_desc
4296 serial_close (rs->remote_desc);
4297 rs->remote_desc = NULL;
4298 perror_with_name (name);
4302 serial_setparity (rs->remote_desc, serial_parity);
4303 serial_raw (rs->remote_desc);
4305 /* If there is something sitting in the buffer we might take it as a
4306 response to a command, which would be bad. */
4307 serial_flush_input (rs->remote_desc);
4311 puts_filtered ("Remote debugging using ");
4312 puts_filtered (name);
4313 puts_filtered ("\n");
4315 push_target (target); /* Switch to using remote target now. */
4317 /* Register extra event sources in the event loop. */
4318 remote_async_inferior_event_token
4319 = create_async_event_handler (remote_async_inferior_event_handler,
4321 rs->notif_state = remote_notif_state_allocate ();
4323 /* Reset the target state; these things will be queried either by
4324 remote_query_supported or as they are needed. */
4325 reset_all_packet_configs_support ();
4326 rs->cached_wait_status = 0;
4327 rs->explicit_packet_size = 0;
4329 rs->extended = extended_p;
4330 rs->waiting_for_stop_reply = 0;
4331 rs->ctrlc_pending_p = 0;
4333 rs->general_thread = not_sent_ptid;
4334 rs->continue_thread = not_sent_ptid;
4335 rs->remote_traceframe_number = -1;
4337 /* Probe for ability to use "ThreadInfo" query, as required. */
4338 rs->use_threadinfo_query = 1;
4339 rs->use_threadextra_query = 1;
4341 if (target_async_permitted)
4343 /* With this target we start out by owning the terminal. */
4344 remote_async_terminal_ours_p = 1;
4346 /* FIXME: cagney/1999-09-23: During the initial connection it is
4347 assumed that the target is already ready and able to respond to
4348 requests. Unfortunately remote_start_remote() eventually calls
4349 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4350 around this. Eventually a mechanism that allows
4351 wait_for_inferior() to expect/get timeouts will be
4353 wait_forever_enabled_p = 0;
4356 /* First delete any symbols previously loaded from shared libraries. */
4357 no_shared_libraries (NULL, 0);
4360 init_thread_list ();
4362 /* Start the remote connection. If error() or QUIT, discard this
4363 target (we'd otherwise be in an inconsistent state) and then
4364 propogate the error on up the exception chain. This ensures that
4365 the caller doesn't stumble along blindly assuming that the
4366 function succeeded. The CLI doesn't have this problem but other
4367 UI's, such as MI do.
4369 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4370 this function should return an error indication letting the
4371 caller restore the previous state. Unfortunately the command
4372 ``target remote'' is directly wired to this function making that
4373 impossible. On a positive note, the CLI side of this problem has
4374 been fixed - the function set_cmd_context() makes it possible for
4375 all the ``target ....'' commands to share a common callback
4376 function. See cli-dump.c. */
4381 remote_start_remote (from_tty, target, extended_p);
4383 CATCH (ex, RETURN_MASK_ALL)
4385 /* Pop the partially set up target - unless something else did
4386 already before throwing the exception. */
4387 if (rs->remote_desc != NULL)
4388 remote_unpush_target ();
4389 if (target_async_permitted)
4390 wait_forever_enabled_p = 1;
4391 throw_exception (ex);
4396 remote_btrace_reset ();
4398 if (target_async_permitted)
4399 wait_forever_enabled_p = 1;
4402 /* This takes a program previously attached to and detaches it. After
4403 this is done, GDB can be used to debug some other program. We
4404 better not have left any breakpoints in the target program or it'll
4405 die when it hits one. */
4408 remote_detach_1 (const char *args, int from_tty, int extended)
4410 int pid = ptid_get_pid (inferior_ptid);
4411 struct remote_state *rs = get_remote_state ();
4414 error (_("Argument given to \"detach\" when remotely debugging."));
4416 if (!target_has_execution)
4417 error (_("No process to detach from."));
4421 char *exec_file = get_exec_file (0);
4422 if (exec_file == NULL)
4424 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4425 target_pid_to_str (pid_to_ptid (pid)));
4426 gdb_flush (gdb_stdout);
4429 /* Tell the remote target to detach. */
4430 if (remote_multi_process_p (rs))
4431 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4433 strcpy (rs->buf, "D");
4436 getpkt (&rs->buf, &rs->buf_size, 0);
4438 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4440 else if (rs->buf[0] == '\0')
4441 error (_("Remote doesn't know how to detach"));
4443 error (_("Can't detach process."));
4445 if (from_tty && !extended)
4446 puts_filtered (_("Ending remote debugging.\n"));
4448 target_mourn_inferior ();
4452 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4454 remote_detach_1 (args, from_tty, 0);
4458 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4460 remote_detach_1 (args, from_tty, 1);
4463 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4466 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4469 error (_("Argument given to \"disconnect\" when remotely debugging."));
4471 /* Make sure we unpush even the extended remote targets; mourn
4472 won't do it. So call remote_mourn directly instead of
4473 target_mourn_inferior. */
4474 remote_mourn (target);
4477 puts_filtered ("Ending remote debugging.\n");
4480 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4481 be chatty about it. */
4484 extended_remote_attach (struct target_ops *target, const char *args,
4487 struct remote_state *rs = get_remote_state ();
4489 char *wait_status = NULL;
4491 pid = parse_pid_to_attach (args);
4493 /* Remote PID can be freely equal to getpid, do not check it here the same
4494 way as in other targets. */
4496 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4497 error (_("This target does not support attaching to a process"));
4501 char *exec_file = get_exec_file (0);
4504 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4505 target_pid_to_str (pid_to_ptid (pid)));
4507 printf_unfiltered (_("Attaching to %s\n"),
4508 target_pid_to_str (pid_to_ptid (pid)));
4510 gdb_flush (gdb_stdout);
4513 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4515 getpkt (&rs->buf, &rs->buf_size, 0);
4517 switch (packet_ok (rs->buf,
4518 &remote_protocol_packets[PACKET_vAttach]))
4523 /* Save the reply for later. */
4524 wait_status = alloca (strlen (rs->buf) + 1);
4525 strcpy (wait_status, rs->buf);
4527 else if (strcmp (rs->buf, "OK") != 0)
4528 error (_("Attaching to %s failed with: %s"),
4529 target_pid_to_str (pid_to_ptid (pid)),
4532 case PACKET_UNKNOWN:
4533 error (_("This target does not support attaching to a process"));
4535 error (_("Attaching to %s failed"),
4536 target_pid_to_str (pid_to_ptid (pid)));
4539 set_current_inferior (remote_add_inferior (0, pid, 1));
4541 inferior_ptid = pid_to_ptid (pid);
4545 struct thread_info *thread;
4547 /* Get list of threads. */
4548 remote_update_thread_list (target);
4550 thread = first_thread_of_process (pid);
4552 inferior_ptid = thread->ptid;
4554 inferior_ptid = pid_to_ptid (pid);
4556 /* Invalidate our notion of the remote current thread. */
4557 record_currthread (rs, minus_one_ptid);
4561 /* Now, if we have thread information, update inferior_ptid. */
4562 inferior_ptid = remote_current_thread (inferior_ptid);
4564 /* Add the main thread to the thread list. */
4565 add_thread_silent (inferior_ptid);
4568 /* Next, if the target can specify a description, read it. We do
4569 this before anything involving memory or registers. */
4570 target_find_description ();
4574 /* Use the previously fetched status. */
4575 gdb_assert (wait_status != NULL);
4577 if (target_can_async_p ())
4579 struct notif_event *reply
4580 = remote_notif_parse (¬if_client_stop, wait_status);
4582 push_stop_reply ((struct stop_reply *) reply);
4588 gdb_assert (wait_status != NULL);
4589 strcpy (rs->buf, wait_status);
4590 rs->cached_wait_status = 1;
4594 gdb_assert (wait_status == NULL);
4597 /* Implementation of the to_post_attach method. */
4600 extended_remote_post_attach (struct target_ops *ops, int pid)
4602 /* In certain cases GDB might not have had the chance to start
4603 symbol lookup up until now. This could happen if the debugged
4604 binary is not using shared libraries, the vsyscall page is not
4605 present (on Linux) and the binary itself hadn't changed since the
4606 debugging process was started. */
4607 if (symfile_objfile != NULL)
4608 remote_check_symbols();
4612 /* Check for the availability of vCont. This function should also check
4616 remote_vcont_probe (struct remote_state *rs)
4620 strcpy (rs->buf, "vCont?");
4622 getpkt (&rs->buf, &rs->buf_size, 0);
4625 /* Make sure that the features we assume are supported. */
4626 if (startswith (buf, "vCont"))
4629 int support_s, support_S, support_c, support_C;
4635 rs->supports_vCont.t = 0;
4636 rs->supports_vCont.r = 0;
4637 while (p && *p == ';')
4640 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4642 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4644 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4646 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4648 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4649 rs->supports_vCont.t = 1;
4650 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4651 rs->supports_vCont.r = 1;
4653 p = strchr (p, ';');
4656 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4657 BUF will make packet_ok disable the packet. */
4658 if (!support_s || !support_S || !support_c || !support_C)
4662 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4665 /* Helper function for building "vCont" resumptions. Write a
4666 resumption to P. ENDP points to one-passed-the-end of the buffer
4667 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4668 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4669 resumed thread should be single-stepped and/or signalled. If PTID
4670 equals minus_one_ptid, then all threads are resumed; if PTID
4671 represents a process, then all threads of the process are resumed;
4672 the thread to be stepped and/or signalled is given in the global
4676 append_resumption (char *p, char *endp,
4677 ptid_t ptid, int step, enum gdb_signal siggnal)
4679 struct remote_state *rs = get_remote_state ();
4681 if (step && siggnal != GDB_SIGNAL_0)
4682 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4684 /* GDB is willing to range step. */
4685 && use_range_stepping
4686 /* Target supports range stepping. */
4687 && rs->supports_vCont.r
4688 /* We don't currently support range stepping multiple
4689 threads with a wildcard (though the protocol allows it,
4690 so stubs shouldn't make an active effort to forbid
4692 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4694 struct thread_info *tp;
4696 if (ptid_equal (ptid, minus_one_ptid))
4698 /* If we don't know about the target thread's tid, then
4699 we're resuming magic_null_ptid (see caller). */
4700 tp = find_thread_ptid (magic_null_ptid);
4703 tp = find_thread_ptid (ptid);
4704 gdb_assert (tp != NULL);
4706 if (tp->control.may_range_step)
4708 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4710 p += xsnprintf (p, endp - p, ";r%s,%s",
4711 phex_nz (tp->control.step_range_start,
4713 phex_nz (tp->control.step_range_end,
4717 p += xsnprintf (p, endp - p, ";s");
4720 p += xsnprintf (p, endp - p, ";s");
4721 else if (siggnal != GDB_SIGNAL_0)
4722 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4724 p += xsnprintf (p, endp - p, ";c");
4726 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4730 /* All (-1) threads of process. */
4731 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4733 p += xsnprintf (p, endp - p, ":");
4734 p = write_ptid (p, endp, nptid);
4736 else if (!ptid_equal (ptid, minus_one_ptid))
4738 p += xsnprintf (p, endp - p, ":");
4739 p = write_ptid (p, endp, ptid);
4745 /* Append a vCont continue-with-signal action for threads that have a
4746 non-zero stop signal. */
4749 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4751 struct thread_info *thread;
4753 ALL_NON_EXITED_THREADS (thread)
4754 if (ptid_match (thread->ptid, ptid)
4755 && !ptid_equal (inferior_ptid, thread->ptid)
4756 && thread->suspend.stop_signal != GDB_SIGNAL_0)
4758 p = append_resumption (p, endp, thread->ptid,
4759 0, thread->suspend.stop_signal);
4760 thread->suspend.stop_signal = GDB_SIGNAL_0;
4766 /* Resume the remote inferior by using a "vCont" packet. The thread
4767 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4768 resumed thread should be single-stepped and/or signalled. If PTID
4769 equals minus_one_ptid, then all threads are resumed; the thread to
4770 be stepped and/or signalled is given in the global INFERIOR_PTID.
4771 This function returns non-zero iff it resumes the inferior.
4773 This function issues a strict subset of all possible vCont commands at the
4777 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4779 struct remote_state *rs = get_remote_state ();
4783 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4784 remote_vcont_probe (rs);
4786 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
4790 endp = rs->buf + get_remote_packet_size ();
4792 /* If we could generate a wider range of packets, we'd have to worry
4793 about overflowing BUF. Should there be a generic
4794 "multi-part-packet" packet? */
4796 p += xsnprintf (p, endp - p, "vCont");
4798 if (ptid_equal (ptid, magic_null_ptid))
4800 /* MAGIC_NULL_PTID means that we don't have any active threads,
4801 so we don't have any TID numbers the inferior will
4802 understand. Make sure to only send forms that do not specify
4804 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4806 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4808 /* Resume all threads (of all processes, or of a single
4809 process), with preference for INFERIOR_PTID. This assumes
4810 inferior_ptid belongs to the set of all threads we are about
4812 if (step || siggnal != GDB_SIGNAL_0)
4814 /* Step inferior_ptid, with or without signal. */
4815 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4818 /* Also pass down any pending signaled resumption for other
4819 threads not the current. */
4820 p = append_pending_thread_resumptions (p, endp, ptid);
4822 /* And continue others without a signal. */
4823 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4827 /* Scheduler locking; resume only PTID. */
4828 append_resumption (p, endp, ptid, step, siggnal);
4831 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4836 /* In non-stop, the stub replies to vCont with "OK". The stop
4837 reply will be reported asynchronously by means of a `%Stop'
4839 getpkt (&rs->buf, &rs->buf_size, 0);
4840 if (strcmp (rs->buf, "OK") != 0)
4841 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4847 /* Tell the remote machine to resume. */
4850 remote_resume (struct target_ops *ops,
4851 ptid_t ptid, int step, enum gdb_signal siggnal)
4853 struct remote_state *rs = get_remote_state ();
4856 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4857 (explained in remote-notif.c:handle_notification) so
4858 remote_notif_process is not called. We need find a place where
4859 it is safe to start a 'vNotif' sequence. It is good to do it
4860 before resuming inferior, because inferior was stopped and no RSP
4861 traffic at that moment. */
4863 remote_notif_process (rs->notif_state, ¬if_client_stop);
4865 rs->last_sent_signal = siggnal;
4866 rs->last_sent_step = step;
4868 /* The vCont packet doesn't need to specify threads via Hc. */
4869 /* No reverse support (yet) for vCont. */
4870 if (execution_direction != EXEC_REVERSE)
4871 if (remote_vcont_resume (ptid, step, siggnal))
4874 /* All other supported resume packets do use Hc, so set the continue
4876 if (ptid_equal (ptid, minus_one_ptid))
4877 set_continue_thread (any_thread_ptid);
4879 set_continue_thread (ptid);
4882 if (execution_direction == EXEC_REVERSE)
4884 /* We don't pass signals to the target in reverse exec mode. */
4885 if (info_verbose && siggnal != GDB_SIGNAL_0)
4886 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4889 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
4890 error (_("Remote reverse-step not supported."));
4891 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
4892 error (_("Remote reverse-continue not supported."));
4894 strcpy (buf, step ? "bs" : "bc");
4896 else if (siggnal != GDB_SIGNAL_0)
4898 buf[0] = step ? 'S' : 'C';
4899 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4900 buf[2] = tohex (((int) siggnal) & 0xf);
4904 strcpy (buf, step ? "s" : "c");
4909 /* We are about to start executing the inferior, let's register it
4910 with the event loop. NOTE: this is the one place where all the
4911 execution commands end up. We could alternatively do this in each
4912 of the execution commands in infcmd.c. */
4913 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4914 into infcmd.c in order to allow inferior function calls to work
4915 NOT asynchronously. */
4916 if (target_can_async_p ())
4919 /* We've just told the target to resume. The remote server will
4920 wait for the inferior to stop, and then send a stop reply. In
4921 the mean time, we can't start another command/query ourselves
4922 because the stub wouldn't be ready to process it. This applies
4923 only to the base all-stop protocol, however. In non-stop (which
4924 only supports vCont), the stub replies with an "OK", and is
4925 immediate able to process further serial input. */
4927 rs->waiting_for_stop_reply = 1;
4931 /* Set up the signal handler for SIGINT, while the target is
4932 executing, ovewriting the 'regular' SIGINT signal handler. */
4934 async_initialize_sigint_signal_handler (void)
4936 signal (SIGINT, async_handle_remote_sigint);
4939 /* Signal handler for SIGINT, while the target is executing. */
4941 async_handle_remote_sigint (int sig)
4943 signal (sig, async_handle_remote_sigint_twice);
4944 /* Note we need to go through gdb_call_async_signal_handler in order
4945 to wake up the event loop on Windows. */
4946 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
4949 /* Signal handler for SIGINT, installed after SIGINT has already been
4950 sent once. It will take effect the second time that the user sends
4953 async_handle_remote_sigint_twice (int sig)
4955 signal (sig, async_handle_remote_sigint);
4956 /* See note in async_handle_remote_sigint. */
4957 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
4960 /* Perform the real interruption of the target execution, in response
4963 async_remote_interrupt (gdb_client_data arg)
4966 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
4968 target_stop (inferior_ptid);
4971 /* Perform interrupt, if the first attempt did not succeed. Just give
4972 up on the target alltogether. */
4974 async_remote_interrupt_twice (gdb_client_data arg)
4977 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
4982 /* Reinstall the usual SIGINT handlers, after the target has
4985 async_cleanup_sigint_signal_handler (void *dummy)
4987 signal (SIGINT, handle_sigint);
4990 /* Send ^C to target to halt it. Target will respond, and send us a
4992 static void (*ofunc) (int);
4994 /* The command line interface's stop routine. This function is installed
4995 as a signal handler for SIGINT. The first time a user requests a
4996 stop, we call remote_stop to send a break or ^C. If there is no
4997 response from the target (it didn't stop when the user requested it),
4998 we ask the user if he'd like to detach from the target. */
5000 sync_remote_interrupt (int signo)
5002 /* If this doesn't work, try more severe steps. */
5003 signal (signo, sync_remote_interrupt_twice);
5005 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5008 /* The user typed ^C twice. */
5011 sync_remote_interrupt_twice (int signo)
5013 signal (signo, ofunc);
5014 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5015 signal (signo, sync_remote_interrupt);
5018 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5019 thread, all threads of a remote process, or all threads of all
5023 remote_stop_ns (ptid_t ptid)
5025 struct remote_state *rs = get_remote_state ();
5027 char *endp = rs->buf + get_remote_packet_size ();
5029 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5030 remote_vcont_probe (rs);
5032 if (!rs->supports_vCont.t)
5033 error (_("Remote server does not support stopping threads"));
5035 if (ptid_equal (ptid, minus_one_ptid)
5036 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5037 p += xsnprintf (p, endp - p, "vCont;t");
5042 p += xsnprintf (p, endp - p, "vCont;t:");
5044 if (ptid_is_pid (ptid))
5045 /* All (-1) threads of process. */
5046 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5049 /* Small optimization: if we already have a stop reply for
5050 this thread, no use in telling the stub we want this
5052 if (peek_stop_reply (ptid))
5058 write_ptid (p, endp, nptid);
5061 /* In non-stop, we get an immediate OK reply. The stop reply will
5062 come in asynchronously by notification. */
5064 getpkt (&rs->buf, &rs->buf_size, 0);
5065 if (strcmp (rs->buf, "OK") != 0)
5066 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5069 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5070 remote target. It is undefined which thread of which process
5071 reports the stop. */
5074 remote_stop_as (ptid_t ptid)
5076 struct remote_state *rs = get_remote_state ();
5078 rs->ctrlc_pending_p = 1;
5080 /* If the inferior is stopped already, but the core didn't know
5081 about it yet, just ignore the request. The cached wait status
5082 will be collected in remote_wait. */
5083 if (rs->cached_wait_status)
5086 /* Send interrupt_sequence to remote target. */
5087 send_interrupt_sequence ();
5090 /* This is the generic stop called via the target vector. When a target
5091 interrupt is requested, either by the command line or the GUI, we
5092 will eventually end up here. */
5095 remote_stop (struct target_ops *self, ptid_t ptid)
5098 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5101 remote_stop_ns (ptid);
5103 remote_stop_as (ptid);
5106 /* Ask the user what to do when an interrupt is received. */
5109 interrupt_query (void)
5111 target_terminal_ours ();
5113 if (target_is_async_p ())
5115 signal (SIGINT, handle_sigint);
5120 if (query (_("Interrupted while waiting for the program.\n\
5121 Give up (and stop debugging it)? ")))
5123 remote_unpush_target ();
5128 target_terminal_inferior ();
5131 /* Enable/disable target terminal ownership. Most targets can use
5132 terminal groups to control terminal ownership. Remote targets are
5133 different in that explicit transfer of ownership to/from GDB/target
5137 remote_terminal_inferior (struct target_ops *self)
5139 if (!target_async_permitted)
5140 /* Nothing to do. */
5143 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5144 idempotent. The event-loop GDB talking to an asynchronous target
5145 with a synchronous command calls this function from both
5146 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5147 transfer the terminal to the target when it shouldn't this guard
5149 if (!remote_async_terminal_ours_p)
5151 delete_file_handler (input_fd);
5152 remote_async_terminal_ours_p = 0;
5153 async_initialize_sigint_signal_handler ();
5154 /* NOTE: At this point we could also register our selves as the
5155 recipient of all input. Any characters typed could then be
5156 passed on down to the target. */
5160 remote_terminal_ours (struct target_ops *self)
5162 if (!target_async_permitted)
5163 /* Nothing to do. */
5166 /* See FIXME in remote_terminal_inferior. */
5167 if (remote_async_terminal_ours_p)
5169 async_cleanup_sigint_signal_handler (NULL);
5170 add_file_handler (input_fd, stdin_event_handler, 0);
5171 remote_async_terminal_ours_p = 1;
5175 remote_console_output (char *msg)
5179 for (p = msg; p[0] && p[1]; p += 2)
5182 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5186 fputs_unfiltered (tb, gdb_stdtarg);
5188 gdb_flush (gdb_stdtarg);
5191 typedef struct cached_reg
5194 gdb_byte data[MAX_REGISTER_SIZE];
5197 DEF_VEC_O(cached_reg_t);
5199 typedef struct stop_reply
5201 struct notif_event base;
5203 /* The identifier of the thread about this event */
5206 /* The remote state this event is associated with. When the remote
5207 connection, represented by a remote_state object, is closed,
5208 all the associated stop_reply events should be released. */
5209 struct remote_state *rs;
5211 struct target_waitstatus ws;
5213 /* Expedited registers. This makes remote debugging a bit more
5214 efficient for those targets that provide critical registers as
5215 part of their normal status mechanism (as another roundtrip to
5216 fetch them is avoided). */
5217 VEC(cached_reg_t) *regcache;
5219 enum target_stop_reason stop_reason;
5221 CORE_ADDR watch_data_address;
5226 DECLARE_QUEUE_P (stop_reply_p);
5227 DEFINE_QUEUE_P (stop_reply_p);
5228 /* The list of already fetched and acknowledged stop events. This
5229 queue is used for notification Stop, and other notifications
5230 don't need queue for their events, because the notification events
5231 of Stop can't be consumed immediately, so that events should be
5232 queued first, and be consumed by remote_wait_{ns,as} one per
5233 time. Other notifications can consume their events immediately,
5234 so queue is not needed for them. */
5235 static QUEUE (stop_reply_p) *stop_reply_queue;
5238 stop_reply_xfree (struct stop_reply *r)
5240 notif_event_xfree ((struct notif_event *) r);
5244 remote_notif_stop_parse (struct notif_client *self, char *buf,
5245 struct notif_event *event)
5247 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5251 remote_notif_stop_ack (struct notif_client *self, char *buf,
5252 struct notif_event *event)
5254 struct stop_reply *stop_reply = (struct stop_reply *) event;
5257 putpkt ((char *) self->ack_command);
5259 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5260 /* We got an unknown stop reply. */
5261 error (_("Unknown stop reply"));
5263 push_stop_reply (stop_reply);
5267 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5269 /* We can't get pending events in remote_notif_process for
5270 notification stop, and we have to do this in remote_wait_ns
5271 instead. If we fetch all queued events from stub, remote stub
5272 may exit and we have no chance to process them back in
5274 mark_async_event_handler (remote_async_inferior_event_token);
5279 stop_reply_dtr (struct notif_event *event)
5281 struct stop_reply *r = (struct stop_reply *) event;
5283 VEC_free (cached_reg_t, r->regcache);
5286 static struct notif_event *
5287 remote_notif_stop_alloc_reply (void)
5289 struct notif_event *r
5290 = (struct notif_event *) XNEW (struct stop_reply);
5292 r->dtr = stop_reply_dtr;
5297 /* A client of notification Stop. */
5299 struct notif_client notif_client_stop =
5303 remote_notif_stop_parse,
5304 remote_notif_stop_ack,
5305 remote_notif_stop_can_get_pending_events,
5306 remote_notif_stop_alloc_reply,
5310 /* A parameter to pass data in and out. */
5312 struct queue_iter_param
5315 struct stop_reply *output;
5318 /* Remove stop replies in the queue if its pid is equal to the given
5322 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5323 QUEUE_ITER (stop_reply_p) *iter,
5327 struct queue_iter_param *param = data;
5328 struct inferior *inf = param->input;
5330 if (ptid_get_pid (event->ptid) == inf->pid)
5332 stop_reply_xfree (event);
5333 QUEUE_remove_elem (stop_reply_p, q, iter);
5339 /* Discard all pending stop replies of inferior INF. */
5342 discard_pending_stop_replies (struct inferior *inf)
5345 struct queue_iter_param param;
5346 struct stop_reply *reply;
5347 struct remote_state *rs = get_remote_state ();
5348 struct remote_notif_state *rns = rs->notif_state;
5350 /* This function can be notified when an inferior exists. When the
5351 target is not remote, the notification state is NULL. */
5352 if (rs->remote_desc == NULL)
5355 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5357 /* Discard the in-flight notification. */
5358 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5360 stop_reply_xfree (reply);
5361 rns->pending_event[notif_client_stop.id] = NULL;
5365 param.output = NULL;
5366 /* Discard the stop replies we have already pulled with
5368 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5369 remove_stop_reply_for_inferior, ¶m);
5372 /* If its remote state is equal to the given remote state,
5373 remove EVENT from the stop reply queue. */
5376 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5377 QUEUE_ITER (stop_reply_p) *iter,
5381 struct queue_iter_param *param = data;
5382 struct remote_state *rs = param->input;
5384 if (event->rs == rs)
5386 stop_reply_xfree (event);
5387 QUEUE_remove_elem (stop_reply_p, q, iter);
5393 /* Discard the stop replies for RS in stop_reply_queue. */
5396 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5398 struct queue_iter_param param;
5401 param.output = NULL;
5402 /* Discard the stop replies we have already pulled with
5404 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5405 remove_stop_reply_of_remote_state, ¶m);
5408 /* A parameter to pass data in and out. */
5411 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5412 QUEUE_ITER (stop_reply_p) *iter,
5416 struct queue_iter_param *param = data;
5417 ptid_t *ptid = param->input;
5419 if (ptid_match (event->ptid, *ptid))
5421 param->output = event;
5422 QUEUE_remove_elem (stop_reply_p, q, iter);
5429 /* Remove the first reply in 'stop_reply_queue' which matches
5432 static struct stop_reply *
5433 remote_notif_remove_queued_reply (ptid_t ptid)
5435 struct queue_iter_param param;
5437 param.input = &ptid;
5438 param.output = NULL;
5440 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5441 remote_notif_remove_once_on_match, ¶m);
5443 fprintf_unfiltered (gdb_stdlog,
5444 "notif: discard queued event: 'Stop' in %s\n",
5445 target_pid_to_str (ptid));
5447 return param.output;
5450 /* Look for a queued stop reply belonging to PTID. If one is found,
5451 remove it from the queue, and return it. Returns NULL if none is
5452 found. If there are still queued events left to process, tell the
5453 event loop to get back to target_wait soon. */
5455 static struct stop_reply *
5456 queued_stop_reply (ptid_t ptid)
5458 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5460 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5461 /* There's still at least an event left. */
5462 mark_async_event_handler (remote_async_inferior_event_token);
5467 /* Push a fully parsed stop reply in the stop reply queue. Since we
5468 know that we now have at least one queued event left to pass to the
5469 core side, tell the event loop to get back to target_wait soon. */
5472 push_stop_reply (struct stop_reply *new_event)
5474 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5477 fprintf_unfiltered (gdb_stdlog,
5478 "notif: push 'Stop' %s to queue %d\n",
5479 target_pid_to_str (new_event->ptid),
5480 QUEUE_length (stop_reply_p,
5483 mark_async_event_handler (remote_async_inferior_event_token);
5487 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5488 QUEUE_ITER (stop_reply_p) *iter,
5489 struct stop_reply *event,
5492 ptid_t *ptid = data;
5494 return !(ptid_equal (*ptid, event->ptid)
5495 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5498 /* Returns true if we have a stop reply for PTID. */
5501 peek_stop_reply (ptid_t ptid)
5503 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5504 stop_reply_match_ptid_and_ws, &ptid);
5507 /* Skip PACKET until the next semi-colon (or end of string). */
5510 skip_to_semicolon (char *p)
5512 while (*p != '\0' && *p != ';')
5517 /* Parse the stop reply in BUF. Either the function succeeds, and the
5518 result is stored in EVENT, or throws an error. */
5521 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5523 struct remote_arch_state *rsa = get_remote_arch_state ();
5527 event->ptid = null_ptid;
5528 event->rs = get_remote_state ();
5529 event->ws.kind = TARGET_WAITKIND_IGNORE;
5530 event->ws.value.integer = 0;
5531 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5532 event->regcache = NULL;
5537 case 'T': /* Status with PC, SP, FP, ... */
5538 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5539 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5541 n... = register number
5542 r... = register contents
5545 p = &buf[3]; /* after Txx */
5551 p1 = strchr (p, ':');
5553 error (_("Malformed packet(a) (missing colon): %s\n\
5557 error (_("Malformed packet(a) (missing register number): %s\n\
5561 /* Some "registers" are actually extended stop information.
5562 Note if you're adding a new entry here: GDB 7.9 and
5563 earlier assume that all register "numbers" that start
5564 with an hex digit are real register numbers. Make sure
5565 the server only sends such a packet if it knows the
5566 client understands it. */
5568 if (strncmp (p, "thread", p1 - p) == 0)
5569 event->ptid = read_ptid (++p1, &p);
5570 else if ((strncmp (p, "watch", p1 - p) == 0)
5571 || (strncmp (p, "rwatch", p1 - p) == 0)
5572 || (strncmp (p, "awatch", p1 - p) == 0))
5574 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
5575 p = unpack_varlen_hex (++p1, &addr);
5576 event->watch_data_address = (CORE_ADDR) addr;
5578 else if (strncmp (p, "swbreak", p1 - p) == 0)
5580 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5582 /* Make sure the stub doesn't forget to indicate support
5584 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5585 error (_("Unexpected swbreak stop reason"));
5587 /* The value part is documented as "must be empty",
5588 though we ignore it, in case we ever decide to make
5589 use of it in a backward compatible way. */
5590 p = skip_to_semicolon (p1 + 1);
5592 else if (strncmp (p, "hwbreak", p1 - p) == 0)
5594 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5596 /* Make sure the stub doesn't forget to indicate support
5598 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5599 error (_("Unexpected hwbreak stop reason"));
5602 p = skip_to_semicolon (p1 + 1);
5604 else if (strncmp (p, "library", p1 - p) == 0)
5606 event->ws.kind = TARGET_WAITKIND_LOADED;
5607 p = skip_to_semicolon (p1 + 1);
5609 else if (strncmp (p, "replaylog", p1 - p) == 0)
5611 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5612 /* p1 will indicate "begin" or "end", but it makes
5613 no difference for now, so ignore it. */
5614 p = skip_to_semicolon (p1 + 1);
5616 else if (strncmp (p, "core", p1 - p) == 0)
5620 p = unpack_varlen_hex (++p1, &c);
5628 /* Maybe a real ``P'' register number. */
5629 p_temp = unpack_varlen_hex (p, &pnum);
5630 /* If the first invalid character is the colon, we got a
5631 register number. Otherwise, it's an unknown stop
5635 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5636 cached_reg_t cached_reg;
5639 error (_("Remote sent bad register number %s: %s\n\
5641 hex_string (pnum), p, buf);
5643 cached_reg.num = reg->regnum;
5646 fieldsize = hex2bin (p, cached_reg.data,
5647 register_size (target_gdbarch (),
5650 if (fieldsize < register_size (target_gdbarch (),
5652 warning (_("Remote reply is too short: %s"), buf);
5654 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5658 /* Not a number. Silently skip unknown optional
5660 p = skip_to_semicolon (p1 + 1);
5665 error (_("Remote register badly formatted: %s\nhere: %s"),
5670 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5674 case 'S': /* Old style status, just signal only. */
5678 event->ws.kind = TARGET_WAITKIND_STOPPED;
5679 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5680 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5681 event->ws.value.sig = (enum gdb_signal) sig;
5683 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5686 case 'W': /* Target exited. */
5693 /* GDB used to accept only 2 hex chars here. Stubs should
5694 only send more if they detect GDB supports multi-process
5696 p = unpack_varlen_hex (&buf[1], &value);
5700 /* The remote process exited. */
5701 event->ws.kind = TARGET_WAITKIND_EXITED;
5702 event->ws.value.integer = value;
5706 /* The remote process exited with a signal. */
5707 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5708 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5709 event->ws.value.sig = (enum gdb_signal) value;
5711 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5714 /* If no process is specified, assume inferior_ptid. */
5715 pid = ptid_get_pid (inferior_ptid);
5724 else if (startswith (p, "process:"))
5728 p += sizeof ("process:") - 1;
5729 unpack_varlen_hex (p, &upid);
5733 error (_("unknown stop reply packet: %s"), buf);
5736 error (_("unknown stop reply packet: %s"), buf);
5737 event->ptid = pid_to_ptid (pid);
5742 if (non_stop && ptid_equal (event->ptid, null_ptid))
5743 error (_("No process or thread specified in stop reply: %s"), buf);
5746 /* When the stub wants to tell GDB about a new notification reply, it
5747 sends a notification (%Stop, for example). Those can come it at
5748 any time, hence, we have to make sure that any pending
5749 putpkt/getpkt sequence we're making is finished, before querying
5750 the stub for more events with the corresponding ack command
5751 (vStopped, for example). E.g., if we started a vStopped sequence
5752 immediately upon receiving the notification, something like this
5760 1.6) <-- (registers reply to step #1.3)
5762 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5765 To solve this, whenever we parse a %Stop notification successfully,
5766 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5767 doing whatever we were doing:
5773 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5774 2.5) <-- (registers reply to step #2.3)
5776 Eventualy after step #2.5, we return to the event loop, which
5777 notices there's an event on the
5778 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5779 associated callback --- the function below. At this point, we're
5780 always safe to start a vStopped sequence. :
5783 2.7) <-- T05 thread:2
5789 remote_notif_get_pending_events (struct notif_client *nc)
5791 struct remote_state *rs = get_remote_state ();
5793 if (rs->notif_state->pending_event[nc->id] != NULL)
5796 fprintf_unfiltered (gdb_stdlog,
5797 "notif: process: '%s' ack pending event\n",
5801 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5802 rs->notif_state->pending_event[nc->id] = NULL;
5806 getpkt (&rs->buf, &rs->buf_size, 0);
5807 if (strcmp (rs->buf, "OK") == 0)
5810 remote_notif_ack (nc, rs->buf);
5816 fprintf_unfiltered (gdb_stdlog,
5817 "notif: process: '%s' no pending reply\n",
5822 /* Called when it is decided that STOP_REPLY holds the info of the
5823 event that is to be returned to the core. This function always
5824 destroys STOP_REPLY. */
5827 process_stop_reply (struct stop_reply *stop_reply,
5828 struct target_waitstatus *status)
5832 *status = stop_reply->ws;
5833 ptid = stop_reply->ptid;
5835 /* If no thread/process was reported by the stub, assume the current
5837 if (ptid_equal (ptid, null_ptid))
5838 ptid = inferior_ptid;
5840 if (status->kind != TARGET_WAITKIND_EXITED
5841 && status->kind != TARGET_WAITKIND_SIGNALLED)
5843 struct remote_state *rs = get_remote_state ();
5845 /* Expedited registers. */
5846 if (stop_reply->regcache)
5848 struct regcache *regcache
5849 = get_thread_arch_regcache (ptid, target_gdbarch ());
5854 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5856 regcache_raw_supply (regcache, reg->num, reg->data);
5857 VEC_free (cached_reg_t, stop_reply->regcache);
5860 rs->stop_reason = stop_reply->stop_reason;
5861 rs->remote_watch_data_address = stop_reply->watch_data_address;
5863 remote_notice_new_inferior (ptid, 0);
5864 demand_private_info (ptid)->core = stop_reply->core;
5867 stop_reply_xfree (stop_reply);
5871 /* The non-stop mode version of target_wait. */
5874 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5876 struct remote_state *rs = get_remote_state ();
5877 struct stop_reply *stop_reply;
5881 /* If in non-stop mode, get out of getpkt even if a
5882 notification is received. */
5884 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5885 0 /* forever */, &is_notif);
5888 if (ret != -1 && !is_notif)
5891 case 'E': /* Error of some sort. */
5892 /* We're out of sync with the target now. Did it continue
5893 or not? We can't tell which thread it was in non-stop,
5894 so just ignore this. */
5895 warning (_("Remote failure reply: %s"), rs->buf);
5897 case 'O': /* Console output. */
5898 remote_console_output (rs->buf + 1);
5901 warning (_("Invalid remote reply: %s"), rs->buf);
5905 /* Acknowledge a pending stop reply that may have arrived in the
5907 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
5908 remote_notif_get_pending_events (¬if_client_stop);
5910 /* If indeed we noticed a stop reply, we're done. */
5911 stop_reply = queued_stop_reply (ptid);
5912 if (stop_reply != NULL)
5913 return process_stop_reply (stop_reply, status);
5915 /* Still no event. If we're just polling for an event, then
5916 return to the event loop. */
5917 if (options & TARGET_WNOHANG)
5919 status->kind = TARGET_WAITKIND_IGNORE;
5920 return minus_one_ptid;
5923 /* Otherwise do a blocking wait. */
5924 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5925 1 /* forever */, &is_notif);
5929 /* Wait until the remote machine stops, then return, storing status in
5930 STATUS just as `wait' would. */
5933 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5935 struct remote_state *rs = get_remote_state ();
5936 ptid_t event_ptid = null_ptid;
5938 struct stop_reply *stop_reply;
5942 status->kind = TARGET_WAITKIND_IGNORE;
5943 status->value.integer = 0;
5945 stop_reply = queued_stop_reply (ptid);
5946 if (stop_reply != NULL)
5947 return process_stop_reply (stop_reply, status);
5949 if (rs->cached_wait_status)
5950 /* Use the cached wait status, but only once. */
5951 rs->cached_wait_status = 0;
5957 if (!target_is_async_p ())
5959 ofunc = signal (SIGINT, sync_remote_interrupt);
5960 /* If the user hit C-c before this packet, or between packets,
5961 pretend that it was hit right here. */
5962 if (check_quit_flag ())
5965 sync_remote_interrupt (SIGINT);
5969 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5970 _never_ wait for ever -> test on target_is_async_p().
5971 However, before we do that we need to ensure that the caller
5972 knows how to take the target into/out of async mode. */
5973 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5974 wait_forever_enabled_p, &is_notif);
5976 if (!target_is_async_p ())
5977 signal (SIGINT, ofunc);
5979 /* GDB gets a notification. Return to core as this event is
5981 if (ret != -1 && is_notif)
5982 return minus_one_ptid;
5987 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5989 /* We got something. */
5990 rs->waiting_for_stop_reply = 0;
5992 /* Assume that the target has acknowledged Ctrl-C unless we receive
5993 an 'F' or 'O' packet. */
5994 if (buf[0] != 'F' && buf[0] != 'O')
5995 rs->ctrlc_pending_p = 0;
5999 case 'E': /* Error of some sort. */
6000 /* We're out of sync with the target now. Did it continue or
6001 not? Not is more likely, so report a stop. */
6002 warning (_("Remote failure reply: %s"), buf);
6003 status->kind = TARGET_WAITKIND_STOPPED;
6004 status->value.sig = GDB_SIGNAL_0;
6006 case 'F': /* File-I/O request. */
6007 remote_fileio_request (buf, rs->ctrlc_pending_p);
6008 rs->ctrlc_pending_p = 0;
6010 case 'T': case 'S': case 'X': case 'W':
6012 struct stop_reply *stop_reply
6013 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6016 event_ptid = process_stop_reply (stop_reply, status);
6019 case 'O': /* Console output. */
6020 remote_console_output (buf + 1);
6022 /* The target didn't really stop; keep waiting. */
6023 rs->waiting_for_stop_reply = 1;
6027 if (rs->last_sent_signal != GDB_SIGNAL_0)
6029 /* Zero length reply means that we tried 'S' or 'C' and the
6030 remote system doesn't support it. */
6031 target_terminal_ours_for_output ();
6033 ("Can't send signals to this remote system. %s not sent.\n",
6034 gdb_signal_to_name (rs->last_sent_signal));
6035 rs->last_sent_signal = GDB_SIGNAL_0;
6036 target_terminal_inferior ();
6038 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6039 putpkt ((char *) buf);
6041 /* We just told the target to resume, so a stop reply is in
6043 rs->waiting_for_stop_reply = 1;
6046 /* else fallthrough */
6048 warning (_("Invalid remote reply: %s"), buf);
6050 rs->waiting_for_stop_reply = 1;
6054 if (status->kind == TARGET_WAITKIND_IGNORE)
6056 /* Nothing interesting happened. If we're doing a non-blocking
6057 poll, we're done. Otherwise, go back to waiting. */
6058 if (options & TARGET_WNOHANG)
6059 return minus_one_ptid;
6063 else if (status->kind != TARGET_WAITKIND_EXITED
6064 && status->kind != TARGET_WAITKIND_SIGNALLED)
6066 if (!ptid_equal (event_ptid, null_ptid))
6067 record_currthread (rs, event_ptid);
6069 event_ptid = inferior_ptid;
6072 /* A process exit. Invalidate our notion of current thread. */
6073 record_currthread (rs, minus_one_ptid);
6078 /* Wait until the remote machine stops, then return, storing status in
6079 STATUS just as `wait' would. */
6082 remote_wait (struct target_ops *ops,
6083 ptid_t ptid, struct target_waitstatus *status, int options)
6088 event_ptid = remote_wait_ns (ptid, status, options);
6090 event_ptid = remote_wait_as (ptid, status, options);
6092 if (target_is_async_p ())
6094 /* If there are are events left in the queue tell the event loop
6096 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6097 mark_async_event_handler (remote_async_inferior_event_token);
6103 /* Fetch a single register using a 'p' packet. */
6106 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6108 struct remote_state *rs = get_remote_state ();
6110 char regp[MAX_REGISTER_SIZE];
6113 if (packet_support (PACKET_p) == PACKET_DISABLE)
6116 if (reg->pnum == -1)
6121 p += hexnumstr (p, reg->pnum);
6124 getpkt (&rs->buf, &rs->buf_size, 0);
6128 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6132 case PACKET_UNKNOWN:
6135 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6136 gdbarch_register_name (get_regcache_arch (regcache),
6141 /* If this register is unfetchable, tell the regcache. */
6144 regcache_raw_supply (regcache, reg->regnum, NULL);
6148 /* Otherwise, parse and supply the value. */
6154 error (_("fetch_register_using_p: early buf termination"));
6156 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6159 regcache_raw_supply (regcache, reg->regnum, regp);
6163 /* Fetch the registers included in the target's 'g' packet. */
6166 send_g_packet (void)
6168 struct remote_state *rs = get_remote_state ();
6171 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6172 remote_send (&rs->buf, &rs->buf_size);
6174 /* We can get out of synch in various cases. If the first character
6175 in the buffer is not a hex character, assume that has happened
6176 and try to fetch another packet to read. */
6177 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6178 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6179 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6180 && rs->buf[0] != 'x') /* New: unavailable register value. */
6183 fprintf_unfiltered (gdb_stdlog,
6184 "Bad register packet; fetching a new packet\n");
6185 getpkt (&rs->buf, &rs->buf_size, 0);
6188 buf_len = strlen (rs->buf);
6190 /* Sanity check the received packet. */
6191 if (buf_len % 2 != 0)
6192 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6198 process_g_packet (struct regcache *regcache)
6200 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6201 struct remote_state *rs = get_remote_state ();
6202 struct remote_arch_state *rsa = get_remote_arch_state ();
6207 buf_len = strlen (rs->buf);
6209 /* Further sanity checks, with knowledge of the architecture. */
6210 if (buf_len > 2 * rsa->sizeof_g_packet)
6211 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6213 /* Save the size of the packet sent to us by the target. It is used
6214 as a heuristic when determining the max size of packets that the
6215 target can safely receive. */
6216 if (rsa->actual_register_packet_size == 0)
6217 rsa->actual_register_packet_size = buf_len;
6219 /* If this is smaller than we guessed the 'g' packet would be,
6220 update our records. A 'g' reply that doesn't include a register's
6221 value implies either that the register is not available, or that
6222 the 'p' packet must be used. */
6223 if (buf_len < 2 * rsa->sizeof_g_packet)
6225 rsa->sizeof_g_packet = buf_len / 2;
6227 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6229 if (rsa->regs[i].pnum == -1)
6232 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6233 rsa->regs[i].in_g_packet = 0;
6235 rsa->regs[i].in_g_packet = 1;
6239 regs = alloca (rsa->sizeof_g_packet);
6241 /* Unimplemented registers read as all bits zero. */
6242 memset (regs, 0, rsa->sizeof_g_packet);
6244 /* Reply describes registers byte by byte, each byte encoded as two
6245 hex characters. Suck them all up, then supply them to the
6246 register cacheing/storage mechanism. */
6249 for (i = 0; i < rsa->sizeof_g_packet; i++)
6251 if (p[0] == 0 || p[1] == 0)
6252 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6253 internal_error (__FILE__, __LINE__,
6254 _("unexpected end of 'g' packet reply"));
6256 if (p[0] == 'x' && p[1] == 'x')
6257 regs[i] = 0; /* 'x' */
6259 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6263 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6265 struct packet_reg *r = &rsa->regs[i];
6269 if (r->offset * 2 >= strlen (rs->buf))
6270 /* This shouldn't happen - we adjusted in_g_packet above. */
6271 internal_error (__FILE__, __LINE__,
6272 _("unexpected end of 'g' packet reply"));
6273 else if (rs->buf[r->offset * 2] == 'x')
6275 gdb_assert (r->offset * 2 < strlen (rs->buf));
6276 /* The register isn't available, mark it as such (at
6277 the same time setting the value to zero). */
6278 regcache_raw_supply (regcache, r->regnum, NULL);
6281 regcache_raw_supply (regcache, r->regnum,
6288 fetch_registers_using_g (struct regcache *regcache)
6291 process_g_packet (regcache);
6294 /* Make the remote selected traceframe match GDB's selected
6298 set_remote_traceframe (void)
6301 struct remote_state *rs = get_remote_state ();
6303 if (rs->remote_traceframe_number == get_traceframe_number ())
6306 /* Avoid recursion, remote_trace_find calls us again. */
6307 rs->remote_traceframe_number = get_traceframe_number ();
6309 newnum = target_trace_find (tfind_number,
6310 get_traceframe_number (), 0, 0, NULL);
6312 /* Should not happen. If it does, all bets are off. */
6313 if (newnum != get_traceframe_number ())
6314 warning (_("could not set remote traceframe"));
6318 remote_fetch_registers (struct target_ops *ops,
6319 struct regcache *regcache, int regnum)
6321 struct remote_arch_state *rsa = get_remote_arch_state ();
6324 set_remote_traceframe ();
6325 set_general_thread (inferior_ptid);
6329 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6331 gdb_assert (reg != NULL);
6333 /* If this register might be in the 'g' packet, try that first -
6334 we are likely to read more than one register. If this is the
6335 first 'g' packet, we might be overly optimistic about its
6336 contents, so fall back to 'p'. */
6337 if (reg->in_g_packet)
6339 fetch_registers_using_g (regcache);
6340 if (reg->in_g_packet)
6344 if (fetch_register_using_p (regcache, reg))
6347 /* This register is not available. */
6348 regcache_raw_supply (regcache, reg->regnum, NULL);
6353 fetch_registers_using_g (regcache);
6355 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6356 if (!rsa->regs[i].in_g_packet)
6357 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6359 /* This register is not available. */
6360 regcache_raw_supply (regcache, i, NULL);
6364 /* Prepare to store registers. Since we may send them all (using a
6365 'G' request), we have to read out the ones we don't want to change
6369 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6371 struct remote_arch_state *rsa = get_remote_arch_state ();
6373 gdb_byte buf[MAX_REGISTER_SIZE];
6375 /* Make sure the entire registers array is valid. */
6376 switch (packet_support (PACKET_P))
6378 case PACKET_DISABLE:
6379 case PACKET_SUPPORT_UNKNOWN:
6380 /* Make sure all the necessary registers are cached. */
6381 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6382 if (rsa->regs[i].in_g_packet)
6383 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6390 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6391 packet was not recognized. */
6394 store_register_using_P (const struct regcache *regcache,
6395 struct packet_reg *reg)
6397 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6398 struct remote_state *rs = get_remote_state ();
6399 /* Try storing a single register. */
6400 char *buf = rs->buf;
6401 gdb_byte regp[MAX_REGISTER_SIZE];
6404 if (packet_support (PACKET_P) == PACKET_DISABLE)
6407 if (reg->pnum == -1)
6410 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6411 p = buf + strlen (buf);
6412 regcache_raw_collect (regcache, reg->regnum, regp);
6413 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6415 getpkt (&rs->buf, &rs->buf_size, 0);
6417 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6422 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6423 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6424 case PACKET_UNKNOWN:
6427 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6431 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6432 contents of the register cache buffer. FIXME: ignores errors. */
6435 store_registers_using_G (const struct regcache *regcache)
6437 struct remote_state *rs = get_remote_state ();
6438 struct remote_arch_state *rsa = get_remote_arch_state ();
6442 /* Extract all the registers in the regcache copying them into a
6447 regs = alloca (rsa->sizeof_g_packet);
6448 memset (regs, 0, rsa->sizeof_g_packet);
6449 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6451 struct packet_reg *r = &rsa->regs[i];
6454 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6458 /* Command describes registers byte by byte,
6459 each byte encoded as two hex characters. */
6462 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6464 bin2hex (regs, p, rsa->sizeof_g_packet);
6466 getpkt (&rs->buf, &rs->buf_size, 0);
6467 if (packet_check_result (rs->buf) == PACKET_ERROR)
6468 error (_("Could not write registers; remote failure reply '%s'"),
6472 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6473 of the register cache buffer. FIXME: ignores errors. */
6476 remote_store_registers (struct target_ops *ops,
6477 struct regcache *regcache, int regnum)
6479 struct remote_arch_state *rsa = get_remote_arch_state ();
6482 set_remote_traceframe ();
6483 set_general_thread (inferior_ptid);
6487 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6489 gdb_assert (reg != NULL);
6491 /* Always prefer to store registers using the 'P' packet if
6492 possible; we often change only a small number of registers.
6493 Sometimes we change a larger number; we'd need help from a
6494 higher layer to know to use 'G'. */
6495 if (store_register_using_P (regcache, reg))
6498 /* For now, don't complain if we have no way to write the
6499 register. GDB loses track of unavailable registers too
6500 easily. Some day, this may be an error. We don't have
6501 any way to read the register, either... */
6502 if (!reg->in_g_packet)
6505 store_registers_using_G (regcache);
6509 store_registers_using_G (regcache);
6511 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6512 if (!rsa->regs[i].in_g_packet)
6513 if (!store_register_using_P (regcache, &rsa->regs[i]))
6514 /* See above for why we do not issue an error here. */
6519 /* Return the number of hex digits in num. */
6522 hexnumlen (ULONGEST num)
6526 for (i = 0; num != 0; i++)
6532 /* Set BUF to the minimum number of hex digits representing NUM. */
6535 hexnumstr (char *buf, ULONGEST num)
6537 int len = hexnumlen (num);
6539 return hexnumnstr (buf, num, len);
6543 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6546 hexnumnstr (char *buf, ULONGEST num, int width)
6552 for (i = width - 1; i >= 0; i--)
6554 buf[i] = "0123456789abcdef"[(num & 0xf)];
6561 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6564 remote_address_masked (CORE_ADDR addr)
6566 unsigned int address_size = remote_address_size;
6568 /* If "remoteaddresssize" was not set, default to target address size. */
6570 address_size = gdbarch_addr_bit (target_gdbarch ());
6572 if (address_size > 0
6573 && address_size < (sizeof (ULONGEST) * 8))
6575 /* Only create a mask when that mask can safely be constructed
6576 in a ULONGEST variable. */
6579 mask = (mask << address_size) - 1;
6585 /* Determine whether the remote target supports binary downloading.
6586 This is accomplished by sending a no-op memory write of zero length
6587 to the target at the specified address. It does not suffice to send
6588 the whole packet, since many stubs strip the eighth bit and
6589 subsequently compute a wrong checksum, which causes real havoc with
6592 NOTE: This can still lose if the serial line is not eight-bit
6593 clean. In cases like this, the user should clear "remote
6597 check_binary_download (CORE_ADDR addr)
6599 struct remote_state *rs = get_remote_state ();
6601 switch (packet_support (PACKET_X))
6603 case PACKET_DISABLE:
6607 case PACKET_SUPPORT_UNKNOWN:
6613 p += hexnumstr (p, (ULONGEST) addr);
6615 p += hexnumstr (p, (ULONGEST) 0);
6619 putpkt_binary (rs->buf, (int) (p - rs->buf));
6620 getpkt (&rs->buf, &rs->buf_size, 0);
6622 if (rs->buf[0] == '\0')
6625 fprintf_unfiltered (gdb_stdlog,
6626 "binary downloading NOT "
6627 "supported by target\n");
6628 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6633 fprintf_unfiltered (gdb_stdlog,
6634 "binary downloading supported by target\n");
6635 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6642 /* Write memory data directly to the remote machine.
6643 This does not inform the data cache; the data cache uses this.
6644 HEADER is the starting part of the packet.
6645 MEMADDR is the address in the remote memory space.
6646 MYADDR is the address of the buffer in our space.
6647 LEN is the number of bytes.
6648 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6649 should send data as binary ('X'), or hex-encoded ('M').
6651 The function creates packet of the form
6652 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6654 where encoding of <DATA> is termined by PACKET_FORMAT.
6656 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6659 Return the transferred status, error or OK (an
6660 'enum target_xfer_status' value). Save the number of bytes
6661 transferred in *XFERED_LEN. Only transfer a single packet. */
6663 static enum target_xfer_status
6664 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6665 const gdb_byte *myaddr, ULONGEST len,
6666 ULONGEST *xfered_len, char packet_format,
6669 struct remote_state *rs = get_remote_state ();
6679 if (packet_format != 'X' && packet_format != 'M')
6680 internal_error (__FILE__, __LINE__,
6681 _("remote_write_bytes_aux: bad packet format"));
6684 return TARGET_XFER_EOF;
6686 payload_size = get_memory_write_packet_size ();
6688 /* The packet buffer will be large enough for the payload;
6689 get_memory_packet_size ensures this. */
6692 /* Compute the size of the actual payload by subtracting out the
6693 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6695 payload_size -= strlen ("$,:#NN");
6697 /* The comma won't be used. */
6699 header_length = strlen (header);
6700 payload_size -= header_length;
6701 payload_size -= hexnumlen (memaddr);
6703 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6705 strcat (rs->buf, header);
6706 p = rs->buf + strlen (header);
6708 /* Compute a best guess of the number of bytes actually transfered. */
6709 if (packet_format == 'X')
6711 /* Best guess at number of bytes that will fit. */
6712 todo = min (len, payload_size);
6714 payload_size -= hexnumlen (todo);
6715 todo = min (todo, payload_size);
6719 /* Num bytes that will fit. */
6720 todo = min (len, payload_size / 2);
6722 payload_size -= hexnumlen (todo);
6723 todo = min (todo, payload_size / 2);
6727 internal_error (__FILE__, __LINE__,
6728 _("minimum packet size too small to write data"));
6730 /* If we already need another packet, then try to align the end
6731 of this packet to a useful boundary. */
6732 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6733 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6735 /* Append "<memaddr>". */
6736 memaddr = remote_address_masked (memaddr);
6737 p += hexnumstr (p, (ULONGEST) memaddr);
6744 /* Append <len>. Retain the location/size of <len>. It may need to
6745 be adjusted once the packet body has been created. */
6747 plenlen = hexnumstr (p, (ULONGEST) todo);
6755 /* Append the packet body. */
6756 if (packet_format == 'X')
6758 /* Binary mode. Send target system values byte by byte, in
6759 increasing byte addresses. Only escape certain critical
6761 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6762 &nr_bytes, payload_size);
6764 /* If not all TODO bytes fit, then we'll need another packet. Make
6765 a second try to keep the end of the packet aligned. Don't do
6766 this if the packet is tiny. */
6767 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6771 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6773 if (new_nr_bytes != nr_bytes)
6774 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6775 (gdb_byte *) p, &nr_bytes,
6779 p += payload_length;
6780 if (use_length && nr_bytes < todo)
6782 /* Escape chars have filled up the buffer prematurely,
6783 and we have actually sent fewer bytes than planned.
6784 Fix-up the length field of the packet. Use the same
6785 number of characters as before. */
6786 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6787 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6792 /* Normal mode: Send target system values byte by byte, in
6793 increasing byte addresses. Each byte is encoded as a two hex
6795 nr_bytes = bin2hex (myaddr, p, todo);
6799 putpkt_binary (rs->buf, (int) (p - rs->buf));
6800 getpkt (&rs->buf, &rs->buf_size, 0);
6802 if (rs->buf[0] == 'E')
6803 return TARGET_XFER_E_IO;
6805 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6806 fewer bytes than we'd planned. */
6807 *xfered_len = (ULONGEST) nr_bytes;
6808 return TARGET_XFER_OK;
6811 /* Write memory data directly to the remote machine.
6812 This does not inform the data cache; the data cache uses this.
6813 MEMADDR is the address in the remote memory space.
6814 MYADDR is the address of the buffer in our space.
6815 LEN is the number of bytes.
6817 Return the transferred status, error or OK (an
6818 'enum target_xfer_status' value). Save the number of bytes
6819 transferred in *XFERED_LEN. Only transfer a single packet. */
6821 static enum target_xfer_status
6822 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6823 ULONGEST *xfered_len)
6825 char *packet_format = 0;
6827 /* Check whether the target supports binary download. */
6828 check_binary_download (memaddr);
6830 switch (packet_support (PACKET_X))
6833 packet_format = "X";
6835 case PACKET_DISABLE:
6836 packet_format = "M";
6838 case PACKET_SUPPORT_UNKNOWN:
6839 internal_error (__FILE__, __LINE__,
6840 _("remote_write_bytes: bad internal state"));
6842 internal_error (__FILE__, __LINE__, _("bad switch"));
6845 return remote_write_bytes_aux (packet_format,
6846 memaddr, myaddr, len, xfered_len,
6847 packet_format[0], 1);
6850 /* Read memory data directly from the remote machine.
6851 This does not use the data cache; the data cache uses this.
6852 MEMADDR is the address in the remote memory space.
6853 MYADDR is the address of the buffer in our space.
6854 LEN is the number of bytes.
6856 Return the transferred status, error or OK (an
6857 'enum target_xfer_status' value). Save the number of bytes
6858 transferred in *XFERED_LEN. */
6860 static enum target_xfer_status
6861 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6862 ULONGEST *xfered_len)
6864 struct remote_state *rs = get_remote_state ();
6865 int max_buf_size; /* Max size of packet output buffer. */
6870 max_buf_size = get_memory_read_packet_size ();
6871 /* The packet buffer will be large enough for the payload;
6872 get_memory_packet_size ensures this. */
6874 /* Number if bytes that will fit. */
6875 todo = min (len, max_buf_size / 2);
6877 /* Construct "m"<memaddr>","<len>". */
6878 memaddr = remote_address_masked (memaddr);
6881 p += hexnumstr (p, (ULONGEST) memaddr);
6883 p += hexnumstr (p, (ULONGEST) todo);
6886 getpkt (&rs->buf, &rs->buf_size, 0);
6887 if (rs->buf[0] == 'E'
6888 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6889 && rs->buf[3] == '\0')
6890 return TARGET_XFER_E_IO;
6891 /* Reply describes memory byte by byte, each byte encoded as two hex
6894 i = hex2bin (p, myaddr, todo);
6895 /* Return what we have. Let higher layers handle partial reads. */
6896 *xfered_len = (ULONGEST) i;
6897 return TARGET_XFER_OK;
6900 /* Using the set of read-only target sections of remote, read live
6903 For interface/parameters/return description see target.h,
6906 static enum target_xfer_status
6907 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6908 ULONGEST memaddr, ULONGEST len,
6909 ULONGEST *xfered_len)
6911 struct target_section *secp;
6912 struct target_section_table *table;
6914 secp = target_section_by_addr (ops, memaddr);
6916 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6917 secp->the_bfd_section)
6920 struct target_section *p;
6921 ULONGEST memend = memaddr + len;
6923 table = target_get_section_table (ops);
6925 for (p = table->sections; p < table->sections_end; p++)
6927 if (memaddr >= p->addr)
6929 if (memend <= p->endaddr)
6931 /* Entire transfer is within this section. */
6932 return remote_read_bytes_1 (memaddr, readbuf, len,
6935 else if (memaddr >= p->endaddr)
6937 /* This section ends before the transfer starts. */
6942 /* This section overlaps the transfer. Just do half. */
6943 len = p->endaddr - memaddr;
6944 return remote_read_bytes_1 (memaddr, readbuf, len,
6951 return TARGET_XFER_EOF;
6954 /* Similar to remote_read_bytes_1, but it reads from the remote stub
6955 first if the requested memory is unavailable in traceframe.
6956 Otherwise, fall back to remote_read_bytes_1. */
6958 static enum target_xfer_status
6959 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6960 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
6963 return TARGET_XFER_EOF;
6965 if (get_traceframe_number () != -1)
6967 VEC(mem_range_s) *available;
6969 /* If we fail to get the set of available memory, then the
6970 target does not support querying traceframe info, and so we
6971 attempt reading from the traceframe anyway (assuming the
6972 target implements the old QTro packet then). */
6973 if (traceframe_available_memory (&available, memaddr, len))
6975 struct cleanup *old_chain;
6977 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6979 if (VEC_empty (mem_range_s, available)
6980 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6982 enum target_xfer_status res;
6984 /* Don't read into the traceframe's available
6986 if (!VEC_empty (mem_range_s, available))
6988 LONGEST oldlen = len;
6990 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
6991 gdb_assert (len <= oldlen);
6994 do_cleanups (old_chain);
6996 /* This goes through the topmost target again. */
6997 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
6999 if (res == TARGET_XFER_OK)
7000 return TARGET_XFER_OK;
7003 /* No use trying further, we know some memory starting
7004 at MEMADDR isn't available. */
7006 return TARGET_XFER_UNAVAILABLE;
7010 /* Don't try to read more than how much is available, in
7011 case the target implements the deprecated QTro packet to
7012 cater for older GDBs (the target's knowledge of read-only
7013 sections may be outdated by now). */
7014 len = VEC_index (mem_range_s, available, 0)->length;
7016 do_cleanups (old_chain);
7020 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
7025 /* Sends a packet with content determined by the printf format string
7026 FORMAT and the remaining arguments, then gets the reply. Returns
7027 whether the packet was a success, a failure, or unknown. */
7029 static enum packet_result remote_send_printf (const char *format, ...)
7030 ATTRIBUTE_PRINTF (1, 2);
7032 static enum packet_result
7033 remote_send_printf (const char *format, ...)
7035 struct remote_state *rs = get_remote_state ();
7036 int max_size = get_remote_packet_size ();
7039 va_start (ap, format);
7042 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7043 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7045 if (putpkt (rs->buf) < 0)
7046 error (_("Communication problem with target."));
7049 getpkt (&rs->buf, &rs->buf_size, 0);
7051 return packet_check_result (rs->buf);
7055 restore_remote_timeout (void *p)
7057 int value = *(int *)p;
7059 remote_timeout = value;
7062 /* Flash writing can take quite some time. We'll set
7063 effectively infinite timeout for flash operations.
7064 In future, we'll need to decide on a better approach. */
7065 static const int remote_flash_timeout = 1000;
7068 remote_flash_erase (struct target_ops *ops,
7069 ULONGEST address, LONGEST length)
7071 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7072 int saved_remote_timeout = remote_timeout;
7073 enum packet_result ret;
7074 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7075 &saved_remote_timeout);
7077 remote_timeout = remote_flash_timeout;
7079 ret = remote_send_printf ("vFlashErase:%s,%s",
7080 phex (address, addr_size),
7084 case PACKET_UNKNOWN:
7085 error (_("Remote target does not support flash erase"));
7087 error (_("Error erasing flash with vFlashErase packet"));
7092 do_cleanups (back_to);
7095 static enum target_xfer_status
7096 remote_flash_write (struct target_ops *ops, ULONGEST address,
7097 ULONGEST length, ULONGEST *xfered_len,
7098 const gdb_byte *data)
7100 int saved_remote_timeout = remote_timeout;
7101 enum target_xfer_status ret;
7102 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7103 &saved_remote_timeout);
7105 remote_timeout = remote_flash_timeout;
7106 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7108 do_cleanups (back_to);
7114 remote_flash_done (struct target_ops *ops)
7116 int saved_remote_timeout = remote_timeout;
7118 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7119 &saved_remote_timeout);
7121 remote_timeout = remote_flash_timeout;
7122 ret = remote_send_printf ("vFlashDone");
7123 do_cleanups (back_to);
7127 case PACKET_UNKNOWN:
7128 error (_("Remote target does not support vFlashDone"));
7130 error (_("Error finishing flash operation"));
7137 remote_files_info (struct target_ops *ignore)
7139 puts_filtered ("Debugging a target over a serial line.\n");
7142 /* Stuff for dealing with the packets which are part of this protocol.
7143 See comment at top of file for details. */
7145 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7146 error to higher layers. Called when a serial error is detected.
7147 The exception message is STRING, followed by a colon and a blank,
7148 the system error message for errno at function entry and final dot
7149 for output compatibility with throw_perror_with_name. */
7152 unpush_and_perror (const char *string)
7154 int saved_errno = errno;
7156 remote_unpush_target ();
7157 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7158 safe_strerror (saved_errno));
7161 /* Read a single character from the remote end. */
7164 readchar (int timeout)
7167 struct remote_state *rs = get_remote_state ();
7169 ch = serial_readchar (rs->remote_desc, timeout);
7174 switch ((enum serial_rc) ch)
7177 remote_unpush_target ();
7178 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7181 unpush_and_perror (_("Remote communication error. "
7182 "Target disconnected."));
7184 case SERIAL_TIMEOUT:
7190 /* Wrapper for serial_write that closes the target and throws if
7194 remote_serial_write (const char *str, int len)
7196 struct remote_state *rs = get_remote_state ();
7198 if (serial_write (rs->remote_desc, str, len))
7200 unpush_and_perror (_("Remote communication error. "
7201 "Target disconnected."));
7205 /* Send the command in *BUF to the remote machine, and read the reply
7206 into *BUF. Report an error if we get an error reply. Resize
7207 *BUF using xrealloc if necessary to hold the result, and update
7211 remote_send (char **buf,
7215 getpkt (buf, sizeof_buf, 0);
7217 if ((*buf)[0] == 'E')
7218 error (_("Remote failure reply: %s"), *buf);
7221 /* Return a pointer to an xmalloc'ed string representing an escaped
7222 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7223 etc. The caller is responsible for releasing the returned
7227 escape_buffer (const char *buf, int n)
7229 struct cleanup *old_chain;
7230 struct ui_file *stb;
7233 stb = mem_fileopen ();
7234 old_chain = make_cleanup_ui_file_delete (stb);
7236 fputstrn_unfiltered (buf, n, '\\', stb);
7237 str = ui_file_xstrdup (stb, NULL);
7238 do_cleanups (old_chain);
7242 /* Display a null-terminated packet on stdout, for debugging, using C
7246 print_packet (const char *buf)
7248 puts_filtered ("\"");
7249 fputstr_filtered (buf, '"', gdb_stdout);
7250 puts_filtered ("\"");
7254 putpkt (const char *buf)
7256 return putpkt_binary (buf, strlen (buf));
7259 /* Send a packet to the remote machine, with error checking. The data
7260 of the packet is in BUF. The string in BUF can be at most
7261 get_remote_packet_size () - 5 to account for the $, # and checksum,
7262 and for a possible /0 if we are debugging (remote_debug) and want
7263 to print the sent packet as a string. */
7266 putpkt_binary (const char *buf, int cnt)
7268 struct remote_state *rs = get_remote_state ();
7270 unsigned char csum = 0;
7271 char *buf2 = alloca (cnt + 6);
7278 /* Catch cases like trying to read memory or listing threads while
7279 we're waiting for a stop reply. The remote server wouldn't be
7280 ready to handle this request, so we'd hang and timeout. We don't
7281 have to worry about this in synchronous mode, because in that
7282 case it's not possible to issue a command while the target is
7283 running. This is not a problem in non-stop mode, because in that
7284 case, the stub is always ready to process serial input. */
7285 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7287 error (_("Cannot execute this command while the target is running.\n"
7288 "Use the \"interrupt\" command to stop the target\n"
7289 "and then try again."));
7292 /* We're sending out a new packet. Make sure we don't look at a
7293 stale cached response. */
7294 rs->cached_wait_status = 0;
7296 /* Copy the packet into buffer BUF2, encapsulating it
7297 and giving it a checksum. */
7302 for (i = 0; i < cnt; i++)
7308 *p++ = tohex ((csum >> 4) & 0xf);
7309 *p++ = tohex (csum & 0xf);
7311 /* Send it over and over until we get a positive ack. */
7315 int started_error_output = 0;
7319 struct cleanup *old_chain;
7323 str = escape_buffer (buf2, p - buf2);
7324 old_chain = make_cleanup (xfree, str);
7325 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7326 gdb_flush (gdb_stdlog);
7327 do_cleanups (old_chain);
7329 remote_serial_write (buf2, p - buf2);
7331 /* If this is a no acks version of the remote protocol, send the
7332 packet and move on. */
7336 /* Read until either a timeout occurs (-2) or '+' is read.
7337 Handle any notification that arrives in the mean time. */
7340 ch = readchar (remote_timeout);
7348 case SERIAL_TIMEOUT:
7351 if (started_error_output)
7353 putchar_unfiltered ('\n');
7354 started_error_output = 0;
7363 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7367 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7369 case SERIAL_TIMEOUT:
7373 break; /* Retransmit buffer. */
7377 fprintf_unfiltered (gdb_stdlog,
7378 "Packet instead of Ack, ignoring it\n");
7379 /* It's probably an old response sent because an ACK
7380 was lost. Gobble up the packet and ack it so it
7381 doesn't get retransmitted when we resend this
7384 remote_serial_write ("+", 1);
7385 continue; /* Now, go look for +. */
7392 /* If we got a notification, handle it, and go back to looking
7394 /* We've found the start of a notification. Now
7395 collect the data. */
7396 val = read_frame (&rs->buf, &rs->buf_size);
7401 struct cleanup *old_chain;
7404 str = escape_buffer (rs->buf, val);
7405 old_chain = make_cleanup (xfree, str);
7406 fprintf_unfiltered (gdb_stdlog,
7407 " Notification received: %s\n",
7409 do_cleanups (old_chain);
7411 handle_notification (rs->notif_state, rs->buf);
7412 /* We're in sync now, rewait for the ack. */
7419 if (!started_error_output)
7421 started_error_output = 1;
7422 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7424 fputc_unfiltered (ch & 0177, gdb_stdlog);
7425 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7434 if (!started_error_output)
7436 started_error_output = 1;
7437 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7439 fputc_unfiltered (ch & 0177, gdb_stdlog);
7443 break; /* Here to retransmit. */
7447 /* This is wrong. If doing a long backtrace, the user should be
7448 able to get out next time we call QUIT, without anything as
7449 violent as interrupt_query. If we want to provide a way out of
7450 here without getting to the next QUIT, it should be based on
7451 hitting ^C twice as in remote_wait. */
7462 /* Come here after finding the start of a frame when we expected an
7463 ack. Do our best to discard the rest of this packet. */
7472 c = readchar (remote_timeout);
7475 case SERIAL_TIMEOUT:
7476 /* Nothing we can do. */
7479 /* Discard the two bytes of checksum and stop. */
7480 c = readchar (remote_timeout);
7482 c = readchar (remote_timeout);
7485 case '*': /* Run length encoding. */
7486 /* Discard the repeat count. */
7487 c = readchar (remote_timeout);
7492 /* A regular character. */
7498 /* Come here after finding the start of the frame. Collect the rest
7499 into *BUF, verifying the checksum, length, and handling run-length
7500 compression. NUL terminate the buffer. If there is not enough room,
7501 expand *BUF using xrealloc.
7503 Returns -1 on error, number of characters in buffer (ignoring the
7504 trailing NULL) on success. (could be extended to return one of the
7505 SERIAL status indications). */
7508 read_frame (char **buf_p,
7515 struct remote_state *rs = get_remote_state ();
7522 c = readchar (remote_timeout);
7525 case SERIAL_TIMEOUT:
7527 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7531 fputs_filtered ("Saw new packet start in middle of old one\n",
7533 return -1; /* Start a new packet, count retries. */
7536 unsigned char pktcsum;
7542 check_0 = readchar (remote_timeout);
7544 check_1 = readchar (remote_timeout);
7546 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7549 fputs_filtered ("Timeout in checksum, retrying\n",
7553 else if (check_0 < 0 || check_1 < 0)
7556 fputs_filtered ("Communication error in checksum\n",
7561 /* Don't recompute the checksum; with no ack packets we
7562 don't have any way to indicate a packet retransmission
7567 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7568 if (csum == pktcsum)
7573 struct cleanup *old_chain;
7576 str = escape_buffer (buf, bc);
7577 old_chain = make_cleanup (xfree, str);
7578 fprintf_unfiltered (gdb_stdlog,
7579 "Bad checksum, sentsum=0x%x, "
7580 "csum=0x%x, buf=%s\n",
7581 pktcsum, csum, str);
7582 do_cleanups (old_chain);
7584 /* Number of characters in buffer ignoring trailing
7588 case '*': /* Run length encoding. */
7593 c = readchar (remote_timeout);
7595 repeat = c - ' ' + 3; /* Compute repeat count. */
7597 /* The character before ``*'' is repeated. */
7599 if (repeat > 0 && repeat <= 255 && bc > 0)
7601 if (bc + repeat - 1 >= *sizeof_buf - 1)
7603 /* Make some more room in the buffer. */
7604 *sizeof_buf += repeat;
7605 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7609 memset (&buf[bc], buf[bc - 1], repeat);
7615 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7619 if (bc >= *sizeof_buf - 1)
7621 /* Make some more room in the buffer. */
7623 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7634 /* Read a packet from the remote machine, with error checking, and
7635 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7636 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7637 rather than timing out; this is used (in synchronous mode) to wait
7638 for a target that is is executing user code to stop. */
7639 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7640 don't have to change all the calls to getpkt to deal with the
7641 return value, because at the moment I don't know what the right
7642 thing to do it for those. */
7650 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7654 /* Read a packet from the remote machine, with error checking, and
7655 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7656 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7657 rather than timing out; this is used (in synchronous mode) to wait
7658 for a target that is is executing user code to stop. If FOREVER ==
7659 0, this function is allowed to time out gracefully and return an
7660 indication of this to the caller. Otherwise return the number of
7661 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7662 enough reason to return to the caller. *IS_NOTIF is an output
7663 boolean that indicates whether *BUF holds a notification or not
7664 (a regular packet). */
7667 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7668 int expecting_notif, int *is_notif)
7670 struct remote_state *rs = get_remote_state ();
7676 /* We're reading a new response. Make sure we don't look at a
7677 previously cached response. */
7678 rs->cached_wait_status = 0;
7680 strcpy (*buf, "timeout");
7683 timeout = watchdog > 0 ? watchdog : -1;
7684 else if (expecting_notif)
7685 timeout = 0; /* There should already be a char in the buffer. If
7688 timeout = remote_timeout;
7692 /* Process any number of notifications, and then return when
7696 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
7698 for (tries = 1; tries <= MAX_TRIES; tries++)
7700 /* This can loop forever if the remote side sends us
7701 characters continuously, but if it pauses, we'll get
7702 SERIAL_TIMEOUT from readchar because of timeout. Then
7703 we'll count that as a retry.
7705 Note that even when forever is set, we will only wait
7706 forever prior to the start of a packet. After that, we
7707 expect characters to arrive at a brisk pace. They should
7708 show up within remote_timeout intervals. */
7710 c = readchar (timeout);
7711 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7713 if (c == SERIAL_TIMEOUT)
7715 if (expecting_notif)
7716 return -1; /* Don't complain, it's normal to not get
7717 anything in this case. */
7719 if (forever) /* Watchdog went off? Kill the target. */
7722 remote_unpush_target ();
7723 throw_error (TARGET_CLOSE_ERROR,
7724 _("Watchdog timeout has expired. "
7725 "Target detached."));
7728 fputs_filtered ("Timed out.\n", gdb_stdlog);
7732 /* We've found the start of a packet or notification.
7733 Now collect the data. */
7734 val = read_frame (buf, sizeof_buf);
7739 remote_serial_write ("-", 1);
7742 if (tries > MAX_TRIES)
7744 /* We have tried hard enough, and just can't receive the
7745 packet/notification. Give up. */
7746 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7748 /* Skip the ack char if we're in no-ack mode. */
7749 if (!rs->noack_mode)
7750 remote_serial_write ("+", 1);
7754 /* If we got an ordinary packet, return that to our caller. */
7759 struct cleanup *old_chain;
7762 str = escape_buffer (*buf, val);
7763 old_chain = make_cleanup (xfree, str);
7764 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7765 do_cleanups (old_chain);
7768 /* Skip the ack char if we're in no-ack mode. */
7769 if (!rs->noack_mode)
7770 remote_serial_write ("+", 1);
7771 if (is_notif != NULL)
7776 /* If we got a notification, handle it, and go back to looking
7780 gdb_assert (c == '%');
7784 struct cleanup *old_chain;
7787 str = escape_buffer (*buf, val);
7788 old_chain = make_cleanup (xfree, str);
7789 fprintf_unfiltered (gdb_stdlog,
7790 " Notification received: %s\n",
7792 do_cleanups (old_chain);
7794 if (is_notif != NULL)
7797 handle_notification (rs->notif_state, *buf);
7799 /* Notifications require no acknowledgement. */
7801 if (expecting_notif)
7808 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7810 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7814 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7817 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7823 remote_kill (struct target_ops *ops)
7826 /* Catch errors so the user can quit from gdb even when we
7827 aren't on speaking terms with the remote system. */
7832 CATCH (ex, RETURN_MASK_ERROR)
7834 if (ex.error == TARGET_CLOSE_ERROR)
7836 /* If we got an (EOF) error that caused the target
7837 to go away, then we're done, that's what we wanted.
7838 "k" is susceptible to cause a premature EOF, given
7839 that the remote server isn't actually required to
7840 reply to "k", and it can happen that it doesn't
7841 even get to reply ACK to the "k". */
7845 /* Otherwise, something went wrong. We didn't actually kill
7846 the target. Just propagate the exception, and let the
7847 user or higher layers decide what to do. */
7848 throw_exception (ex);
7852 /* We've killed the remote end, we get to mourn it. Since this is
7853 target remote, single-process, mourning the inferior also
7854 unpushes remote_ops. */
7855 target_mourn_inferior ();
7859 remote_vkill (int pid, struct remote_state *rs)
7861 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
7864 /* Tell the remote target to detach. */
7865 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7867 getpkt (&rs->buf, &rs->buf_size, 0);
7869 switch (packet_ok (rs->buf,
7870 &remote_protocol_packets[PACKET_vKill]))
7876 case PACKET_UNKNOWN:
7879 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7884 extended_remote_kill (struct target_ops *ops)
7887 int pid = ptid_get_pid (inferior_ptid);
7888 struct remote_state *rs = get_remote_state ();
7890 res = remote_vkill (pid, rs);
7891 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7893 /* Don't try 'k' on a multi-process aware stub -- it has no way
7894 to specify the pid. */
7898 getpkt (&rs->buf, &rs->buf_size, 0);
7899 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7902 /* Don't wait for it to die. I'm not really sure it matters whether
7903 we do or not. For the existing stubs, kill is a noop. */
7909 error (_("Can't kill process"));
7911 target_mourn_inferior ();
7915 remote_mourn (struct target_ops *target)
7917 unpush_target (target);
7919 /* remote_close takes care of doing most of the clean up. */
7920 generic_mourn_inferior ();
7924 extended_remote_mourn (struct target_ops *target)
7926 struct remote_state *rs = get_remote_state ();
7928 /* In case we got here due to an error, but we're going to stay
7930 rs->waiting_for_stop_reply = 0;
7932 /* If the current general thread belonged to the process we just
7933 detached from or has exited, the remote side current general
7934 thread becomes undefined. Considering a case like this:
7936 - We just got here due to a detach.
7937 - The process that we're detaching from happens to immediately
7938 report a global breakpoint being hit in non-stop mode, in the
7939 same thread we had selected before.
7940 - GDB attaches to this process again.
7941 - This event happens to be the next event we handle.
7943 GDB would consider that the current general thread didn't need to
7944 be set on the stub side (with Hg), since for all it knew,
7945 GENERAL_THREAD hadn't changed.
7947 Notice that although in all-stop mode, the remote server always
7948 sets the current thread to the thread reporting the stop event,
7949 that doesn't happen in non-stop mode; in non-stop, the stub *must
7950 not* change the current thread when reporting a breakpoint hit,
7951 due to the decoupling of event reporting and event handling.
7953 To keep things simple, we always invalidate our notion of the
7955 record_currthread (rs, minus_one_ptid);
7957 /* Unlike "target remote", we do not want to unpush the target; then
7958 the next time the user says "run", we won't be connected. */
7960 /* Call common code to mark the inferior as not running. */
7961 generic_mourn_inferior ();
7963 if (!have_inferiors ())
7965 if (!remote_multi_process_p (rs))
7967 /* Check whether the target is running now - some remote stubs
7968 automatically restart after kill. */
7970 getpkt (&rs->buf, &rs->buf_size, 0);
7972 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7974 /* Assume that the target has been restarted. Set
7975 inferior_ptid so that bits of core GDB realizes
7976 there's something here, e.g., so that the user can
7977 say "kill" again. */
7978 inferior_ptid = magic_null_ptid;
7985 extended_remote_supports_disable_randomization (struct target_ops *self)
7987 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
7991 extended_remote_disable_randomization (int val)
7993 struct remote_state *rs = get_remote_state ();
7996 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7999 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8001 error (_("Target does not support QDisableRandomization."));
8002 if (strcmp (reply, "OK") != 0)
8003 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8007 extended_remote_run (char *args)
8009 struct remote_state *rs = get_remote_state ();
8012 /* If the user has disabled vRun support, or we have detected that
8013 support is not available, do not try it. */
8014 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8017 strcpy (rs->buf, "vRun;");
8018 len = strlen (rs->buf);
8020 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8021 error (_("Remote file name too long for run packet"));
8022 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8023 strlen (remote_exec_file));
8025 gdb_assert (args != NULL);
8028 struct cleanup *back_to;
8032 argv = gdb_buildargv (args);
8033 back_to = make_cleanup_freeargv (argv);
8034 for (i = 0; argv[i] != NULL; i++)
8036 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8037 error (_("Argument list too long for run packet"));
8038 rs->buf[len++] = ';';
8039 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8042 do_cleanups (back_to);
8045 rs->buf[len++] = '\0';
8048 getpkt (&rs->buf, &rs->buf_size, 0);
8050 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8053 /* We have a wait response. All is well. */
8055 case PACKET_UNKNOWN:
8058 if (remote_exec_file[0] == '\0')
8059 error (_("Running the default executable on the remote target failed; "
8060 "try \"set remote exec-file\"?"));
8062 error (_("Running \"%s\" on the remote target failed"),
8065 gdb_assert_not_reached (_("bad switch"));
8069 /* In the extended protocol we want to be able to do things like
8070 "run" and have them basically work as expected. So we need
8071 a special create_inferior function. We support changing the
8072 executable file and the command line arguments, but not the
8076 extended_remote_create_inferior (struct target_ops *ops,
8077 char *exec_file, char *args,
8078 char **env, int from_tty)
8082 struct remote_state *rs = get_remote_state ();
8084 /* If running asynchronously, register the target file descriptor
8085 with the event loop. */
8086 if (target_can_async_p ())
8089 /* Disable address space randomization if requested (and supported). */
8090 if (extended_remote_supports_disable_randomization (ops))
8091 extended_remote_disable_randomization (disable_randomization);
8093 /* Now restart the remote server. */
8094 run_worked = extended_remote_run (args) != -1;
8097 /* vRun was not supported. Fail if we need it to do what the
8099 if (remote_exec_file[0])
8100 error (_("Remote target does not support \"set remote exec-file\""));
8102 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8104 /* Fall back to "R". */
8105 extended_remote_restart ();
8108 if (!have_inferiors ())
8110 /* Clean up from the last time we ran, before we mark the target
8111 running again. This will mark breakpoints uninserted, and
8112 get_offsets may insert breakpoints. */
8113 init_thread_list ();
8114 init_wait_for_inferior ();
8117 /* vRun's success return is a stop reply. */
8118 stop_reply = run_worked ? rs->buf : NULL;
8119 add_current_inferior_and_thread (stop_reply);
8121 /* Get updated offsets, if the stub uses qOffsets. */
8126 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8127 the list of conditions (in agent expression bytecode format), if any, the
8128 target needs to evaluate. The output is placed into the packet buffer
8129 started from BUF and ended at BUF_END. */
8132 remote_add_target_side_condition (struct gdbarch *gdbarch,
8133 struct bp_target_info *bp_tgt, char *buf,
8136 struct agent_expr *aexpr = NULL;
8139 char *buf_start = buf;
8141 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8144 buf += strlen (buf);
8145 xsnprintf (buf, buf_end - buf, "%s", ";");
8148 /* Send conditions to the target and free the vector. */
8150 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8153 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8154 buf += strlen (buf);
8155 for (i = 0; i < aexpr->len; ++i)
8156 buf = pack_hex_byte (buf, aexpr->buf[i]);
8163 remote_add_target_side_commands (struct gdbarch *gdbarch,
8164 struct bp_target_info *bp_tgt, char *buf)
8166 struct agent_expr *aexpr = NULL;
8169 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8172 buf += strlen (buf);
8174 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8175 buf += strlen (buf);
8177 /* Concatenate all the agent expressions that are commands into the
8180 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8183 sprintf (buf, "X%x,", aexpr->len);
8184 buf += strlen (buf);
8185 for (i = 0; i < aexpr->len; ++i)
8186 buf = pack_hex_byte (buf, aexpr->buf[i]);
8191 /* Insert a breakpoint. On targets that have software breakpoint
8192 support, we ask the remote target to do the work; on targets
8193 which don't, we insert a traditional memory breakpoint. */
8196 remote_insert_breakpoint (struct target_ops *ops,
8197 struct gdbarch *gdbarch,
8198 struct bp_target_info *bp_tgt)
8200 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8201 If it succeeds, then set the support to PACKET_ENABLE. If it
8202 fails, and the user has explicitly requested the Z support then
8203 report an error, otherwise, mark it disabled and go on. */
8205 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8207 CORE_ADDR addr = bp_tgt->reqstd_address;
8208 struct remote_state *rs;
8211 struct condition_list *cond = NULL;
8213 /* Make sure the remote is pointing at the right process, if
8215 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8216 set_general_process ();
8218 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8220 rs = get_remote_state ();
8222 endbuf = rs->buf + get_remote_packet_size ();
8227 addr = (ULONGEST) remote_address_masked (addr);
8228 p += hexnumstr (p, addr);
8229 xsnprintf (p, endbuf - p, ",%d", bpsize);
8231 if (remote_supports_cond_breakpoints (ops))
8232 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8234 if (remote_can_run_breakpoint_commands (ops))
8235 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8238 getpkt (&rs->buf, &rs->buf_size, 0);
8240 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8245 bp_tgt->placed_address = addr;
8246 bp_tgt->placed_size = bpsize;
8248 case PACKET_UNKNOWN:
8253 /* If this breakpoint has target-side commands but this stub doesn't
8254 support Z0 packets, throw error. */
8255 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8256 throw_error (NOT_SUPPORTED_ERROR, _("\
8257 Target doesn't support breakpoints that have target side commands."));
8259 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8263 remote_remove_breakpoint (struct target_ops *ops,
8264 struct gdbarch *gdbarch,
8265 struct bp_target_info *bp_tgt)
8267 CORE_ADDR addr = bp_tgt->placed_address;
8268 struct remote_state *rs = get_remote_state ();
8270 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8273 char *endbuf = rs->buf + get_remote_packet_size ();
8275 /* Make sure the remote is pointing at the right process, if
8277 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8278 set_general_process ();
8284 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8285 p += hexnumstr (p, addr);
8286 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8289 getpkt (&rs->buf, &rs->buf_size, 0);
8291 return (rs->buf[0] == 'E');
8294 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8298 watchpoint_to_Z_packet (int type)
8303 return Z_PACKET_WRITE_WP;
8306 return Z_PACKET_READ_WP;
8309 return Z_PACKET_ACCESS_WP;
8312 internal_error (__FILE__, __LINE__,
8313 _("hw_bp_to_z: bad watchpoint type %d"), type);
8318 remote_insert_watchpoint (struct target_ops *self,
8319 CORE_ADDR addr, int len, int type,
8320 struct expression *cond)
8322 struct remote_state *rs = get_remote_state ();
8323 char *endbuf = rs->buf + get_remote_packet_size ();
8325 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8327 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8330 /* Make sure the remote is pointing at the right process, if
8332 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8333 set_general_process ();
8335 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8336 p = strchr (rs->buf, '\0');
8337 addr = remote_address_masked (addr);
8338 p += hexnumstr (p, (ULONGEST) addr);
8339 xsnprintf (p, endbuf - p, ",%x", len);
8342 getpkt (&rs->buf, &rs->buf_size, 0);
8344 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8348 case PACKET_UNKNOWN:
8353 internal_error (__FILE__, __LINE__,
8354 _("remote_insert_watchpoint: reached end of function"));
8358 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8359 CORE_ADDR start, int length)
8361 CORE_ADDR diff = remote_address_masked (addr - start);
8363 return diff < length;
8368 remote_remove_watchpoint (struct target_ops *self,
8369 CORE_ADDR addr, int len, int type,
8370 struct expression *cond)
8372 struct remote_state *rs = get_remote_state ();
8373 char *endbuf = rs->buf + get_remote_packet_size ();
8375 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8377 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8380 /* Make sure the remote is pointing at the right process, if
8382 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8383 set_general_process ();
8385 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8386 p = strchr (rs->buf, '\0');
8387 addr = remote_address_masked (addr);
8388 p += hexnumstr (p, (ULONGEST) addr);
8389 xsnprintf (p, endbuf - p, ",%x", len);
8391 getpkt (&rs->buf, &rs->buf_size, 0);
8393 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8396 case PACKET_UNKNOWN:
8401 internal_error (__FILE__, __LINE__,
8402 _("remote_remove_watchpoint: reached end of function"));
8406 int remote_hw_watchpoint_limit = -1;
8407 int remote_hw_watchpoint_length_limit = -1;
8408 int remote_hw_breakpoint_limit = -1;
8411 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8412 CORE_ADDR addr, int len)
8414 if (remote_hw_watchpoint_length_limit == 0)
8416 else if (remote_hw_watchpoint_length_limit < 0)
8418 else if (len <= remote_hw_watchpoint_length_limit)
8425 remote_check_watch_resources (struct target_ops *self,
8426 int type, int cnt, int ot)
8428 if (type == bp_hardware_breakpoint)
8430 if (remote_hw_breakpoint_limit == 0)
8432 else if (remote_hw_breakpoint_limit < 0)
8434 else if (cnt <= remote_hw_breakpoint_limit)
8439 if (remote_hw_watchpoint_limit == 0)
8441 else if (remote_hw_watchpoint_limit < 0)
8445 else if (cnt <= remote_hw_watchpoint_limit)
8451 /* The to_stopped_by_sw_breakpoint method of target remote. */
8454 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8456 struct remote_state *rs = get_remote_state ();
8458 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8461 /* The to_supports_stopped_by_sw_breakpoint method of target
8465 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8467 struct remote_state *rs = get_remote_state ();
8469 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8472 /* The to_stopped_by_hw_breakpoint method of target remote. */
8475 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8477 struct remote_state *rs = get_remote_state ();
8479 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8482 /* The to_supports_stopped_by_hw_breakpoint method of target
8486 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8488 struct remote_state *rs = get_remote_state ();
8490 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8494 remote_stopped_by_watchpoint (struct target_ops *ops)
8496 struct remote_state *rs = get_remote_state ();
8498 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
8502 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8504 struct remote_state *rs = get_remote_state ();
8507 if (remote_stopped_by_watchpoint (target))
8509 *addr_p = rs->remote_watch_data_address;
8518 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8519 struct bp_target_info *bp_tgt)
8521 CORE_ADDR addr = bp_tgt->reqstd_address;
8522 struct remote_state *rs;
8527 /* The length field should be set to the size of a breakpoint
8528 instruction, even though we aren't inserting one ourselves. */
8530 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8532 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8535 /* Make sure the remote is pointing at the right process, if
8537 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8538 set_general_process ();
8540 rs = get_remote_state ();
8542 endbuf = rs->buf + get_remote_packet_size ();
8548 addr = remote_address_masked (addr);
8549 p += hexnumstr (p, (ULONGEST) addr);
8550 xsnprintf (p, endbuf - p, ",%x", bpsize);
8552 if (remote_supports_cond_breakpoints (self))
8553 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8555 if (remote_can_run_breakpoint_commands (self))
8556 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8559 getpkt (&rs->buf, &rs->buf_size, 0);
8561 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8564 if (rs->buf[1] == '.')
8566 message = strchr (rs->buf + 2, '.');
8568 error (_("Remote failure reply: %s"), message + 1);
8571 case PACKET_UNKNOWN:
8574 bp_tgt->placed_address = addr;
8575 bp_tgt->placed_size = bpsize;
8578 internal_error (__FILE__, __LINE__,
8579 _("remote_insert_hw_breakpoint: reached end of function"));
8584 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8585 struct bp_target_info *bp_tgt)
8588 struct remote_state *rs = get_remote_state ();
8590 char *endbuf = rs->buf + get_remote_packet_size ();
8592 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8595 /* Make sure the remote is pointing at the right process, if
8597 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8598 set_general_process ();
8604 addr = remote_address_masked (bp_tgt->placed_address);
8605 p += hexnumstr (p, (ULONGEST) addr);
8606 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8609 getpkt (&rs->buf, &rs->buf_size, 0);
8611 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8614 case PACKET_UNKNOWN:
8619 internal_error (__FILE__, __LINE__,
8620 _("remote_remove_hw_breakpoint: reached end of function"));
8623 /* Verify memory using the "qCRC:" request. */
8626 remote_verify_memory (struct target_ops *ops,
8627 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8629 struct remote_state *rs = get_remote_state ();
8630 unsigned long host_crc, target_crc;
8633 /* It doesn't make sense to use qCRC if the remote target is
8634 connected but not running. */
8635 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8637 enum packet_result result;
8639 /* Make sure the remote is pointing at the right process. */
8640 set_general_process ();
8642 /* FIXME: assumes lma can fit into long. */
8643 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8644 (long) lma, (long) size);
8647 /* Be clever; compute the host_crc before waiting for target
8649 host_crc = xcrc32 (data, size, 0xffffffff);
8651 getpkt (&rs->buf, &rs->buf_size, 0);
8653 result = packet_ok (rs->buf,
8654 &remote_protocol_packets[PACKET_qCRC]);
8655 if (result == PACKET_ERROR)
8657 else if (result == PACKET_OK)
8659 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8660 target_crc = target_crc * 16 + fromhex (*tmp);
8662 return (host_crc == target_crc);
8666 return simple_verify_memory (ops, data, lma, size);
8669 /* compare-sections command
8671 With no arguments, compares each loadable section in the exec bfd
8672 with the same memory range on the target, and reports mismatches.
8673 Useful for verifying the image on the target against the exec file. */
8676 compare_sections_command (char *args, int from_tty)
8679 struct cleanup *old_chain;
8681 const char *sectname;
8690 error (_("command cannot be used without an exec file"));
8692 /* Make sure the remote is pointing at the right process. */
8693 set_general_process ();
8695 if (args != NULL && strcmp (args, "-r") == 0)
8701 for (s = exec_bfd->sections; s; s = s->next)
8703 if (!(s->flags & SEC_LOAD))
8704 continue; /* Skip non-loadable section. */
8706 if (read_only && (s->flags & SEC_READONLY) == 0)
8707 continue; /* Skip writeable sections */
8709 size = bfd_get_section_size (s);
8711 continue; /* Skip zero-length section. */
8713 sectname = bfd_get_section_name (exec_bfd, s);
8714 if (args && strcmp (args, sectname) != 0)
8715 continue; /* Not the section selected by user. */
8717 matched = 1; /* Do this section. */
8720 sectdata = xmalloc (size);
8721 old_chain = make_cleanup (xfree, sectdata);
8722 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8724 res = target_verify_memory (sectdata, lma, size);
8727 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8728 paddress (target_gdbarch (), lma),
8729 paddress (target_gdbarch (), lma + size));
8731 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8732 paddress (target_gdbarch (), lma),
8733 paddress (target_gdbarch (), lma + size));
8735 printf_filtered ("matched.\n");
8738 printf_filtered ("MIS-MATCHED!\n");
8742 do_cleanups (old_chain);
8745 warning (_("One or more sections of the target image does not match\n\
8746 the loaded file\n"));
8747 if (args && !matched)
8748 printf_filtered (_("No loaded section named '%s'.\n"), args);
8751 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8752 into remote target. The number of bytes written to the remote
8753 target is returned, or -1 for error. */
8755 static enum target_xfer_status
8756 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8757 const char *annex, const gdb_byte *writebuf,
8758 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
8759 struct packet_config *packet)
8763 struct remote_state *rs = get_remote_state ();
8764 int max_size = get_memory_write_packet_size ();
8766 if (packet->support == PACKET_DISABLE)
8767 return TARGET_XFER_E_IO;
8769 /* Insert header. */
8770 i = snprintf (rs->buf, max_size,
8771 "qXfer:%s:write:%s:%s:",
8772 object_name, annex ? annex : "",
8773 phex_nz (offset, sizeof offset));
8774 max_size -= (i + 1);
8776 /* Escape as much data as fits into rs->buf. */
8777 buf_len = remote_escape_output
8778 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8780 if (putpkt_binary (rs->buf, i + buf_len) < 0
8781 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8782 || packet_ok (rs->buf, packet) != PACKET_OK)
8783 return TARGET_XFER_E_IO;
8785 unpack_varlen_hex (rs->buf, &n);
8788 return TARGET_XFER_OK;
8791 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8792 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8793 number of bytes read is returned, or 0 for EOF, or -1 for error.
8794 The number of bytes read may be less than LEN without indicating an
8795 EOF. PACKET is checked and updated to indicate whether the remote
8796 target supports this object. */
8798 static enum target_xfer_status
8799 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8801 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8802 ULONGEST *xfered_len,
8803 struct packet_config *packet)
8805 struct remote_state *rs = get_remote_state ();
8806 LONGEST i, n, packet_len;
8808 if (packet->support == PACKET_DISABLE)
8809 return TARGET_XFER_E_IO;
8811 /* Check whether we've cached an end-of-object packet that matches
8813 if (rs->finished_object)
8815 if (strcmp (object_name, rs->finished_object) == 0
8816 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8817 && offset == rs->finished_offset)
8818 return TARGET_XFER_EOF;
8821 /* Otherwise, we're now reading something different. Discard
8823 xfree (rs->finished_object);
8824 xfree (rs->finished_annex);
8825 rs->finished_object = NULL;
8826 rs->finished_annex = NULL;
8829 /* Request only enough to fit in a single packet. The actual data
8830 may not, since we don't know how much of it will need to be escaped;
8831 the target is free to respond with slightly less data. We subtract
8832 five to account for the response type and the protocol frame. */
8833 n = min (get_remote_packet_size () - 5, len);
8834 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8835 object_name, annex ? annex : "",
8836 phex_nz (offset, sizeof offset),
8837 phex_nz (n, sizeof n));
8838 i = putpkt (rs->buf);
8840 return TARGET_XFER_E_IO;
8843 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8844 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8845 return TARGET_XFER_E_IO;
8847 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8848 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8850 /* 'm' means there is (or at least might be) more data after this
8851 batch. That does not make sense unless there's at least one byte
8852 of data in this reply. */
8853 if (rs->buf[0] == 'm' && packet_len == 1)
8854 error (_("Remote qXfer reply contained no data."));
8856 /* Got some data. */
8857 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8858 packet_len - 1, readbuf, n);
8860 /* 'l' is an EOF marker, possibly including a final block of data,
8861 or possibly empty. If we have the final block of a non-empty
8862 object, record this fact to bypass a subsequent partial read. */
8863 if (rs->buf[0] == 'l' && offset + i > 0)
8865 rs->finished_object = xstrdup (object_name);
8866 rs->finished_annex = xstrdup (annex ? annex : "");
8867 rs->finished_offset = offset + i;
8871 return TARGET_XFER_EOF;
8875 return TARGET_XFER_OK;
8879 static enum target_xfer_status
8880 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8881 const char *annex, gdb_byte *readbuf,
8882 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8883 ULONGEST *xfered_len)
8885 struct remote_state *rs;
8890 set_remote_traceframe ();
8891 set_general_thread (inferior_ptid);
8893 rs = get_remote_state ();
8895 /* Handle memory using the standard memory routines. */
8896 if (object == TARGET_OBJECT_MEMORY)
8898 /* If the remote target is connected but not running, we should
8899 pass this request down to a lower stratum (e.g. the executable
8901 if (!target_has_execution)
8902 return TARGET_XFER_EOF;
8904 if (writebuf != NULL)
8905 return remote_write_bytes (offset, writebuf, len, xfered_len);
8907 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
8910 /* Handle SPU memory using qxfer packets. */
8911 if (object == TARGET_OBJECT_SPU)
8914 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8915 xfered_len, &remote_protocol_packets
8916 [PACKET_qXfer_spu_read]);
8918 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8919 xfered_len, &remote_protocol_packets
8920 [PACKET_qXfer_spu_write]);
8923 /* Handle extra signal info using qxfer packets. */
8924 if (object == TARGET_OBJECT_SIGNAL_INFO)
8927 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8928 xfered_len, &remote_protocol_packets
8929 [PACKET_qXfer_siginfo_read]);
8931 return remote_write_qxfer (ops, "siginfo", annex,
8932 writebuf, offset, len, xfered_len,
8933 &remote_protocol_packets
8934 [PACKET_qXfer_siginfo_write]);
8937 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8940 return remote_read_qxfer (ops, "statictrace", annex,
8941 readbuf, offset, len, xfered_len,
8942 &remote_protocol_packets
8943 [PACKET_qXfer_statictrace_read]);
8945 return TARGET_XFER_E_IO;
8948 /* Only handle flash writes. */
8949 if (writebuf != NULL)
8955 case TARGET_OBJECT_FLASH:
8956 return remote_flash_write (ops, offset, len, xfered_len,
8960 return TARGET_XFER_E_IO;
8964 /* Map pre-existing objects onto letters. DO NOT do this for new
8965 objects!!! Instead specify new query packets. */
8968 case TARGET_OBJECT_AVR:
8972 case TARGET_OBJECT_AUXV:
8973 gdb_assert (annex == NULL);
8974 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8976 &remote_protocol_packets[PACKET_qXfer_auxv]);
8978 case TARGET_OBJECT_AVAILABLE_FEATURES:
8979 return remote_read_qxfer
8980 (ops, "features", annex, readbuf, offset, len, xfered_len,
8981 &remote_protocol_packets[PACKET_qXfer_features]);
8983 case TARGET_OBJECT_LIBRARIES:
8984 return remote_read_qxfer
8985 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
8986 &remote_protocol_packets[PACKET_qXfer_libraries]);
8988 case TARGET_OBJECT_LIBRARIES_SVR4:
8989 return remote_read_qxfer
8990 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
8991 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8993 case TARGET_OBJECT_MEMORY_MAP:
8994 gdb_assert (annex == NULL);
8995 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8997 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8999 case TARGET_OBJECT_OSDATA:
9000 /* Should only get here if we're connected. */
9001 gdb_assert (rs->remote_desc);
9002 return remote_read_qxfer
9003 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9004 &remote_protocol_packets[PACKET_qXfer_osdata]);
9006 case TARGET_OBJECT_THREADS:
9007 gdb_assert (annex == NULL);
9008 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9010 &remote_protocol_packets[PACKET_qXfer_threads]);
9012 case TARGET_OBJECT_TRACEFRAME_INFO:
9013 gdb_assert (annex == NULL);
9014 return remote_read_qxfer
9015 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9016 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9018 case TARGET_OBJECT_FDPIC:
9019 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9021 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9023 case TARGET_OBJECT_OPENVMS_UIB:
9024 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9026 &remote_protocol_packets[PACKET_qXfer_uib]);
9028 case TARGET_OBJECT_BTRACE:
9029 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9031 &remote_protocol_packets[PACKET_qXfer_btrace]);
9033 case TARGET_OBJECT_BTRACE_CONF:
9034 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9036 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9039 return TARGET_XFER_E_IO;
9042 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9043 large enough let the caller deal with it. */
9044 if (len < get_remote_packet_size ())
9045 return TARGET_XFER_E_IO;
9046 len = get_remote_packet_size ();
9048 /* Except for querying the minimum buffer size, target must be open. */
9049 if (!rs->remote_desc)
9050 error (_("remote query is only available after target open"));
9052 gdb_assert (annex != NULL);
9053 gdb_assert (readbuf != NULL);
9059 /* We used one buffer char for the remote protocol q command and
9060 another for the query type. As the remote protocol encapsulation
9061 uses 4 chars plus one extra in case we are debugging
9062 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9065 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9067 /* Bad caller may have sent forbidden characters. */
9068 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9073 gdb_assert (annex[i] == '\0');
9075 i = putpkt (rs->buf);
9077 return TARGET_XFER_E_IO;
9079 getpkt (&rs->buf, &rs->buf_size, 0);
9080 strcpy ((char *) readbuf, rs->buf);
9082 *xfered_len = strlen ((char *) readbuf);
9083 return TARGET_XFER_OK;
9087 remote_search_memory (struct target_ops* ops,
9088 CORE_ADDR start_addr, ULONGEST search_space_len,
9089 const gdb_byte *pattern, ULONGEST pattern_len,
9090 CORE_ADDR *found_addrp)
9092 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9093 struct remote_state *rs = get_remote_state ();
9094 int max_size = get_memory_write_packet_size ();
9095 struct packet_config *packet =
9096 &remote_protocol_packets[PACKET_qSearch_memory];
9097 /* Number of packet bytes used to encode the pattern;
9098 this could be more than PATTERN_LEN due to escape characters. */
9099 int escaped_pattern_len;
9100 /* Amount of pattern that was encodable in the packet. */
9101 int used_pattern_len;
9104 ULONGEST found_addr;
9106 /* Don't go to the target if we don't have to.
9107 This is done before checking packet->support to avoid the possibility that
9108 a success for this edge case means the facility works in general. */
9109 if (pattern_len > search_space_len)
9111 if (pattern_len == 0)
9113 *found_addrp = start_addr;
9117 /* If we already know the packet isn't supported, fall back to the simple
9118 way of searching memory. */
9120 if (packet_config_support (packet) == PACKET_DISABLE)
9122 /* Target doesn't provided special support, fall back and use the
9123 standard support (copy memory and do the search here). */
9124 return simple_search_memory (ops, start_addr, search_space_len,
9125 pattern, pattern_len, found_addrp);
9128 /* Make sure the remote is pointing at the right process. */
9129 set_general_process ();
9131 /* Insert header. */
9132 i = snprintf (rs->buf, max_size,
9133 "qSearch:memory:%s;%s;",
9134 phex_nz (start_addr, addr_size),
9135 phex_nz (search_space_len, sizeof (search_space_len)));
9136 max_size -= (i + 1);
9138 /* Escape as much data as fits into rs->buf. */
9139 escaped_pattern_len =
9140 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9141 &used_pattern_len, max_size);
9143 /* Bail if the pattern is too large. */
9144 if (used_pattern_len != pattern_len)
9145 error (_("Pattern is too large to transmit to remote target."));
9147 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9148 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9149 || packet_ok (rs->buf, packet) != PACKET_OK)
9151 /* The request may not have worked because the command is not
9152 supported. If so, fall back to the simple way. */
9153 if (packet->support == PACKET_DISABLE)
9155 return simple_search_memory (ops, start_addr, search_space_len,
9156 pattern, pattern_len, found_addrp);
9161 if (rs->buf[0] == '0')
9163 else if (rs->buf[0] == '1')
9166 if (rs->buf[1] != ',')
9167 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9168 unpack_varlen_hex (rs->buf + 2, &found_addr);
9169 *found_addrp = found_addr;
9172 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9178 remote_rcmd (struct target_ops *self, const char *command,
9179 struct ui_file *outbuf)
9181 struct remote_state *rs = get_remote_state ();
9184 if (!rs->remote_desc)
9185 error (_("remote rcmd is only available after target open"));
9187 /* Send a NULL command across as an empty command. */
9188 if (command == NULL)
9191 /* The query prefix. */
9192 strcpy (rs->buf, "qRcmd,");
9193 p = strchr (rs->buf, '\0');
9195 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9196 > get_remote_packet_size ())
9197 error (_("\"monitor\" command ``%s'' is too long."), command);
9199 /* Encode the actual command. */
9200 bin2hex ((const gdb_byte *) command, p, strlen (command));
9202 if (putpkt (rs->buf) < 0)
9203 error (_("Communication problem with target."));
9205 /* get/display the response */
9210 /* XXX - see also remote_get_noisy_reply(). */
9211 QUIT; /* Allow user to bail out with ^C. */
9213 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9215 /* Timeout. Continue to (try to) read responses.
9216 This is better than stopping with an error, assuming the stub
9217 is still executing the (long) monitor command.
9218 If needed, the user can interrupt gdb using C-c, obtaining
9219 an effect similar to stop on timeout. */
9224 error (_("Target does not support this command."));
9225 if (buf[0] == 'O' && buf[1] != 'K')
9227 remote_console_output (buf + 1); /* 'O' message from stub. */
9230 if (strcmp (buf, "OK") == 0)
9232 if (strlen (buf) == 3 && buf[0] == 'E'
9233 && isdigit (buf[1]) && isdigit (buf[2]))
9235 error (_("Protocol error with Rcmd"));
9237 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9239 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9241 fputc_unfiltered (c, outbuf);
9247 static VEC(mem_region_s) *
9248 remote_memory_map (struct target_ops *ops)
9250 VEC(mem_region_s) *result = NULL;
9251 char *text = target_read_stralloc (¤t_target,
9252 TARGET_OBJECT_MEMORY_MAP, NULL);
9256 struct cleanup *back_to = make_cleanup (xfree, text);
9258 result = parse_memory_map (text);
9259 do_cleanups (back_to);
9266 packet_command (char *args, int from_tty)
9268 struct remote_state *rs = get_remote_state ();
9270 if (!rs->remote_desc)
9271 error (_("command can only be used with remote target"));
9274 error (_("remote-packet command requires packet text as argument"));
9276 puts_filtered ("sending: ");
9277 print_packet (args);
9278 puts_filtered ("\n");
9281 getpkt (&rs->buf, &rs->buf_size, 0);
9282 puts_filtered ("received: ");
9283 print_packet (rs->buf);
9284 puts_filtered ("\n");
9288 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9290 static void display_thread_info (struct gdb_ext_thread_info *info);
9292 static void threadset_test_cmd (char *cmd, int tty);
9294 static void threadalive_test (char *cmd, int tty);
9296 static void threadlist_test_cmd (char *cmd, int tty);
9298 int get_and_display_threadinfo (threadref *ref);
9300 static void threadinfo_test_cmd (char *cmd, int tty);
9302 static int thread_display_step (threadref *ref, void *context);
9304 static void threadlist_update_test_cmd (char *cmd, int tty);
9306 static void init_remote_threadtests (void);
9308 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9311 threadset_test_cmd (char *cmd, int tty)
9313 int sample_thread = SAMPLE_THREAD;
9315 printf_filtered (_("Remote threadset test\n"));
9316 set_general_thread (sample_thread);
9321 threadalive_test (char *cmd, int tty)
9323 int sample_thread = SAMPLE_THREAD;
9324 int pid = ptid_get_pid (inferior_ptid);
9325 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9327 if (remote_thread_alive (ptid))
9328 printf_filtered ("PASS: Thread alive test\n");
9330 printf_filtered ("FAIL: Thread alive test\n");
9333 void output_threadid (char *title, threadref *ref);
9336 output_threadid (char *title, threadref *ref)
9340 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9342 printf_filtered ("%s %s\n", title, (&hexid[0]));
9346 threadlist_test_cmd (char *cmd, int tty)
9349 threadref nextthread;
9350 int done, result_count;
9351 threadref threadlist[3];
9353 printf_filtered ("Remote Threadlist test\n");
9354 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9355 &result_count, &threadlist[0]))
9356 printf_filtered ("FAIL: threadlist test\n");
9359 threadref *scan = threadlist;
9360 threadref *limit = scan + result_count;
9362 while (scan < limit)
9363 output_threadid (" thread ", scan++);
9368 display_thread_info (struct gdb_ext_thread_info *info)
9370 output_threadid ("Threadid: ", &info->threadid);
9371 printf_filtered ("Name: %s\n ", info->shortname);
9372 printf_filtered ("State: %s\n", info->display);
9373 printf_filtered ("other: %s\n\n", info->more_display);
9377 get_and_display_threadinfo (threadref *ref)
9381 struct gdb_ext_thread_info threadinfo;
9383 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9384 | TAG_MOREDISPLAY | TAG_DISPLAY;
9385 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9386 display_thread_info (&threadinfo);
9391 threadinfo_test_cmd (char *cmd, int tty)
9393 int athread = SAMPLE_THREAD;
9397 int_to_threadref (&thread, athread);
9398 printf_filtered ("Remote Threadinfo test\n");
9399 if (!get_and_display_threadinfo (&thread))
9400 printf_filtered ("FAIL cannot get thread info\n");
9404 thread_display_step (threadref *ref, void *context)
9406 /* output_threadid(" threadstep ",ref); *//* simple test */
9407 return get_and_display_threadinfo (ref);
9411 threadlist_update_test_cmd (char *cmd, int tty)
9413 printf_filtered ("Remote Threadlist update test\n");
9414 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9418 init_remote_threadtests (void)
9420 add_com ("tlist", class_obscure, threadlist_test_cmd,
9421 _("Fetch and print the remote list of "
9422 "thread identifiers, one pkt only"));
9423 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9424 _("Fetch and display info about one thread"));
9425 add_com ("tset", class_obscure, threadset_test_cmd,
9426 _("Test setting to a different thread"));
9427 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9428 _("Iterate through updating all remote thread info"));
9429 add_com ("talive", class_obscure, threadalive_test,
9430 _(" Remote thread alive test "));
9435 /* Convert a thread ID to a string. Returns the string in a static
9439 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9441 static char buf[64];
9442 struct remote_state *rs = get_remote_state ();
9444 if (ptid_equal (ptid, null_ptid))
9445 return normal_pid_to_str (ptid);
9446 else if (ptid_is_pid (ptid))
9448 /* Printing an inferior target id. */
9450 /* When multi-process extensions are off, there's no way in the
9451 remote protocol to know the remote process id, if there's any
9452 at all. There's one exception --- when we're connected with
9453 target extended-remote, and we manually attached to a process
9454 with "attach PID". We don't record anywhere a flag that
9455 allows us to distinguish that case from the case of
9456 connecting with extended-remote and the stub already being
9457 attached to a process, and reporting yes to qAttached, hence
9458 no smart special casing here. */
9459 if (!remote_multi_process_p (rs))
9461 xsnprintf (buf, sizeof buf, "Remote target");
9465 return normal_pid_to_str (ptid);
9469 if (ptid_equal (magic_null_ptid, ptid))
9470 xsnprintf (buf, sizeof buf, "Thread <main>");
9471 else if (rs->extended && remote_multi_process_p (rs))
9472 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9473 ptid_get_pid (ptid), ptid_get_lwp (ptid));
9475 xsnprintf (buf, sizeof buf, "Thread %ld",
9476 ptid_get_lwp (ptid));
9481 /* Get the address of the thread local variable in OBJFILE which is
9482 stored at OFFSET within the thread local storage for thread PTID. */
9485 remote_get_thread_local_address (struct target_ops *ops,
9486 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9488 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
9490 struct remote_state *rs = get_remote_state ();
9492 char *endp = rs->buf + get_remote_packet_size ();
9493 enum packet_result result;
9495 strcpy (p, "qGetTLSAddr:");
9497 p = write_ptid (p, endp, ptid);
9499 p += hexnumstr (p, offset);
9501 p += hexnumstr (p, lm);
9505 getpkt (&rs->buf, &rs->buf_size, 0);
9506 result = packet_ok (rs->buf,
9507 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9508 if (result == PACKET_OK)
9512 unpack_varlen_hex (rs->buf, &result);
9515 else if (result == PACKET_UNKNOWN)
9516 throw_error (TLS_GENERIC_ERROR,
9517 _("Remote target doesn't support qGetTLSAddr packet"));
9519 throw_error (TLS_GENERIC_ERROR,
9520 _("Remote target failed to process qGetTLSAddr request"));
9523 throw_error (TLS_GENERIC_ERROR,
9524 _("TLS not supported or disabled on this target"));
9529 /* Provide thread local base, i.e. Thread Information Block address.
9530 Returns 1 if ptid is found and thread_local_base is non zero. */
9533 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
9535 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
9537 struct remote_state *rs = get_remote_state ();
9539 char *endp = rs->buf + get_remote_packet_size ();
9540 enum packet_result result;
9542 strcpy (p, "qGetTIBAddr:");
9544 p = write_ptid (p, endp, ptid);
9548 getpkt (&rs->buf, &rs->buf_size, 0);
9549 result = packet_ok (rs->buf,
9550 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9551 if (result == PACKET_OK)
9555 unpack_varlen_hex (rs->buf, &result);
9557 *addr = (CORE_ADDR) result;
9560 else if (result == PACKET_UNKNOWN)
9561 error (_("Remote target doesn't support qGetTIBAddr packet"));
9563 error (_("Remote target failed to process qGetTIBAddr request"));
9566 error (_("qGetTIBAddr not supported or disabled on this target"));
9571 /* Support for inferring a target description based on the current
9572 architecture and the size of a 'g' packet. While the 'g' packet
9573 can have any size (since optional registers can be left off the
9574 end), some sizes are easily recognizable given knowledge of the
9575 approximate architecture. */
9577 struct remote_g_packet_guess
9580 const struct target_desc *tdesc;
9582 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9583 DEF_VEC_O(remote_g_packet_guess_s);
9585 struct remote_g_packet_data
9587 VEC(remote_g_packet_guess_s) *guesses;
9590 static struct gdbarch_data *remote_g_packet_data_handle;
9593 remote_g_packet_data_init (struct obstack *obstack)
9595 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9599 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9600 const struct target_desc *tdesc)
9602 struct remote_g_packet_data *data
9603 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9604 struct remote_g_packet_guess new_guess, *guess;
9607 gdb_assert (tdesc != NULL);
9610 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9612 if (guess->bytes == bytes)
9613 internal_error (__FILE__, __LINE__,
9614 _("Duplicate g packet description added for size %d"),
9617 new_guess.bytes = bytes;
9618 new_guess.tdesc = tdesc;
9619 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9622 /* Return 1 if remote_read_description would do anything on this target
9623 and architecture, 0 otherwise. */
9626 remote_read_description_p (struct target_ops *target)
9628 struct remote_g_packet_data *data
9629 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9631 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9637 static const struct target_desc *
9638 remote_read_description (struct target_ops *target)
9640 struct remote_g_packet_data *data
9641 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9643 /* Do not try this during initial connection, when we do not know
9644 whether there is a running but stopped thread. */
9645 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9646 return target->beneath->to_read_description (target->beneath);
9648 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9650 struct remote_g_packet_guess *guess;
9652 int bytes = send_g_packet ();
9655 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9657 if (guess->bytes == bytes)
9658 return guess->tdesc;
9660 /* We discard the g packet. A minor optimization would be to
9661 hold on to it, and fill the register cache once we have selected
9662 an architecture, but it's too tricky to do safely. */
9665 return target->beneath->to_read_description (target->beneath);
9668 /* Remote file transfer support. This is host-initiated I/O, not
9669 target-initiated; for target-initiated, see remote-fileio.c. */
9671 /* If *LEFT is at least the length of STRING, copy STRING to
9672 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9673 decrease *LEFT. Otherwise raise an error. */
9676 remote_buffer_add_string (char **buffer, int *left, char *string)
9678 int len = strlen (string);
9681 error (_("Packet too long for target."));
9683 memcpy (*buffer, string, len);
9687 /* NUL-terminate the buffer as a convenience, if there is
9693 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9694 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9695 decrease *LEFT. Otherwise raise an error. */
9698 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9701 if (2 * len > *left)
9702 error (_("Packet too long for target."));
9704 bin2hex (bytes, *buffer, len);
9708 /* NUL-terminate the buffer as a convenience, if there is
9714 /* If *LEFT is large enough, convert VALUE to hex and add it to
9715 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9716 decrease *LEFT. Otherwise raise an error. */
9719 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9721 int len = hexnumlen (value);
9724 error (_("Packet too long for target."));
9726 hexnumstr (*buffer, value);
9730 /* NUL-terminate the buffer as a convenience, if there is
9736 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9737 value, *REMOTE_ERRNO to the remote error number or zero if none
9738 was included, and *ATTACHMENT to point to the start of the annex
9739 if any. The length of the packet isn't needed here; there may
9740 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9742 Return 0 if the packet could be parsed, -1 if it could not. If
9743 -1 is returned, the other variables may not be initialized. */
9746 remote_hostio_parse_result (char *buffer, int *retcode,
9747 int *remote_errno, char **attachment)
9754 if (buffer[0] != 'F')
9758 *retcode = strtol (&buffer[1], &p, 16);
9759 if (errno != 0 || p == &buffer[1])
9762 /* Check for ",errno". */
9766 *remote_errno = strtol (p + 1, &p2, 16);
9767 if (errno != 0 || p + 1 == p2)
9772 /* Check for ";attachment". If there is no attachment, the
9773 packet should end here. */
9776 *attachment = p + 1;
9779 else if (*p == '\0')
9785 /* Send a prepared I/O packet to the target and read its response.
9786 The prepared packet is in the global RS->BUF before this function
9787 is called, and the answer is there when we return.
9789 COMMAND_BYTES is the length of the request to send, which may include
9790 binary data. WHICH_PACKET is the packet configuration to check
9791 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9792 is set to the error number and -1 is returned. Otherwise the value
9793 returned by the function is returned.
9795 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9796 attachment is expected; an error will be reported if there's a
9797 mismatch. If one is found, *ATTACHMENT will be set to point into
9798 the packet buffer and *ATTACHMENT_LEN will be set to the
9799 attachment's length. */
9802 remote_hostio_send_command (int command_bytes, int which_packet,
9803 int *remote_errno, char **attachment,
9804 int *attachment_len)
9806 struct remote_state *rs = get_remote_state ();
9807 int ret, bytes_read;
9808 char *attachment_tmp;
9810 if (!rs->remote_desc
9811 || packet_support (which_packet) == PACKET_DISABLE)
9813 *remote_errno = FILEIO_ENOSYS;
9817 putpkt_binary (rs->buf, command_bytes);
9818 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9820 /* If it timed out, something is wrong. Don't try to parse the
9824 *remote_errno = FILEIO_EINVAL;
9828 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9831 *remote_errno = FILEIO_EINVAL;
9833 case PACKET_UNKNOWN:
9834 *remote_errno = FILEIO_ENOSYS;
9840 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9843 *remote_errno = FILEIO_EINVAL;
9847 /* Make sure we saw an attachment if and only if we expected one. */
9848 if ((attachment_tmp == NULL && attachment != NULL)
9849 || (attachment_tmp != NULL && attachment == NULL))
9851 *remote_errno = FILEIO_EINVAL;
9855 /* If an attachment was found, it must point into the packet buffer;
9856 work out how many bytes there were. */
9857 if (attachment_tmp != NULL)
9859 *attachment = attachment_tmp;
9860 *attachment_len = bytes_read - (*attachment - rs->buf);
9866 /* Return nonzero if the filesystem accessed by the target_fileio_*
9867 methods is the local filesystem, zero otherwise. */
9870 remote_filesystem_is_local (struct target_ops *self)
9875 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9876 remote file descriptor, or -1 if an error occurs (and set
9880 remote_hostio_open (struct target_ops *self,
9881 const char *filename, int flags, int mode,
9884 struct remote_state *rs = get_remote_state ();
9886 int left = get_remote_packet_size () - 1;
9888 remote_buffer_add_string (&p, &left, "vFile:open:");
9890 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9892 remote_buffer_add_string (&p, &left, ",");
9894 remote_buffer_add_int (&p, &left, flags);
9895 remote_buffer_add_string (&p, &left, ",");
9897 remote_buffer_add_int (&p, &left, mode);
9899 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9900 remote_errno, NULL, NULL);
9903 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9904 Return the number of bytes written, or -1 if an error occurs (and
9905 set *REMOTE_ERRNO). */
9908 remote_hostio_pwrite (struct target_ops *self,
9909 int fd, const gdb_byte *write_buf, int len,
9910 ULONGEST offset, int *remote_errno)
9912 struct remote_state *rs = get_remote_state ();
9914 int left = get_remote_packet_size ();
9917 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9919 remote_buffer_add_int (&p, &left, fd);
9920 remote_buffer_add_string (&p, &left, ",");
9922 remote_buffer_add_int (&p, &left, offset);
9923 remote_buffer_add_string (&p, &left, ",");
9925 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9926 get_remote_packet_size () - (p - rs->buf));
9928 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9929 remote_errno, NULL, NULL);
9932 /* Read up to LEN bytes FD on the remote target into READ_BUF
9933 Return the number of bytes read, or -1 if an error occurs (and
9934 set *REMOTE_ERRNO). */
9937 remote_hostio_pread (struct target_ops *self,
9938 int fd, gdb_byte *read_buf, int len,
9939 ULONGEST offset, int *remote_errno)
9941 struct remote_state *rs = get_remote_state ();
9944 int left = get_remote_packet_size ();
9945 int ret, attachment_len;
9948 remote_buffer_add_string (&p, &left, "vFile:pread:");
9950 remote_buffer_add_int (&p, &left, fd);
9951 remote_buffer_add_string (&p, &left, ",");
9953 remote_buffer_add_int (&p, &left, len);
9954 remote_buffer_add_string (&p, &left, ",");
9956 remote_buffer_add_int (&p, &left, offset);
9958 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9959 remote_errno, &attachment,
9965 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9967 if (read_len != ret)
9968 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9973 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9974 (and set *REMOTE_ERRNO). */
9977 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
9979 struct remote_state *rs = get_remote_state ();
9981 int left = get_remote_packet_size () - 1;
9983 remote_buffer_add_string (&p, &left, "vFile:close:");
9985 remote_buffer_add_int (&p, &left, fd);
9987 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9988 remote_errno, NULL, NULL);
9991 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9992 occurs (and set *REMOTE_ERRNO). */
9995 remote_hostio_unlink (struct target_ops *self,
9996 const char *filename, int *remote_errno)
9998 struct remote_state *rs = get_remote_state ();
10000 int left = get_remote_packet_size () - 1;
10002 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10004 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10005 strlen (filename));
10007 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10008 remote_errno, NULL, NULL);
10011 /* Read value of symbolic link FILENAME on the remote target. Return
10012 a null-terminated string allocated via xmalloc, or NULL if an error
10013 occurs (and set *REMOTE_ERRNO). */
10016 remote_hostio_readlink (struct target_ops *self,
10017 const char *filename, int *remote_errno)
10019 struct remote_state *rs = get_remote_state ();
10022 int left = get_remote_packet_size ();
10023 int len, attachment_len;
10027 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10029 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10030 strlen (filename));
10032 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10033 remote_errno, &attachment,
10039 ret = xmalloc (len + 1);
10041 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10042 (gdb_byte *) ret, len);
10043 if (read_len != len)
10044 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10050 /* Read information about the open file FD on the remote target
10051 into ST. Return 0 on success, or -1 if an error occurs (and
10052 set *REMOTE_ERRNO). */
10055 remote_hostio_fstat (struct target_ops *self,
10056 int fd, struct stat *st,
10059 struct remote_state *rs = get_remote_state ();
10061 int left = get_remote_packet_size ();
10062 int attachment_len, ret;
10064 struct fio_stat fst;
10067 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10069 remote_buffer_add_int (&p, &left, fd);
10071 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10072 remote_errno, &attachment,
10076 if (*remote_errno != FILEIO_ENOSYS)
10079 /* Strictly we should return -1, ENOSYS here, but when
10080 "set sysroot remote:" was implemented in August 2008
10081 BFD's need for a stat function was sidestepped with
10082 this hack. This was not remedied until March 2015
10083 so we retain the previous behavior to avoid breaking
10086 Note that the memset is a March 2015 addition; older
10087 GDBs set st_size *and nothing else* so the structure
10088 would have garbage in all other fields. This might
10089 break something but retaining the previous behavior
10090 here would be just too wrong. */
10092 memset (st, 0, sizeof (struct stat));
10093 st->st_size = INT_MAX;
10097 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10098 (gdb_byte *) &fst, sizeof (fst));
10100 if (read_len != ret)
10101 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10103 if (read_len != sizeof (fst))
10104 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10105 read_len, (int) sizeof (fst));
10107 remote_fileio_to_host_stat (&fst, st);
10113 remote_fileio_errno_to_host (int errnum)
10119 case FILEIO_ENOENT:
10127 case FILEIO_EACCES:
10129 case FILEIO_EFAULT:
10133 case FILEIO_EEXIST:
10135 case FILEIO_ENODEV:
10137 case FILEIO_ENOTDIR:
10139 case FILEIO_EISDIR:
10141 case FILEIO_EINVAL:
10143 case FILEIO_ENFILE:
10145 case FILEIO_EMFILE:
10149 case FILEIO_ENOSPC:
10151 case FILEIO_ESPIPE:
10155 case FILEIO_ENOSYS:
10157 case FILEIO_ENAMETOOLONG:
10158 return ENAMETOOLONG;
10164 remote_hostio_error (int errnum)
10166 int host_error = remote_fileio_errno_to_host (errnum);
10168 if (host_error == -1)
10169 error (_("Unknown remote I/O error %d"), errnum);
10171 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10175 remote_hostio_close_cleanup (void *opaque)
10177 int fd = *(int *) opaque;
10180 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10184 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10186 struct cleanup *back_to, *close_cleanup;
10187 int retcode, fd, remote_errno, bytes, io_size;
10190 int bytes_in_buffer;
10193 struct remote_state *rs = get_remote_state ();
10195 if (!rs->remote_desc)
10196 error (_("command can only be used with remote target"));
10198 file = gdb_fopen_cloexec (local_file, "rb");
10200 perror_with_name (local_file);
10201 back_to = make_cleanup_fclose (file);
10203 fd = remote_hostio_open (find_target_at (process_stratum),
10204 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10206 0700, &remote_errno);
10208 remote_hostio_error (remote_errno);
10210 /* Send up to this many bytes at once. They won't all fit in the
10211 remote packet limit, so we'll transfer slightly fewer. */
10212 io_size = get_remote_packet_size ();
10213 buffer = xmalloc (io_size);
10214 make_cleanup (xfree, buffer);
10216 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10218 bytes_in_buffer = 0;
10221 while (bytes_in_buffer || !saw_eof)
10225 bytes = fread (buffer + bytes_in_buffer, 1,
10226 io_size - bytes_in_buffer,
10231 error (_("Error reading %s."), local_file);
10234 /* EOF. Unless there is something still in the
10235 buffer from the last iteration, we are done. */
10237 if (bytes_in_buffer == 0)
10245 bytes += bytes_in_buffer;
10246 bytes_in_buffer = 0;
10248 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10250 offset, &remote_errno);
10253 remote_hostio_error (remote_errno);
10254 else if (retcode == 0)
10255 error (_("Remote write of %d bytes returned 0!"), bytes);
10256 else if (retcode < bytes)
10258 /* Short write. Save the rest of the read data for the next
10260 bytes_in_buffer = bytes - retcode;
10261 memmove (buffer, buffer + retcode, bytes_in_buffer);
10267 discard_cleanups (close_cleanup);
10268 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10269 remote_hostio_error (remote_errno);
10272 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10273 do_cleanups (back_to);
10277 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10279 struct cleanup *back_to, *close_cleanup;
10280 int fd, remote_errno, bytes, io_size;
10284 struct remote_state *rs = get_remote_state ();
10286 if (!rs->remote_desc)
10287 error (_("command can only be used with remote target"));
10289 fd = remote_hostio_open (find_target_at (process_stratum),
10290 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10292 remote_hostio_error (remote_errno);
10294 file = gdb_fopen_cloexec (local_file, "wb");
10296 perror_with_name (local_file);
10297 back_to = make_cleanup_fclose (file);
10299 /* Send up to this many bytes at once. They won't all fit in the
10300 remote packet limit, so we'll transfer slightly fewer. */
10301 io_size = get_remote_packet_size ();
10302 buffer = xmalloc (io_size);
10303 make_cleanup (xfree, buffer);
10305 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10310 bytes = remote_hostio_pread (find_target_at (process_stratum),
10311 fd, buffer, io_size, offset, &remote_errno);
10313 /* Success, but no bytes, means end-of-file. */
10316 remote_hostio_error (remote_errno);
10320 bytes = fwrite (buffer, 1, bytes, file);
10322 perror_with_name (local_file);
10325 discard_cleanups (close_cleanup);
10326 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10327 remote_hostio_error (remote_errno);
10330 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10331 do_cleanups (back_to);
10335 remote_file_delete (const char *remote_file, int from_tty)
10337 int retcode, remote_errno;
10338 struct remote_state *rs = get_remote_state ();
10340 if (!rs->remote_desc)
10341 error (_("command can only be used with remote target"));
10343 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10344 remote_file, &remote_errno);
10346 remote_hostio_error (remote_errno);
10349 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10353 remote_put_command (char *args, int from_tty)
10355 struct cleanup *back_to;
10359 error_no_arg (_("file to put"));
10361 argv = gdb_buildargv (args);
10362 back_to = make_cleanup_freeargv (argv);
10363 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10364 error (_("Invalid parameters to remote put"));
10366 remote_file_put (argv[0], argv[1], from_tty);
10368 do_cleanups (back_to);
10372 remote_get_command (char *args, int from_tty)
10374 struct cleanup *back_to;
10378 error_no_arg (_("file to get"));
10380 argv = gdb_buildargv (args);
10381 back_to = make_cleanup_freeargv (argv);
10382 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10383 error (_("Invalid parameters to remote get"));
10385 remote_file_get (argv[0], argv[1], from_tty);
10387 do_cleanups (back_to);
10391 remote_delete_command (char *args, int from_tty)
10393 struct cleanup *back_to;
10397 error_no_arg (_("file to delete"));
10399 argv = gdb_buildargv (args);
10400 back_to = make_cleanup_freeargv (argv);
10401 if (argv[0] == NULL || argv[1] != NULL)
10402 error (_("Invalid parameters to remote delete"));
10404 remote_file_delete (argv[0], from_tty);
10406 do_cleanups (back_to);
10410 remote_command (char *args, int from_tty)
10412 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
10416 remote_can_execute_reverse (struct target_ops *self)
10418 if (packet_support (PACKET_bs) == PACKET_ENABLE
10419 || packet_support (PACKET_bc) == PACKET_ENABLE)
10426 remote_supports_non_stop (struct target_ops *self)
10432 remote_supports_disable_randomization (struct target_ops *self)
10434 /* Only supported in extended mode. */
10439 remote_supports_multi_process (struct target_ops *self)
10441 struct remote_state *rs = get_remote_state ();
10443 /* Only extended-remote handles being attached to multiple
10444 processes, even though plain remote can use the multi-process
10445 thread id extensions, so that GDB knows the target process's
10447 return rs->extended && remote_multi_process_p (rs);
10451 remote_supports_cond_tracepoints (void)
10453 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
10457 remote_supports_cond_breakpoints (struct target_ops *self)
10459 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
10463 remote_supports_fast_tracepoints (void)
10465 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
10469 remote_supports_static_tracepoints (void)
10471 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
10475 remote_supports_install_in_trace (void)
10477 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
10481 remote_supports_enable_disable_tracepoint (struct target_ops *self)
10483 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10488 remote_supports_string_tracing (struct target_ops *self)
10490 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
10494 remote_can_run_breakpoint_commands (struct target_ops *self)
10496 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
10500 remote_trace_init (struct target_ops *self)
10503 remote_get_noisy_reply (&target_buf, &target_buf_size);
10504 if (strcmp (target_buf, "OK") != 0)
10505 error (_("Target does not support this command."));
10508 static void free_actions_list (char **actions_list);
10509 static void free_actions_list_cleanup_wrapper (void *);
10511 free_actions_list_cleanup_wrapper (void *al)
10513 free_actions_list (al);
10517 free_actions_list (char **actions_list)
10521 if (actions_list == 0)
10524 for (ndx = 0; actions_list[ndx]; ndx++)
10525 xfree (actions_list[ndx]);
10527 xfree (actions_list);
10530 /* Recursive routine to walk through command list including loops, and
10531 download packets for each command. */
10534 remote_download_command_source (int num, ULONGEST addr,
10535 struct command_line *cmds)
10537 struct remote_state *rs = get_remote_state ();
10538 struct command_line *cmd;
10540 for (cmd = cmds; cmd; cmd = cmd->next)
10542 QUIT; /* Allow user to bail out with ^C. */
10543 strcpy (rs->buf, "QTDPsrc:");
10544 encode_source_string (num, addr, "cmd", cmd->line,
10545 rs->buf + strlen (rs->buf),
10546 rs->buf_size - strlen (rs->buf));
10548 remote_get_noisy_reply (&target_buf, &target_buf_size);
10549 if (strcmp (target_buf, "OK"))
10550 warning (_("Target does not support source download."));
10552 if (cmd->control_type == while_control
10553 || cmd->control_type == while_stepping_control)
10555 remote_download_command_source (num, addr, *cmd->body_list);
10557 QUIT; /* Allow user to bail out with ^C. */
10558 strcpy (rs->buf, "QTDPsrc:");
10559 encode_source_string (num, addr, "cmd", "end",
10560 rs->buf + strlen (rs->buf),
10561 rs->buf_size - strlen (rs->buf));
10563 remote_get_noisy_reply (&target_buf, &target_buf_size);
10564 if (strcmp (target_buf, "OK"))
10565 warning (_("Target does not support source download."));
10571 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
10573 #define BUF_SIZE 2048
10577 char buf[BUF_SIZE];
10578 char **tdp_actions;
10579 char **stepping_actions;
10581 struct cleanup *old_chain = NULL;
10582 struct agent_expr *aexpr;
10583 struct cleanup *aexpr_chain = NULL;
10585 struct breakpoint *b = loc->owner;
10586 struct tracepoint *t = (struct tracepoint *) b;
10588 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10589 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10591 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10594 tpaddr = loc->address;
10595 sprintf_vma (addrbuf, tpaddr);
10596 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10597 addrbuf, /* address */
10598 (b->enable_state == bp_enabled ? 'E' : 'D'),
10599 t->step_count, t->pass_count);
10600 /* Fast tracepoints are mostly handled by the target, but we can
10601 tell the target how big of an instruction block should be moved
10603 if (b->type == bp_fast_tracepoint)
10605 /* Only test for support at download time; we may not know
10606 target capabilities at definition time. */
10607 if (remote_supports_fast_tracepoints ())
10611 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10612 tpaddr, &isize, NULL))
10613 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10616 /* If it passed validation at definition but fails now,
10617 something is very wrong. */
10618 internal_error (__FILE__, __LINE__,
10619 _("Fast tracepoint not "
10620 "valid during download"));
10623 /* Fast tracepoints are functionally identical to regular
10624 tracepoints, so don't take lack of support as a reason to
10625 give up on the trace run. */
10626 warning (_("Target does not support fast tracepoints, "
10627 "downloading %d as regular tracepoint"), b->number);
10629 else if (b->type == bp_static_tracepoint)
10631 /* Only test for support at download time; we may not know
10632 target capabilities at definition time. */
10633 if (remote_supports_static_tracepoints ())
10635 struct static_tracepoint_marker marker;
10637 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10638 strcat (buf, ":S");
10640 error (_("Static tracepoint not valid during download"));
10643 /* Fast tracepoints are functionally identical to regular
10644 tracepoints, so don't take lack of support as a reason
10645 to give up on the trace run. */
10646 error (_("Target does not support static tracepoints"));
10648 /* If the tracepoint has a conditional, make it into an agent
10649 expression and append to the definition. */
10652 /* Only test support at download time, we may not know target
10653 capabilities at definition time. */
10654 if (remote_supports_cond_tracepoints ())
10656 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10657 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10658 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10660 pkt = buf + strlen (buf);
10661 for (ndx = 0; ndx < aexpr->len; ++ndx)
10662 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10664 do_cleanups (aexpr_chain);
10667 warning (_("Target does not support conditional tracepoints, "
10668 "ignoring tp %d cond"), b->number);
10671 if (b->commands || *default_collect)
10674 remote_get_noisy_reply (&target_buf, &target_buf_size);
10675 if (strcmp (target_buf, "OK"))
10676 error (_("Target does not support tracepoints."));
10678 /* do_single_steps (t); */
10681 for (ndx = 0; tdp_actions[ndx]; ndx++)
10683 QUIT; /* Allow user to bail out with ^C. */
10684 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10685 b->number, addrbuf, /* address */
10687 ((tdp_actions[ndx + 1] || stepping_actions)
10690 remote_get_noisy_reply (&target_buf,
10692 if (strcmp (target_buf, "OK"))
10693 error (_("Error on target while setting tracepoints."));
10696 if (stepping_actions)
10698 for (ndx = 0; stepping_actions[ndx]; ndx++)
10700 QUIT; /* Allow user to bail out with ^C. */
10701 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10702 b->number, addrbuf, /* address */
10703 ((ndx == 0) ? "S" : ""),
10704 stepping_actions[ndx],
10705 (stepping_actions[ndx + 1] ? "-" : ""));
10707 remote_get_noisy_reply (&target_buf,
10709 if (strcmp (target_buf, "OK"))
10710 error (_("Error on target while setting tracepoints."));
10714 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
10716 if (b->addr_string)
10718 strcpy (buf, "QTDPsrc:");
10719 encode_source_string (b->number, loc->address,
10720 "at", b->addr_string, buf + strlen (buf),
10721 2048 - strlen (buf));
10724 remote_get_noisy_reply (&target_buf, &target_buf_size);
10725 if (strcmp (target_buf, "OK"))
10726 warning (_("Target does not support source download."));
10728 if (b->cond_string)
10730 strcpy (buf, "QTDPsrc:");
10731 encode_source_string (b->number, loc->address,
10732 "cond", b->cond_string, buf + strlen (buf),
10733 2048 - strlen (buf));
10735 remote_get_noisy_reply (&target_buf, &target_buf_size);
10736 if (strcmp (target_buf, "OK"))
10737 warning (_("Target does not support source download."));
10739 remote_download_command_source (b->number, loc->address,
10740 breakpoint_commands (b));
10743 do_cleanups (old_chain);
10747 remote_can_download_tracepoint (struct target_ops *self)
10749 struct remote_state *rs = get_remote_state ();
10750 struct trace_status *ts;
10753 /* Don't try to install tracepoints until we've relocated our
10754 symbols, and fetched and merged the target's tracepoint list with
10756 if (rs->starting_up)
10759 ts = current_trace_status ();
10760 status = remote_get_trace_status (self, ts);
10762 if (status == -1 || !ts->running_known || !ts->running)
10765 /* If we are in a tracing experiment, but remote stub doesn't support
10766 installing tracepoint in trace, we have to return. */
10767 if (!remote_supports_install_in_trace ())
10775 remote_download_trace_state_variable (struct target_ops *self,
10776 struct trace_state_variable *tsv)
10778 struct remote_state *rs = get_remote_state ();
10781 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10782 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10784 p = rs->buf + strlen (rs->buf);
10785 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10786 error (_("Trace state variable name too long for tsv definition packet"));
10787 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
10790 remote_get_noisy_reply (&target_buf, &target_buf_size);
10791 if (*target_buf == '\0')
10792 error (_("Target does not support this command."));
10793 if (strcmp (target_buf, "OK") != 0)
10794 error (_("Error on target while downloading trace state variable."));
10798 remote_enable_tracepoint (struct target_ops *self,
10799 struct bp_location *location)
10801 struct remote_state *rs = get_remote_state ();
10804 sprintf_vma (addr_buf, location->address);
10805 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10806 location->owner->number, addr_buf);
10808 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10809 if (*rs->buf == '\0')
10810 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10811 if (strcmp (rs->buf, "OK") != 0)
10812 error (_("Error on target while enabling tracepoint."));
10816 remote_disable_tracepoint (struct target_ops *self,
10817 struct bp_location *location)
10819 struct remote_state *rs = get_remote_state ();
10822 sprintf_vma (addr_buf, location->address);
10823 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10824 location->owner->number, addr_buf);
10826 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10827 if (*rs->buf == '\0')
10828 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10829 if (strcmp (rs->buf, "OK") != 0)
10830 error (_("Error on target while disabling tracepoint."));
10834 remote_trace_set_readonly_regions (struct target_ops *self)
10838 bfd_size_type size;
10844 return; /* No information to give. */
10846 strcpy (target_buf, "QTro");
10847 offset = strlen (target_buf);
10848 for (s = exec_bfd->sections; s; s = s->next)
10850 char tmp1[40], tmp2[40];
10853 if ((s->flags & SEC_LOAD) == 0 ||
10854 /* (s->flags & SEC_CODE) == 0 || */
10855 (s->flags & SEC_READONLY) == 0)
10859 vma = bfd_get_section_vma (abfd, s);
10860 size = bfd_get_section_size (s);
10861 sprintf_vma (tmp1, vma);
10862 sprintf_vma (tmp2, vma + size);
10863 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10864 if (offset + sec_length + 1 > target_buf_size)
10866 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
10868 Too many sections for read-only sections definition packet."));
10871 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10873 offset += sec_length;
10877 putpkt (target_buf);
10878 getpkt (&target_buf, &target_buf_size, 0);
10883 remote_trace_start (struct target_ops *self)
10885 putpkt ("QTStart");
10886 remote_get_noisy_reply (&target_buf, &target_buf_size);
10887 if (*target_buf == '\0')
10888 error (_("Target does not support this command."));
10889 if (strcmp (target_buf, "OK") != 0)
10890 error (_("Bogus reply from target: %s"), target_buf);
10894 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
10896 /* Initialize it just to avoid a GCC false warning. */
10898 /* FIXME we need to get register block size some other way. */
10899 extern int trace_regblock_size;
10900 enum packet_result result;
10902 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
10905 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10907 putpkt ("qTStatus");
10911 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10913 CATCH (ex, RETURN_MASK_ERROR)
10915 if (ex.error != TARGET_CLOSE_ERROR)
10917 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10920 throw_exception (ex);
10924 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10926 /* If the remote target doesn't do tracing, flag it. */
10927 if (result == PACKET_UNKNOWN)
10930 /* We're working with a live target. */
10931 ts->filename = NULL;
10934 error (_("Bogus trace status reply from target: %s"), target_buf);
10936 /* Function 'parse_trace_status' sets default value of each field of
10937 'ts' at first, so we don't have to do it here. */
10938 parse_trace_status (p, ts);
10940 return ts->running;
10944 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
10945 struct uploaded_tp *utp)
10947 struct remote_state *rs = get_remote_state ();
10949 struct bp_location *loc;
10950 struct tracepoint *tp = (struct tracepoint *) bp;
10951 size_t size = get_remote_packet_size ();
10955 tp->base.hit_count = 0;
10956 tp->traceframe_usage = 0;
10957 for (loc = tp->base.loc; loc; loc = loc->next)
10959 /* If the tracepoint was never downloaded, don't go asking for
10961 if (tp->number_on_target == 0)
10963 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10964 phex_nz (loc->address, 0));
10966 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10967 if (reply && *reply)
10970 parse_tracepoint_status (reply + 1, bp, utp);
10976 utp->hit_count = 0;
10977 utp->traceframe_usage = 0;
10978 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10979 phex_nz (utp->addr, 0));
10981 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10982 if (reply && *reply)
10985 parse_tracepoint_status (reply + 1, bp, utp);
10991 remote_trace_stop (struct target_ops *self)
10994 remote_get_noisy_reply (&target_buf, &target_buf_size);
10995 if (*target_buf == '\0')
10996 error (_("Target does not support this command."));
10997 if (strcmp (target_buf, "OK") != 0)
10998 error (_("Bogus reply from target: %s"), target_buf);
11002 remote_trace_find (struct target_ops *self,
11003 enum trace_find_type type, int num,
11004 CORE_ADDR addr1, CORE_ADDR addr2,
11007 struct remote_state *rs = get_remote_state ();
11008 char *endbuf = rs->buf + get_remote_packet_size ();
11010 int target_frameno = -1, target_tracept = -1;
11012 /* Lookups other than by absolute frame number depend on the current
11013 trace selected, so make sure it is correct on the remote end
11015 if (type != tfind_number)
11016 set_remote_traceframe ();
11019 strcpy (p, "QTFrame:");
11020 p = strchr (p, '\0');
11024 xsnprintf (p, endbuf - p, "%x", num);
11027 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11030 xsnprintf (p, endbuf - p, "tdp:%x", num);
11033 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11034 phex_nz (addr2, 0));
11036 case tfind_outside:
11037 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11038 phex_nz (addr2, 0));
11041 error (_("Unknown trace find type %d"), type);
11045 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11046 if (*reply == '\0')
11047 error (_("Target does not support this command."));
11049 while (reply && *reply)
11054 target_frameno = (int) strtol (p, &reply, 16);
11056 error (_("Unable to parse trace frame number"));
11057 /* Don't update our remote traceframe number cache on failure
11058 to select a remote traceframe. */
11059 if (target_frameno == -1)
11064 target_tracept = (int) strtol (p, &reply, 16);
11066 error (_("Unable to parse tracepoint number"));
11068 case 'O': /* "OK"? */
11069 if (reply[1] == 'K' && reply[2] == '\0')
11072 error (_("Bogus reply from target: %s"), reply);
11075 error (_("Bogus reply from target: %s"), reply);
11078 *tpp = target_tracept;
11080 rs->remote_traceframe_number = target_frameno;
11081 return target_frameno;
11085 remote_get_trace_state_variable_value (struct target_ops *self,
11086 int tsvnum, LONGEST *val)
11088 struct remote_state *rs = get_remote_state ();
11092 set_remote_traceframe ();
11094 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11096 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11097 if (reply && *reply)
11101 unpack_varlen_hex (reply + 1, &uval);
11102 *val = (LONGEST) uval;
11110 remote_save_trace_data (struct target_ops *self, const char *filename)
11112 struct remote_state *rs = get_remote_state ();
11116 strcpy (p, "QTSave:");
11118 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11119 error (_("Remote file name too long for trace save packet"));
11120 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11123 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11124 if (*reply == '\0')
11125 error (_("Target does not support this command."));
11126 if (strcmp (reply, "OK") != 0)
11127 error (_("Bogus reply from target: %s"), reply);
11131 /* This is basically a memory transfer, but needs to be its own packet
11132 because we don't know how the target actually organizes its trace
11133 memory, plus we want to be able to ask for as much as possible, but
11134 not be unhappy if we don't get as much as we ask for. */
11137 remote_get_raw_trace_data (struct target_ops *self,
11138 gdb_byte *buf, ULONGEST offset, LONGEST len)
11140 struct remote_state *rs = get_remote_state ();
11146 strcpy (p, "qTBuffer:");
11148 p += hexnumstr (p, offset);
11150 p += hexnumstr (p, len);
11154 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11155 if (reply && *reply)
11157 /* 'l' by itself means we're at the end of the buffer and
11158 there is nothing more to get. */
11162 /* Convert the reply into binary. Limit the number of bytes to
11163 convert according to our passed-in buffer size, rather than
11164 what was returned in the packet; if the target is
11165 unexpectedly generous and gives us a bigger reply than we
11166 asked for, we don't want to crash. */
11167 rslt = hex2bin (target_buf, buf, len);
11171 /* Something went wrong, flag as an error. */
11176 remote_set_disconnected_tracing (struct target_ops *self, int val)
11178 struct remote_state *rs = get_remote_state ();
11180 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11184 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11186 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11187 if (*reply == '\0')
11188 error (_("Target does not support this command."));
11189 if (strcmp (reply, "OK") != 0)
11190 error (_("Bogus reply from target: %s"), reply);
11193 warning (_("Target does not support disconnected tracing."));
11197 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11199 struct thread_info *info = find_thread_ptid (ptid);
11201 if (info && info->priv)
11202 return info->priv->core;
11207 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11209 struct remote_state *rs = get_remote_state ();
11212 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11214 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11215 if (*reply == '\0')
11216 error (_("Target does not support this command."));
11217 if (strcmp (reply, "OK") != 0)
11218 error (_("Bogus reply from target: %s"), reply);
11221 static struct traceframe_info *
11222 remote_traceframe_info (struct target_ops *self)
11226 text = target_read_stralloc (¤t_target,
11227 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11230 struct traceframe_info *info;
11231 struct cleanup *back_to = make_cleanup (xfree, text);
11233 info = parse_traceframe_info (text);
11234 do_cleanups (back_to);
11241 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11242 instruction on which a fast tracepoint may be placed. Returns -1
11243 if the packet is not supported, and 0 if the minimum instruction
11244 length is unknown. */
11247 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11249 struct remote_state *rs = get_remote_state ();
11252 /* If we're not debugging a process yet, the IPA can't be
11254 if (!target_has_execution)
11257 /* Make sure the remote is pointing at the right process. */
11258 set_general_process ();
11260 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11262 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11263 if (*reply == '\0')
11267 ULONGEST min_insn_len;
11269 unpack_varlen_hex (reply, &min_insn_len);
11271 return (int) min_insn_len;
11276 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11278 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11280 struct remote_state *rs = get_remote_state ();
11281 char *buf = rs->buf;
11282 char *endbuf = rs->buf + get_remote_packet_size ();
11283 enum packet_result result;
11285 gdb_assert (val >= 0 || val == -1);
11286 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11287 /* Send -1 as literal "-1" to avoid host size dependency. */
11291 buf += hexnumstr (buf, (ULONGEST) -val);
11294 buf += hexnumstr (buf, (ULONGEST) val);
11297 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11298 result = packet_ok (rs->buf,
11299 &remote_protocol_packets[PACKET_QTBuffer_size]);
11301 if (result != PACKET_OK)
11302 warning (_("Bogus reply from target: %s"), rs->buf);
11307 remote_set_trace_notes (struct target_ops *self,
11308 const char *user, const char *notes,
11309 const char *stop_notes)
11311 struct remote_state *rs = get_remote_state ();
11313 char *buf = rs->buf;
11314 char *endbuf = rs->buf + get_remote_packet_size ();
11317 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11320 buf += xsnprintf (buf, endbuf - buf, "user:");
11321 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11327 buf += xsnprintf (buf, endbuf - buf, "notes:");
11328 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11334 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11335 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11339 /* Ensure the buffer is terminated. */
11343 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11344 if (*reply == '\0')
11347 if (strcmp (reply, "OK") != 0)
11348 error (_("Bogus reply from target: %s"), reply);
11354 remote_use_agent (struct target_ops *self, int use)
11356 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11358 struct remote_state *rs = get_remote_state ();
11360 /* If the stub supports QAgent. */
11361 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11363 getpkt (&rs->buf, &rs->buf_size, 0);
11365 if (strcmp (rs->buf, "OK") == 0)
11376 remote_can_use_agent (struct target_ops *self)
11378 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11381 struct btrace_target_info
11383 /* The ptid of the traced thread. */
11386 /* The obtained branch trace configuration. */
11387 struct btrace_config conf;
11390 /* Reset our idea of our target's btrace configuration. */
11393 remote_btrace_reset (void)
11395 struct remote_state *rs = get_remote_state ();
11397 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11400 /* Check whether the target supports branch tracing. */
11403 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
11405 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
11407 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
11412 case BTRACE_FORMAT_NONE:
11415 case BTRACE_FORMAT_BTS:
11416 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11419 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
11422 /* Synchronize the configuration with the target. */
11425 btrace_sync_conf (const struct btrace_config *conf)
11427 struct packet_config *packet;
11428 struct remote_state *rs;
11429 char *buf, *pos, *endbuf;
11431 rs = get_remote_state ();
11433 endbuf = buf + get_remote_packet_size ();
11435 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11436 if (packet_config_support (packet) == PACKET_ENABLE
11437 && conf->bts.size != rs->btrace_config.bts.size)
11440 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11444 getpkt (&buf, &rs->buf_size, 0);
11446 if (packet_ok (buf, packet) == PACKET_ERROR)
11448 if (buf[0] == 'E' && buf[1] == '.')
11449 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11451 error (_("Failed to configure the BTS buffer size."));
11454 rs->btrace_config.bts.size = conf->bts.size;
11458 /* Read the current thread's btrace configuration from the target and
11459 store it into CONF. */
11462 btrace_read_config (struct btrace_config *conf)
11466 xml = target_read_stralloc (¤t_target,
11467 TARGET_OBJECT_BTRACE_CONF, "");
11470 struct cleanup *cleanup;
11472 cleanup = make_cleanup (xfree, xml);
11473 parse_xml_btrace_conf (conf, xml);
11474 do_cleanups (cleanup);
11478 /* Enable branch tracing. */
11480 static struct btrace_target_info *
11481 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11482 const struct btrace_config *conf)
11484 struct btrace_target_info *tinfo = NULL;
11485 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11486 struct remote_state *rs = get_remote_state ();
11487 char *buf = rs->buf;
11488 char *endbuf = rs->buf + get_remote_packet_size ();
11490 if (packet_config_support (packet) != PACKET_ENABLE)
11491 error (_("Target does not support branch tracing."));
11493 btrace_sync_conf (conf);
11495 set_general_thread (ptid);
11497 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11499 getpkt (&rs->buf, &rs->buf_size, 0);
11501 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11503 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11504 error (_("Could not enable branch tracing for %s: %s"),
11505 target_pid_to_str (ptid), rs->buf + 2);
11507 error (_("Could not enable branch tracing for %s."),
11508 target_pid_to_str (ptid));
11511 tinfo = xzalloc (sizeof (*tinfo));
11512 tinfo->ptid = ptid;
11514 /* If we fail to read the configuration, we lose some information, but the
11515 tracing itself is not impacted. */
11518 btrace_read_config (&tinfo->conf);
11520 CATCH (err, RETURN_MASK_ERROR)
11522 if (err.message != NULL)
11523 warning ("%s", err.message);
11530 /* Disable branch tracing. */
11533 remote_disable_btrace (struct target_ops *self,
11534 struct btrace_target_info *tinfo)
11536 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11537 struct remote_state *rs = get_remote_state ();
11538 char *buf = rs->buf;
11539 char *endbuf = rs->buf + get_remote_packet_size ();
11541 if (packet_config_support (packet) != PACKET_ENABLE)
11542 error (_("Target does not support branch tracing."));
11544 set_general_thread (tinfo->ptid);
11546 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11548 getpkt (&rs->buf, &rs->buf_size, 0);
11550 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11552 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11553 error (_("Could not disable branch tracing for %s: %s"),
11554 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11556 error (_("Could not disable branch tracing for %s."),
11557 target_pid_to_str (tinfo->ptid));
11563 /* Teardown branch tracing. */
11566 remote_teardown_btrace (struct target_ops *self,
11567 struct btrace_target_info *tinfo)
11569 /* We must not talk to the target during teardown. */
11573 /* Read the branch trace. */
11575 static enum btrace_error
11576 remote_read_btrace (struct target_ops *self,
11577 struct btrace_data *btrace,
11578 struct btrace_target_info *tinfo,
11579 enum btrace_read_type type)
11581 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11582 struct remote_state *rs = get_remote_state ();
11583 struct cleanup *cleanup;
11587 if (packet_config_support (packet) != PACKET_ENABLE)
11588 error (_("Target does not support branch tracing."));
11590 #if !defined(HAVE_LIBEXPAT)
11591 error (_("Cannot process branch tracing result. XML parsing not supported."));
11596 case BTRACE_READ_ALL:
11599 case BTRACE_READ_NEW:
11602 case BTRACE_READ_DELTA:
11606 internal_error (__FILE__, __LINE__,
11607 _("Bad branch tracing read type: %u."),
11608 (unsigned int) type);
11611 xml = target_read_stralloc (¤t_target,
11612 TARGET_OBJECT_BTRACE, annex);
11614 return BTRACE_ERR_UNKNOWN;
11616 cleanup = make_cleanup (xfree, xml);
11617 parse_xml_btrace (btrace, xml);
11618 do_cleanups (cleanup);
11620 return BTRACE_ERR_NONE;
11623 static const struct btrace_config *
11624 remote_btrace_conf (struct target_ops *self,
11625 const struct btrace_target_info *tinfo)
11627 return &tinfo->conf;
11631 remote_augmented_libraries_svr4_read (struct target_ops *self)
11633 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11637 /* Implementation of to_load. */
11640 remote_load (struct target_ops *self, const char *name, int from_tty)
11642 generic_load (name, from_tty);
11646 init_remote_ops (void)
11648 remote_ops.to_shortname = "remote";
11649 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11650 remote_ops.to_doc =
11651 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11652 Specify the serial device it is connected to\n\
11653 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11654 remote_ops.to_open = remote_open;
11655 remote_ops.to_close = remote_close;
11656 remote_ops.to_detach = remote_detach;
11657 remote_ops.to_disconnect = remote_disconnect;
11658 remote_ops.to_resume = remote_resume;
11659 remote_ops.to_wait = remote_wait;
11660 remote_ops.to_fetch_registers = remote_fetch_registers;
11661 remote_ops.to_store_registers = remote_store_registers;
11662 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11663 remote_ops.to_files_info = remote_files_info;
11664 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11665 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11666 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
11667 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
11668 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
11669 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
11670 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11671 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11672 remote_ops.to_watchpoint_addr_within_range =
11673 remote_watchpoint_addr_within_range;
11674 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11675 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11676 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11677 remote_ops.to_region_ok_for_hw_watchpoint
11678 = remote_region_ok_for_hw_watchpoint;
11679 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11680 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11681 remote_ops.to_kill = remote_kill;
11682 remote_ops.to_load = remote_load;
11683 remote_ops.to_mourn_inferior = remote_mourn;
11684 remote_ops.to_pass_signals = remote_pass_signals;
11685 remote_ops.to_program_signals = remote_program_signals;
11686 remote_ops.to_thread_alive = remote_thread_alive;
11687 remote_ops.to_update_thread_list = remote_update_thread_list;
11688 remote_ops.to_pid_to_str = remote_pid_to_str;
11689 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11690 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11691 remote_ops.to_stop = remote_stop;
11692 remote_ops.to_xfer_partial = remote_xfer_partial;
11693 remote_ops.to_rcmd = remote_rcmd;
11694 remote_ops.to_log_command = serial_log_command;
11695 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11696 remote_ops.to_stratum = process_stratum;
11697 remote_ops.to_has_all_memory = default_child_has_all_memory;
11698 remote_ops.to_has_memory = default_child_has_memory;
11699 remote_ops.to_has_stack = default_child_has_stack;
11700 remote_ops.to_has_registers = default_child_has_registers;
11701 remote_ops.to_has_execution = default_child_has_execution;
11702 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11703 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11704 remote_ops.to_magic = OPS_MAGIC;
11705 remote_ops.to_memory_map = remote_memory_map;
11706 remote_ops.to_flash_erase = remote_flash_erase;
11707 remote_ops.to_flash_done = remote_flash_done;
11708 remote_ops.to_read_description = remote_read_description;
11709 remote_ops.to_search_memory = remote_search_memory;
11710 remote_ops.to_can_async_p = remote_can_async_p;
11711 remote_ops.to_is_async_p = remote_is_async_p;
11712 remote_ops.to_async = remote_async;
11713 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11714 remote_ops.to_terminal_ours = remote_terminal_ours;
11715 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11716 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11717 remote_ops.to_supports_disable_randomization
11718 = remote_supports_disable_randomization;
11719 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
11720 remote_ops.to_fileio_open = remote_hostio_open;
11721 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11722 remote_ops.to_fileio_pread = remote_hostio_pread;
11723 remote_ops.to_fileio_fstat = remote_hostio_fstat;
11724 remote_ops.to_fileio_close = remote_hostio_close;
11725 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11726 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11727 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11728 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11729 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11730 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11731 remote_ops.to_trace_init = remote_trace_init;
11732 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11733 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11734 remote_ops.to_download_trace_state_variable
11735 = remote_download_trace_state_variable;
11736 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11737 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11738 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11739 remote_ops.to_trace_start = remote_trace_start;
11740 remote_ops.to_get_trace_status = remote_get_trace_status;
11741 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11742 remote_ops.to_trace_stop = remote_trace_stop;
11743 remote_ops.to_trace_find = remote_trace_find;
11744 remote_ops.to_get_trace_state_variable_value
11745 = remote_get_trace_state_variable_value;
11746 remote_ops.to_save_trace_data = remote_save_trace_data;
11747 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11748 remote_ops.to_upload_trace_state_variables
11749 = remote_upload_trace_state_variables;
11750 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11751 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11752 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11753 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11754 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11755 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11756 remote_ops.to_core_of_thread = remote_core_of_thread;
11757 remote_ops.to_verify_memory = remote_verify_memory;
11758 remote_ops.to_get_tib_address = remote_get_tib_address;
11759 remote_ops.to_set_permissions = remote_set_permissions;
11760 remote_ops.to_static_tracepoint_marker_at
11761 = remote_static_tracepoint_marker_at;
11762 remote_ops.to_static_tracepoint_markers_by_strid
11763 = remote_static_tracepoint_markers_by_strid;
11764 remote_ops.to_traceframe_info = remote_traceframe_info;
11765 remote_ops.to_use_agent = remote_use_agent;
11766 remote_ops.to_can_use_agent = remote_can_use_agent;
11767 remote_ops.to_supports_btrace = remote_supports_btrace;
11768 remote_ops.to_enable_btrace = remote_enable_btrace;
11769 remote_ops.to_disable_btrace = remote_disable_btrace;
11770 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11771 remote_ops.to_read_btrace = remote_read_btrace;
11772 remote_ops.to_btrace_conf = remote_btrace_conf;
11773 remote_ops.to_augmented_libraries_svr4_read =
11774 remote_augmented_libraries_svr4_read;
11777 /* Set up the extended remote vector by making a copy of the standard
11778 remote vector and adding to it. */
11781 init_extended_remote_ops (void)
11783 extended_remote_ops = remote_ops;
11785 extended_remote_ops.to_shortname = "extended-remote";
11786 extended_remote_ops.to_longname =
11787 "Extended remote serial target in gdb-specific protocol";
11788 extended_remote_ops.to_doc =
11789 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11790 Specify the serial device it is connected to (e.g. /dev/ttya).";
11791 extended_remote_ops.to_open = extended_remote_open;
11792 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11793 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11794 extended_remote_ops.to_detach = extended_remote_detach;
11795 extended_remote_ops.to_attach = extended_remote_attach;
11796 extended_remote_ops.to_post_attach = extended_remote_post_attach;
11797 extended_remote_ops.to_kill = extended_remote_kill;
11798 extended_remote_ops.to_supports_disable_randomization
11799 = extended_remote_supports_disable_randomization;
11803 remote_can_async_p (struct target_ops *ops)
11805 struct remote_state *rs = get_remote_state ();
11807 if (!target_async_permitted)
11808 /* We only enable async when the user specifically asks for it. */
11811 /* We're async whenever the serial device is. */
11812 return serial_can_async_p (rs->remote_desc);
11816 remote_is_async_p (struct target_ops *ops)
11818 struct remote_state *rs = get_remote_state ();
11820 if (!target_async_permitted)
11821 /* We only enable async when the user specifically asks for it. */
11824 /* We're async whenever the serial device is. */
11825 return serial_is_async_p (rs->remote_desc);
11828 /* Pass the SERIAL event on and up to the client. One day this code
11829 will be able to delay notifying the client of an event until the
11830 point where an entire packet has been received. */
11832 static serial_event_ftype remote_async_serial_handler;
11835 remote_async_serial_handler (struct serial *scb, void *context)
11837 struct remote_state *rs = context;
11839 /* Don't propogate error information up to the client. Instead let
11840 the client find out about the error by querying the target. */
11841 inferior_event_handler (INF_REG_EVENT, NULL);
11845 remote_async_inferior_event_handler (gdb_client_data data)
11847 inferior_event_handler (INF_REG_EVENT, NULL);
11851 remote_async (struct target_ops *ops, int enable)
11853 struct remote_state *rs = get_remote_state ();
11857 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11859 /* If there are pending events in the stop reply queue tell the
11860 event loop to process them. */
11861 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11862 mark_async_event_handler (remote_async_inferior_event_token);
11866 serial_async (rs->remote_desc, NULL, NULL);
11867 clear_async_event_handler (remote_async_inferior_event_token);
11872 set_remote_cmd (char *args, int from_tty)
11874 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
11878 show_remote_cmd (char *args, int from_tty)
11880 /* We can't just use cmd_show_list here, because we want to skip
11881 the redundant "show remote Z-packet" and the legacy aliases. */
11882 struct cleanup *showlist_chain;
11883 struct cmd_list_element *list = remote_show_cmdlist;
11884 struct ui_out *uiout = current_uiout;
11886 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11887 for (; list != NULL; list = list->next)
11888 if (strcmp (list->name, "Z-packet") == 0)
11890 else if (list->type == not_set_cmd)
11891 /* Alias commands are exactly like the original, except they
11892 don't have the normal type. */
11896 struct cleanup *option_chain
11897 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11899 ui_out_field_string (uiout, "name", list->name);
11900 ui_out_text (uiout, ": ");
11901 if (list->type == show_cmd)
11902 do_show_command ((char *) NULL, from_tty, list);
11904 cmd_func (list, NULL, from_tty);
11905 /* Close the tuple. */
11906 do_cleanups (option_chain);
11909 /* Close the tuple. */
11910 do_cleanups (showlist_chain);
11914 /* Function to be called whenever a new objfile (shlib) is detected. */
11916 remote_new_objfile (struct objfile *objfile)
11918 struct remote_state *rs = get_remote_state ();
11920 if (rs->remote_desc != 0) /* Have a remote connection. */
11921 remote_check_symbols ();
11924 /* Pull all the tracepoints defined on the target and create local
11925 data structures representing them. We don't want to create real
11926 tracepoints yet, we don't want to mess up the user's existing
11930 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
11932 struct remote_state *rs = get_remote_state ();
11935 /* Ask for a first packet of tracepoint definition. */
11937 getpkt (&rs->buf, &rs->buf_size, 0);
11939 while (*p && *p != 'l')
11941 parse_tracepoint_definition (p, utpp);
11942 /* Ask for another packet of tracepoint definition. */
11944 getpkt (&rs->buf, &rs->buf_size, 0);
11951 remote_upload_trace_state_variables (struct target_ops *self,
11952 struct uploaded_tsv **utsvp)
11954 struct remote_state *rs = get_remote_state ();
11957 /* Ask for a first packet of variable definition. */
11959 getpkt (&rs->buf, &rs->buf_size, 0);
11961 while (*p && *p != 'l')
11963 parse_tsv_definition (p, utsvp);
11964 /* Ask for another packet of variable definition. */
11966 getpkt (&rs->buf, &rs->buf_size, 0);
11972 /* The "set/show range-stepping" show hook. */
11975 show_range_stepping (struct ui_file *file, int from_tty,
11976 struct cmd_list_element *c,
11979 fprintf_filtered (file,
11980 _("Debugger's willingness to use range stepping "
11981 "is %s.\n"), value);
11984 /* The "set/show range-stepping" set hook. */
11987 set_range_stepping (char *ignore_args, int from_tty,
11988 struct cmd_list_element *c)
11990 struct remote_state *rs = get_remote_state ();
11992 /* Whene enabling, check whether range stepping is actually
11993 supported by the target, and warn if not. */
11994 if (use_range_stepping)
11996 if (rs->remote_desc != NULL)
11998 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
11999 remote_vcont_probe (rs);
12001 if (packet_support (PACKET_vCont) == PACKET_ENABLE
12002 && rs->supports_vCont.r)
12006 warning (_("Range stepping is not supported by the current target"));
12011 _initialize_remote (void)
12013 struct remote_state *rs;
12014 struct cmd_list_element *cmd;
12015 const char *cmd_name;
12017 /* architecture specific data */
12018 remote_gdbarch_data_handle =
12019 gdbarch_data_register_post_init (init_remote_state);
12020 remote_g_packet_data_handle =
12021 gdbarch_data_register_pre_init (remote_g_packet_data_init);
12023 /* Initialize the per-target state. At the moment there is only one
12024 of these, not one per target. Only one target is active at a
12026 remote_state = new_remote_state ();
12028 init_remote_ops ();
12029 add_target (&remote_ops);
12031 init_extended_remote_ops ();
12032 add_target (&extended_remote_ops);
12034 /* Hook into new objfile notification. */
12035 observer_attach_new_objfile (remote_new_objfile);
12036 /* We're no longer interested in notification events of an inferior
12038 observer_attach_inferior_exit (discard_pending_stop_replies);
12040 /* Set up signal handlers. */
12041 async_sigint_remote_token =
12042 create_async_signal_handler (async_remote_interrupt, NULL);
12043 async_sigint_remote_twice_token =
12044 create_async_signal_handler (async_remote_interrupt_twice, NULL);
12047 init_remote_threadtests ();
12050 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
12051 /* set/show remote ... */
12053 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12054 Remote protocol specific variables\n\
12055 Configure various remote-protocol specific variables such as\n\
12056 the packets being used"),
12057 &remote_set_cmdlist, "set remote ",
12058 0 /* allow-unknown */, &setlist);
12059 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12060 Remote protocol specific variables\n\
12061 Configure various remote-protocol specific variables such as\n\
12062 the packets being used"),
12063 &remote_show_cmdlist, "show remote ",
12064 0 /* allow-unknown */, &showlist);
12066 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12067 Compare section data on target to the exec file.\n\
12068 Argument is a single section name (default: all loaded sections).\n\
12069 To compare only read-only loaded sections, specify the -r option."),
12072 add_cmd ("packet", class_maintenance, packet_command, _("\
12073 Send an arbitrary packet to a remote target.\n\
12074 maintenance packet TEXT\n\
12075 If GDB is talking to an inferior via the GDB serial protocol, then\n\
12076 this command sends the string TEXT to the inferior, and displays the\n\
12077 response packet. GDB supplies the initial `$' character, and the\n\
12078 terminating `#' character and checksum."),
12081 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12082 Set whether to send break if interrupted."), _("\
12083 Show whether to send break if interrupted."), _("\
12084 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12085 set_remotebreak, show_remotebreak,
12086 &setlist, &showlist);
12087 cmd_name = "remotebreak";
12088 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12089 deprecate_cmd (cmd, "set remote interrupt-sequence");
12090 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12091 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12092 deprecate_cmd (cmd, "show remote interrupt-sequence");
12094 add_setshow_enum_cmd ("interrupt-sequence", class_support,
12095 interrupt_sequence_modes, &interrupt_sequence_mode,
12097 Set interrupt sequence to remote target."), _("\
12098 Show interrupt sequence to remote target."), _("\
12099 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12100 NULL, show_interrupt_sequence,
12101 &remote_set_cmdlist,
12102 &remote_show_cmdlist);
12104 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12105 &interrupt_on_connect, _("\
12106 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12107 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12108 If set, interrupt sequence is sent to remote target."),
12110 &remote_set_cmdlist, &remote_show_cmdlist);
12112 /* Install commands for configuring memory read/write packets. */
12114 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12115 Set the maximum number of bytes per memory write packet (deprecated)."),
12117 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12118 Show the maximum number of bytes per memory write packet (deprecated)."),
12120 add_cmd ("memory-write-packet-size", no_class,
12121 set_memory_write_packet_size, _("\
12122 Set the maximum number of bytes per memory-write packet.\n\
12123 Specify the number of bytes in a packet or 0 (zero) for the\n\
12124 default packet size. The actual limit is further reduced\n\
12125 dependent on the target. Specify ``fixed'' to disable the\n\
12126 further restriction and ``limit'' to enable that restriction."),
12127 &remote_set_cmdlist);
12128 add_cmd ("memory-read-packet-size", no_class,
12129 set_memory_read_packet_size, _("\
12130 Set the maximum number of bytes per memory-read packet.\n\
12131 Specify the number of bytes in a packet or 0 (zero) for the\n\
12132 default packet size. The actual limit is further reduced\n\
12133 dependent on the target. Specify ``fixed'' to disable the\n\
12134 further restriction and ``limit'' to enable that restriction."),
12135 &remote_set_cmdlist);
12136 add_cmd ("memory-write-packet-size", no_class,
12137 show_memory_write_packet_size,
12138 _("Show the maximum number of bytes per memory-write packet."),
12139 &remote_show_cmdlist);
12140 add_cmd ("memory-read-packet-size", no_class,
12141 show_memory_read_packet_size,
12142 _("Show the maximum number of bytes per memory-read packet."),
12143 &remote_show_cmdlist);
12145 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12146 &remote_hw_watchpoint_limit, _("\
12147 Set the maximum number of target hardware watchpoints."), _("\
12148 Show the maximum number of target hardware watchpoints."), _("\
12149 Specify a negative limit for unlimited."),
12150 NULL, NULL, /* FIXME: i18n: The maximum
12151 number of target hardware
12152 watchpoints is %s. */
12153 &remote_set_cmdlist, &remote_show_cmdlist);
12154 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12155 &remote_hw_watchpoint_length_limit, _("\
12156 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12157 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12158 Specify a negative limit for unlimited."),
12159 NULL, NULL, /* FIXME: i18n: The maximum
12160 length (in bytes) of a target
12161 hardware watchpoint is %s. */
12162 &remote_set_cmdlist, &remote_show_cmdlist);
12163 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12164 &remote_hw_breakpoint_limit, _("\
12165 Set the maximum number of target hardware breakpoints."), _("\
12166 Show the maximum number of target hardware breakpoints."), _("\
12167 Specify a negative limit for unlimited."),
12168 NULL, NULL, /* FIXME: i18n: The maximum
12169 number of target hardware
12170 breakpoints is %s. */
12171 &remote_set_cmdlist, &remote_show_cmdlist);
12173 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12174 &remote_address_size, _("\
12175 Set the maximum size of the address (in bits) in a memory packet."), _("\
12176 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12178 NULL, /* FIXME: i18n: */
12179 &setlist, &showlist);
12181 init_all_packet_configs ();
12183 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12184 "X", "binary-download", 1);
12186 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12187 "vCont", "verbose-resume", 0);
12189 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12190 "QPassSignals", "pass-signals", 0);
12192 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12193 "QProgramSignals", "program-signals", 0);
12195 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12196 "qSymbol", "symbol-lookup", 0);
12198 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12199 "P", "set-register", 1);
12201 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12202 "p", "fetch-register", 1);
12204 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12205 "Z0", "software-breakpoint", 0);
12207 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12208 "Z1", "hardware-breakpoint", 0);
12210 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12211 "Z2", "write-watchpoint", 0);
12213 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12214 "Z3", "read-watchpoint", 0);
12216 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12217 "Z4", "access-watchpoint", 0);
12219 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12220 "qXfer:auxv:read", "read-aux-vector", 0);
12222 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12223 "qXfer:features:read", "target-features", 0);
12225 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12226 "qXfer:libraries:read", "library-info", 0);
12228 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12229 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12231 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12232 "qXfer:memory-map:read", "memory-map", 0);
12234 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12235 "qXfer:spu:read", "read-spu-object", 0);
12237 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12238 "qXfer:spu:write", "write-spu-object", 0);
12240 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12241 "qXfer:osdata:read", "osdata", 0);
12243 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12244 "qXfer:threads:read", "threads", 0);
12246 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12247 "qXfer:siginfo:read", "read-siginfo-object", 0);
12249 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12250 "qXfer:siginfo:write", "write-siginfo-object", 0);
12252 add_packet_config_cmd
12253 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12254 "qXfer:traceframe-info:read", "traceframe-info", 0);
12256 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12257 "qXfer:uib:read", "unwind-info-block", 0);
12259 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12260 "qGetTLSAddr", "get-thread-local-storage-address",
12263 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12264 "qGetTIBAddr", "get-thread-information-block-address",
12267 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12268 "bc", "reverse-continue", 0);
12270 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12271 "bs", "reverse-step", 0);
12273 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12274 "qSupported", "supported-packets", 0);
12276 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12277 "qSearch:memory", "search-memory", 0);
12279 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12280 "qTStatus", "trace-status", 0);
12282 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12283 "vFile:open", "hostio-open", 0);
12285 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12286 "vFile:pread", "hostio-pread", 0);
12288 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12289 "vFile:pwrite", "hostio-pwrite", 0);
12291 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12292 "vFile:close", "hostio-close", 0);
12294 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12295 "vFile:unlink", "hostio-unlink", 0);
12297 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12298 "vFile:readlink", "hostio-readlink", 0);
12300 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12301 "vFile:fstat", "hostio-fstat", 0);
12303 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12304 "vAttach", "attach", 0);
12306 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12309 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12310 "QStartNoAckMode", "noack", 0);
12312 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12313 "vKill", "kill", 0);
12315 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12316 "qAttached", "query-attached", 0);
12318 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12319 "ConditionalTracepoints",
12320 "conditional-tracepoints", 0);
12322 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12323 "ConditionalBreakpoints",
12324 "conditional-breakpoints", 0);
12326 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12327 "BreakpointCommands",
12328 "breakpoint-commands", 0);
12330 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12331 "FastTracepoints", "fast-tracepoints", 0);
12333 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12334 "TracepointSource", "TracepointSource", 0);
12336 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12337 "QAllow", "allow", 0);
12339 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12340 "StaticTracepoints", "static-tracepoints", 0);
12342 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12343 "InstallInTrace", "install-in-trace", 0);
12345 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12346 "qXfer:statictrace:read", "read-sdata-object", 0);
12348 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12349 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12351 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12352 "QDisableRandomization", "disable-randomization", 0);
12354 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12355 "QAgent", "agent", 0);
12357 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12358 "QTBuffer:size", "trace-buffer-size", 0);
12360 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12361 "Qbtrace:off", "disable-btrace", 0);
12363 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12364 "Qbtrace:bts", "enable-btrace", 0);
12366 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12367 "qXfer:btrace", "read-btrace", 0);
12369 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12370 "qXfer:btrace-conf", "read-btrace-conf", 0);
12372 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12373 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12375 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12376 "swbreak-feature", "swbreak-feature", 0);
12378 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12379 "hwbreak-feature", "hwbreak-feature", 0);
12381 /* Assert that we've registered "set remote foo-packet" commands
12382 for all packet configs. */
12386 for (i = 0; i < PACKET_MAX; i++)
12388 /* Ideally all configs would have a command associated. Some
12389 still don't though. */
12394 case PACKET_QNonStop:
12395 case PACKET_multiprocess_feature:
12396 case PACKET_EnableDisableTracepoints_feature:
12397 case PACKET_tracenz_feature:
12398 case PACKET_DisconnectedTracing_feature:
12399 case PACKET_augmented_libraries_svr4_read_feature:
12401 /* Additions to this list need to be well justified:
12402 pre-existing packets are OK; new packets are not. */
12410 /* This catches both forgetting to add a config command, and
12411 forgetting to remove a packet from the exception list. */
12412 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12416 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12417 Z sub-packet has its own set and show commands, but users may
12418 have sets to this variable in their .gdbinit files (or in their
12420 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12421 &remote_Z_packet_detect, _("\
12422 Set use of remote protocol `Z' packets"), _("\
12423 Show use of remote protocol `Z' packets "), _("\
12424 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12426 set_remote_protocol_Z_packet_cmd,
12427 show_remote_protocol_Z_packet_cmd,
12428 /* FIXME: i18n: Use of remote protocol
12429 `Z' packets is %s. */
12430 &remote_set_cmdlist, &remote_show_cmdlist);
12432 add_prefix_cmd ("remote", class_files, remote_command, _("\
12433 Manipulate files on the remote system\n\
12434 Transfer files to and from the remote target system."),
12435 &remote_cmdlist, "remote ",
12436 0 /* allow-unknown */, &cmdlist);
12438 add_cmd ("put", class_files, remote_put_command,
12439 _("Copy a local file to the remote system."),
12442 add_cmd ("get", class_files, remote_get_command,
12443 _("Copy a remote file to the local system."),
12446 add_cmd ("delete", class_files, remote_delete_command,
12447 _("Delete a remote file."),
12450 remote_exec_file = xstrdup ("");
12451 add_setshow_string_noescape_cmd ("exec-file", class_files,
12452 &remote_exec_file, _("\
12453 Set the remote pathname for \"run\""), _("\
12454 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12455 &remote_set_cmdlist, &remote_show_cmdlist);
12457 add_setshow_boolean_cmd ("range-stepping", class_run,
12458 &use_range_stepping, _("\
12459 Enable or disable range stepping."), _("\
12460 Show whether target-assisted range stepping is enabled."), _("\
12461 If on, and the target supports it, when stepping a source line, GDB\n\
12462 tells the target to step the corresponding range of addresses itself instead\n\
12463 of issuing multiple single-steps. This speeds up source level\n\
12464 stepping. If off, GDB always issues single-steps, even if range\n\
12465 stepping is supported by the target. The default is on."),
12466 set_range_stepping,
12467 show_range_stepping,
12471 /* Eventually initialize fileio. See fileio.c */
12472 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12474 /* Take advantage of the fact that the TID field is not used, to tag
12475 special ptids with it set to != 0. */
12476 magic_null_ptid = ptid_build (42000, -1, 1);
12477 not_sent_ptid = ptid_build (42000, -2, 1);
12478 any_thread_ptid = ptid_build (42000, 0, 1);
12480 target_buf_size = 2048;
12481 target_buf = xmalloc (target_buf_size);