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_mourn_1 (struct target_ops *);
115 static void remote_send (char **buf, long *sizeof_buf_p);
117 static int readchar (int timeout);
119 static void remote_serial_write (const char *str, int len);
121 static void remote_kill (struct target_ops *ops);
123 static int remote_can_async_p (struct target_ops *);
125 static int remote_is_async_p (struct target_ops *);
127 static void remote_async (struct target_ops *ops, int enable);
129 static void sync_remote_interrupt_twice (int signo);
131 static void interrupt_query (void);
133 static void set_general_thread (struct ptid ptid);
134 static void set_continue_thread (struct ptid ptid);
136 static void get_offsets (void);
138 static void skip_frame (void);
140 static long read_frame (char **buf_p, long *sizeof_buf);
142 static int hexnumlen (ULONGEST num);
144 static void init_remote_ops (void);
146 static void init_extended_remote_ops (void);
148 static void remote_stop (struct target_ops *self, ptid_t);
150 static int stubhex (int ch);
152 static int hexnumstr (char *, ULONGEST);
154 static int hexnumnstr (char *, ULONGEST, int);
156 static CORE_ADDR remote_address_masked (CORE_ADDR);
158 static void print_packet (const char *);
160 static void compare_sections_command (char *, int);
162 static void packet_command (char *, int);
164 static int stub_unpack_int (char *buff, int fieldlength);
166 static ptid_t remote_current_thread (ptid_t oldptid);
168 static int putpkt_binary (const char *buf, int cnt);
170 static void check_binary_download (CORE_ADDR addr);
172 struct packet_config;
174 static void show_packet_config_cmd (struct packet_config *config);
176 static void show_remote_protocol_packet_cmd (struct ui_file *file,
178 struct cmd_list_element *c,
181 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
182 static ptid_t read_ptid (char *buf, char **obuf);
184 static void remote_set_permissions (struct target_ops *self);
187 static int remote_get_trace_status (struct target_ops *self,
188 struct trace_status *ts);
190 static int remote_upload_tracepoints (struct target_ops *self,
191 struct uploaded_tp **utpp);
193 static int remote_upload_trace_state_variables (struct target_ops *self,
194 struct uploaded_tsv **utsvp);
196 static void remote_query_supported (void);
198 static void remote_check_symbols (void);
200 void _initialize_remote (void);
203 static void stop_reply_xfree (struct stop_reply *);
204 static void remote_parse_stop_reply (char *, struct stop_reply *);
205 static void push_stop_reply (struct stop_reply *);
206 static void discard_pending_stop_replies_in_queue (struct remote_state *);
207 static int peek_stop_reply (ptid_t ptid);
209 static void remote_async_inferior_event_handler (gdb_client_data);
211 static void remote_terminal_ours (struct target_ops *self);
213 static int remote_read_description_p (struct target_ops *target);
215 static void remote_console_output (char *msg);
217 static int remote_supports_cond_breakpoints (struct target_ops *self);
219 static int remote_can_run_breakpoint_commands (struct target_ops *self);
221 static void remote_btrace_reset (void);
225 static struct cmd_list_element *remote_cmdlist;
227 /* For "set remote" and "show remote". */
229 static struct cmd_list_element *remote_set_cmdlist;
230 static struct cmd_list_element *remote_show_cmdlist;
232 /* Stub vCont actions support.
234 Each field is a boolean flag indicating whether the stub reports
235 support for the corresponding action. */
237 struct vCont_action_support
246 /* Controls whether GDB is willing to use range stepping. */
248 static int use_range_stepping = 1;
250 #define OPAQUETHREADBYTES 8
252 /* a 64 bit opaque identifier */
253 typedef unsigned char threadref[OPAQUETHREADBYTES];
255 /* About this many threadisds fit in a packet. */
257 #define MAXTHREADLISTRESULTS 32
259 /* Description of the remote protocol state for the currently
260 connected target. This is per-target state, and independent of the
261 selected architecture. */
265 /* A buffer to use for incoming packets, and its current size. The
266 buffer is grown dynamically for larger incoming packets.
267 Outgoing packets may also be constructed in this buffer.
268 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
269 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
274 /* True if we're going through initial connection setup (finding out
275 about the remote side's threads, relocating symbols, etc.). */
278 /* If we negotiated packet size explicitly (and thus can bypass
279 heuristics for the largest packet size that will not overflow
280 a buffer in the stub), this will be set to that packet size.
281 Otherwise zero, meaning to use the guessed size. */
282 long explicit_packet_size;
284 /* remote_wait is normally called when the target is running and
285 waits for a stop reply packet. But sometimes we need to call it
286 when the target is already stopped. We can send a "?" packet
287 and have remote_wait read the response. Or, if we already have
288 the response, we can stash it in BUF and tell remote_wait to
289 skip calling getpkt. This flag is set when BUF contains a
290 stop reply packet and the target is not waiting. */
291 int cached_wait_status;
293 /* True, if in no ack mode. That is, neither GDB nor the stub will
294 expect acks from each other. The connection is assumed to be
298 /* True if we're connected in extended remote mode. */
301 /* True if we resumed the target and we're waiting for the target to
302 stop. In the mean time, we can't start another command/query.
303 The remote server wouldn't be ready to process it, so we'd
304 timeout waiting for a reply that would never come and eventually
305 we'd close the connection. This can happen in asynchronous mode
306 because we allow GDB commands while the target is running. */
307 int waiting_for_stop_reply;
309 /* The status of the stub support for the various vCont actions. */
310 struct vCont_action_support supports_vCont;
312 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
313 responded to that. */
316 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
317 remote_open knows that we don't have a file open when the program
319 struct serial *remote_desc;
321 /* These are the threads which we last sent to the remote system. The
322 TID member will be -1 for all or -2 for not sent yet. */
323 ptid_t general_thread;
324 ptid_t continue_thread;
326 /* This is the traceframe which we last selected on the remote system.
327 It will be -1 if no traceframe is selected. */
328 int remote_traceframe_number;
330 char *last_pass_packet;
332 /* The last QProgramSignals packet sent to the target. We bypass
333 sending a new program signals list down to the target if the new
334 packet is exactly the same as the last we sent. IOW, we only let
335 the target know about program signals list changes. */
336 char *last_program_signals_packet;
338 enum gdb_signal last_sent_signal;
342 char *finished_object;
343 char *finished_annex;
344 ULONGEST finished_offset;
346 /* Should we try the 'ThreadInfo' query packet?
348 This variable (NOT available to the user: auto-detect only!)
349 determines whether GDB will use the new, simpler "ThreadInfo"
350 query or the older, more complex syntax for thread queries.
351 This is an auto-detect variable (set to true at each connect,
352 and set to false when the target fails to recognize it). */
353 int use_threadinfo_query;
354 int use_threadextra_query;
356 /* This is set to the data address of the access causing the target
357 to stop for a watchpoint. */
358 CORE_ADDR remote_watch_data_address;
360 /* Whether the target stopped for a breakpoint/watchpoint. */
361 enum target_stop_reason stop_reason;
363 threadref echo_nextthread;
364 threadref nextthread;
365 threadref resultthreadlist[MAXTHREADLISTRESULTS];
367 /* The state of remote notification. */
368 struct remote_notif_state *notif_state;
370 /* The branch trace configuration. */
371 struct btrace_config btrace_config;
374 /* Private data that we'll store in (struct thread_info)->private. */
375 struct private_thread_info
382 free_private_thread_info (struct private_thread_info *info)
388 /* This data could be associated with a target, but we do not always
389 have access to the current target when we need it, so for now it is
390 static. This will be fine for as long as only one target is in use
392 static struct remote_state *remote_state;
394 static struct remote_state *
395 get_remote_state_raw (void)
400 /* Allocate a new struct remote_state with xmalloc, initialize it, and
403 static struct remote_state *
404 new_remote_state (void)
406 struct remote_state *result = XCNEW (struct remote_state);
408 /* The default buffer size is unimportant; it will be expanded
409 whenever a larger buffer is needed. */
410 result->buf_size = 400;
411 result->buf = xmalloc (result->buf_size);
412 result->remote_traceframe_number = -1;
413 result->last_sent_signal = GDB_SIGNAL_0;
418 /* Description of the remote protocol for a given architecture. */
422 long offset; /* Offset into G packet. */
423 long regnum; /* GDB's internal register number. */
424 LONGEST pnum; /* Remote protocol register number. */
425 int in_g_packet; /* Always part of G packet. */
426 /* long size in bytes; == register_size (target_gdbarch (), regnum);
428 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
432 struct remote_arch_state
434 /* Description of the remote protocol registers. */
435 long sizeof_g_packet;
437 /* Description of the remote protocol registers indexed by REGNUM
438 (making an array gdbarch_num_regs in size). */
439 struct packet_reg *regs;
441 /* This is the size (in chars) of the first response to the ``g''
442 packet. It is used as a heuristic when determining the maximum
443 size of memory-read and memory-write packets. A target will
444 typically only reserve a buffer large enough to hold the ``g''
445 packet. The size does not include packet overhead (headers and
447 long actual_register_packet_size;
449 /* This is the maximum size (in chars) of a non read/write packet.
450 It is also used as a cap on the size of read/write packets. */
451 long remote_packet_size;
454 /* Utility: generate error from an incoming stub packet. */
456 trace_error (char *buf)
459 return; /* not an error msg */
462 case '1': /* malformed packet error */
463 if (*++buf == '0') /* general case: */
464 error (_("remote.c: error in outgoing packet."));
466 error (_("remote.c: error in outgoing packet at field #%ld."),
467 strtol (buf, NULL, 16));
469 error (_("Target returns error code '%s'."), buf);
473 /* Utility: wait for reply from stub, while accepting "O" packets. */
475 remote_get_noisy_reply (char **buf_p,
478 do /* Loop on reply from remote stub. */
482 QUIT; /* Allow user to bail out with ^C. */
483 getpkt (buf_p, sizeof_buf, 0);
487 else if (startswith (buf, "qRelocInsn:"))
490 CORE_ADDR from, to, org_to;
492 int adjusted_size = 0;
495 p = buf + strlen ("qRelocInsn:");
496 pp = unpack_varlen_hex (p, &ul);
498 error (_("invalid qRelocInsn packet: %s"), buf);
502 unpack_varlen_hex (p, &ul);
509 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
512 CATCH (ex, RETURN_MASK_ALL)
514 if (ex.error == MEMORY_ERROR)
516 /* Propagate memory errors silently back to the
517 target. The stub may have limited the range of
518 addresses we can write to, for example. */
522 /* Something unexpectedly bad happened. Be verbose
523 so we can tell what, and propagate the error back
524 to the stub, so it doesn't get stuck waiting for
526 exception_fprintf (gdb_stderr, ex,
527 _("warning: relocating instruction: "));
535 adjusted_size = to - org_to;
537 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
541 else if (buf[0] == 'O' && buf[1] != 'K')
542 remote_console_output (buf + 1); /* 'O' message from stub */
544 return buf; /* Here's the actual reply. */
549 /* Handle for retreving the remote protocol data from gdbarch. */
550 static struct gdbarch_data *remote_gdbarch_data_handle;
552 static struct remote_arch_state *
553 get_remote_arch_state (void)
555 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
558 /* Fetch the global remote target state. */
560 static struct remote_state *
561 get_remote_state (void)
563 /* Make sure that the remote architecture state has been
564 initialized, because doing so might reallocate rs->buf. Any
565 function which calls getpkt also needs to be mindful of changes
566 to rs->buf, but this call limits the number of places which run
568 get_remote_arch_state ();
570 return get_remote_state_raw ();
574 compare_pnums (const void *lhs_, const void *rhs_)
576 const struct packet_reg * const *lhs = lhs_;
577 const struct packet_reg * const *rhs = rhs_;
579 if ((*lhs)->pnum < (*rhs)->pnum)
581 else if ((*lhs)->pnum == (*rhs)->pnum)
588 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
590 int regnum, num_remote_regs, offset;
591 struct packet_reg **remote_regs;
593 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
595 struct packet_reg *r = ®s[regnum];
597 if (register_size (gdbarch, regnum) == 0)
598 /* Do not try to fetch zero-sized (placeholder) registers. */
601 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
606 /* Define the g/G packet format as the contents of each register
607 with a remote protocol number, in order of ascending protocol
610 remote_regs = alloca (gdbarch_num_regs (gdbarch)
611 * sizeof (struct packet_reg *));
612 for (num_remote_regs = 0, regnum = 0;
613 regnum < gdbarch_num_regs (gdbarch);
615 if (regs[regnum].pnum != -1)
616 remote_regs[num_remote_regs++] = ®s[regnum];
618 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
621 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
623 remote_regs[regnum]->in_g_packet = 1;
624 remote_regs[regnum]->offset = offset;
625 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
631 /* Given the architecture described by GDBARCH, return the remote
632 protocol register's number and the register's offset in the g/G
633 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
634 If the target does not have a mapping for REGNUM, return false,
635 otherwise, return true. */
638 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
639 int *pnum, int *poffset)
642 struct packet_reg *regs;
643 struct cleanup *old_chain;
645 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
647 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
648 old_chain = make_cleanup (xfree, regs);
650 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
652 *pnum = regs[regnum].pnum;
653 *poffset = regs[regnum].offset;
655 do_cleanups (old_chain);
661 init_remote_state (struct gdbarch *gdbarch)
663 struct remote_state *rs = get_remote_state_raw ();
664 struct remote_arch_state *rsa;
666 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
668 /* Use the architecture to build a regnum<->pnum table, which will be
669 1:1 unless a feature set specifies otherwise. */
670 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
671 gdbarch_num_regs (gdbarch),
674 /* Record the maximum possible size of the g packet - it may turn out
676 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
678 /* Default maximum number of characters in a packet body. Many
679 remote stubs have a hardwired buffer size of 400 bytes
680 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
681 as the maximum packet-size to ensure that the packet and an extra
682 NUL character can always fit in the buffer. This stops GDB
683 trashing stubs that try to squeeze an extra NUL into what is
684 already a full buffer (As of 1999-12-04 that was most stubs). */
685 rsa->remote_packet_size = 400 - 1;
687 /* This one is filled in when a ``g'' packet is received. */
688 rsa->actual_register_packet_size = 0;
690 /* Should rsa->sizeof_g_packet needs more space than the
691 default, adjust the size accordingly. Remember that each byte is
692 encoded as two characters. 32 is the overhead for the packet
693 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
694 (``$NN:G...#NN'') is a better guess, the below has been padded a
696 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
697 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
699 /* Make sure that the packet buffer is plenty big enough for
700 this architecture. */
701 if (rs->buf_size < rsa->remote_packet_size)
703 rs->buf_size = 2 * rsa->remote_packet_size;
704 rs->buf = xrealloc (rs->buf, rs->buf_size);
710 /* Return the current allowed size of a remote packet. This is
711 inferred from the current architecture, and should be used to
712 limit the length of outgoing packets. */
714 get_remote_packet_size (void)
716 struct remote_state *rs = get_remote_state ();
717 struct remote_arch_state *rsa = get_remote_arch_state ();
719 if (rs->explicit_packet_size)
720 return rs->explicit_packet_size;
722 return rsa->remote_packet_size;
725 static struct packet_reg *
726 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
728 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
732 struct packet_reg *r = &rsa->regs[regnum];
734 gdb_assert (r->regnum == regnum);
739 static struct packet_reg *
740 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
744 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
746 struct packet_reg *r = &rsa->regs[i];
754 static struct target_ops remote_ops;
756 static struct target_ops extended_remote_ops;
758 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
759 ``forever'' still use the normal timeout mechanism. This is
760 currently used by the ASYNC code to guarentee that target reads
761 during the initial connect always time-out. Once getpkt has been
762 modified to return a timeout indication and, in turn
763 remote_wait()/wait_for_inferior() have gained a timeout parameter
765 static int wait_forever_enabled_p = 1;
767 /* Allow the user to specify what sequence to send to the remote
768 when he requests a program interruption: Although ^C is usually
769 what remote systems expect (this is the default, here), it is
770 sometimes preferable to send a break. On other systems such
771 as the Linux kernel, a break followed by g, which is Magic SysRq g
772 is required in order to interrupt the execution. */
773 const char interrupt_sequence_control_c[] = "Ctrl-C";
774 const char interrupt_sequence_break[] = "BREAK";
775 const char interrupt_sequence_break_g[] = "BREAK-g";
776 static const char *const interrupt_sequence_modes[] =
778 interrupt_sequence_control_c,
779 interrupt_sequence_break,
780 interrupt_sequence_break_g,
783 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
786 show_interrupt_sequence (struct ui_file *file, int from_tty,
787 struct cmd_list_element *c,
790 if (interrupt_sequence_mode == interrupt_sequence_control_c)
791 fprintf_filtered (file,
792 _("Send the ASCII ETX character (Ctrl-c) "
793 "to the remote target to interrupt the "
794 "execution of the program.\n"));
795 else if (interrupt_sequence_mode == interrupt_sequence_break)
796 fprintf_filtered (file,
797 _("send a break signal to the remote target "
798 "to interrupt the execution of the program.\n"));
799 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
800 fprintf_filtered (file,
801 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
802 "the remote target to interrupt the execution "
803 "of Linux kernel.\n"));
805 internal_error (__FILE__, __LINE__,
806 _("Invalid value for interrupt_sequence_mode: %s."),
807 interrupt_sequence_mode);
810 /* This boolean variable specifies whether interrupt_sequence is sent
811 to the remote target when gdb connects to it.
812 This is mostly needed when you debug the Linux kernel: The Linux kernel
813 expects BREAK g which is Magic SysRq g for connecting gdb. */
814 static int interrupt_on_connect = 0;
816 /* This variable is used to implement the "set/show remotebreak" commands.
817 Since these commands are now deprecated in favor of "set/show remote
818 interrupt-sequence", it no longer has any effect on the code. */
819 static int remote_break;
822 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
825 interrupt_sequence_mode = interrupt_sequence_break;
827 interrupt_sequence_mode = interrupt_sequence_control_c;
831 show_remotebreak (struct ui_file *file, int from_tty,
832 struct cmd_list_element *c,
837 /* This variable sets the number of bits in an address that are to be
838 sent in a memory ("M" or "m") packet. Normally, after stripping
839 leading zeros, the entire address would be sent. This variable
840 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
841 initial implementation of remote.c restricted the address sent in
842 memory packets to ``host::sizeof long'' bytes - (typically 32
843 bits). Consequently, for 64 bit targets, the upper 32 bits of an
844 address was never sent. Since fixing this bug may cause a break in
845 some remote targets this variable is principly provided to
846 facilitate backward compatibility. */
848 static unsigned int remote_address_size;
850 /* Temporary to track who currently owns the terminal. See
851 remote_terminal_* for more details. */
853 static int remote_async_terminal_ours_p;
855 /* The executable file to use for "run" on the remote side. */
857 static char *remote_exec_file = "";
860 /* User configurable variables for the number of characters in a
861 memory read/write packet. MIN (rsa->remote_packet_size,
862 rsa->sizeof_g_packet) is the default. Some targets need smaller
863 values (fifo overruns, et.al.) and some users need larger values
864 (speed up transfers). The variables ``preferred_*'' (the user
865 request), ``current_*'' (what was actually set) and ``forced_*''
866 (Positive - a soft limit, negative - a hard limit). */
868 struct memory_packet_config
875 /* Compute the current size of a read/write packet. Since this makes
876 use of ``actual_register_packet_size'' the computation is dynamic. */
879 get_memory_packet_size (struct memory_packet_config *config)
881 struct remote_state *rs = get_remote_state ();
882 struct remote_arch_state *rsa = get_remote_arch_state ();
884 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
885 law?) that some hosts don't cope very well with large alloca()
886 calls. Eventually the alloca() code will be replaced by calls to
887 xmalloc() and make_cleanups() allowing this restriction to either
888 be lifted or removed. */
889 #ifndef MAX_REMOTE_PACKET_SIZE
890 #define MAX_REMOTE_PACKET_SIZE 16384
892 /* NOTE: 20 ensures we can write at least one byte. */
893 #ifndef MIN_REMOTE_PACKET_SIZE
894 #define MIN_REMOTE_PACKET_SIZE 20
899 if (config->size <= 0)
900 what_they_get = MAX_REMOTE_PACKET_SIZE;
902 what_they_get = config->size;
906 what_they_get = get_remote_packet_size ();
907 /* Limit the packet to the size specified by the user. */
909 && what_they_get > config->size)
910 what_they_get = config->size;
912 /* Limit it to the size of the targets ``g'' response unless we have
913 permission from the stub to use a larger packet size. */
914 if (rs->explicit_packet_size == 0
915 && rsa->actual_register_packet_size > 0
916 && what_they_get > rsa->actual_register_packet_size)
917 what_they_get = rsa->actual_register_packet_size;
919 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
920 what_they_get = MAX_REMOTE_PACKET_SIZE;
921 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
922 what_they_get = MIN_REMOTE_PACKET_SIZE;
924 /* Make sure there is room in the global buffer for this packet
925 (including its trailing NUL byte). */
926 if (rs->buf_size < what_they_get + 1)
928 rs->buf_size = 2 * what_they_get;
929 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
932 return what_they_get;
935 /* Update the size of a read/write packet. If they user wants
936 something really big then do a sanity check. */
939 set_memory_packet_size (char *args, struct memory_packet_config *config)
941 int fixed_p = config->fixed_p;
942 long size = config->size;
945 error (_("Argument required (integer, `fixed' or `limited')."));
946 else if (strcmp (args, "hard") == 0
947 || strcmp (args, "fixed") == 0)
949 else if (strcmp (args, "soft") == 0
950 || strcmp (args, "limit") == 0)
956 size = strtoul (args, &end, 0);
958 error (_("Invalid %s (bad syntax)."), config->name);
960 /* Instead of explicitly capping the size of a packet to
961 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
962 instead allowed to set the size to something arbitrarily
964 if (size > MAX_REMOTE_PACKET_SIZE)
965 error (_("Invalid %s (too large)."), config->name);
969 if (fixed_p && !config->fixed_p)
971 if (! query (_("The target may not be able to correctly handle a %s\n"
972 "of %ld bytes. Change the packet size? "),
974 error (_("Packet size not changed."));
976 /* Update the config. */
977 config->fixed_p = fixed_p;
982 show_memory_packet_size (struct memory_packet_config *config)
984 printf_filtered (_("The %s is %ld. "), config->name, config->size);
986 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
987 get_memory_packet_size (config));
989 printf_filtered (_("Packets are limited to %ld bytes.\n"),
990 get_memory_packet_size (config));
993 static struct memory_packet_config memory_write_packet_config =
995 "memory-write-packet-size",
999 set_memory_write_packet_size (char *args, int from_tty)
1001 set_memory_packet_size (args, &memory_write_packet_config);
1005 show_memory_write_packet_size (char *args, int from_tty)
1007 show_memory_packet_size (&memory_write_packet_config);
1011 get_memory_write_packet_size (void)
1013 return get_memory_packet_size (&memory_write_packet_config);
1016 static struct memory_packet_config memory_read_packet_config =
1018 "memory-read-packet-size",
1022 set_memory_read_packet_size (char *args, int from_tty)
1024 set_memory_packet_size (args, &memory_read_packet_config);
1028 show_memory_read_packet_size (char *args, int from_tty)
1030 show_memory_packet_size (&memory_read_packet_config);
1034 get_memory_read_packet_size (void)
1036 long size = get_memory_packet_size (&memory_read_packet_config);
1038 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1039 extra buffer size argument before the memory read size can be
1040 increased beyond this. */
1041 if (size > get_remote_packet_size ())
1042 size = get_remote_packet_size ();
1047 /* Generic configuration support for packets the stub optionally
1048 supports. Allows the user to specify the use of the packet as well
1049 as allowing GDB to auto-detect support in the remote stub. */
1053 PACKET_SUPPORT_UNKNOWN = 0,
1058 struct packet_config
1063 /* If auto, GDB auto-detects support for this packet or feature,
1064 either through qSupported, or by trying the packet and looking
1065 at the response. If true, GDB assumes the target supports this
1066 packet. If false, the packet is disabled. Configs that don't
1067 have an associated command always have this set to auto. */
1068 enum auto_boolean detect;
1070 /* Does the target support this packet? */
1071 enum packet_support support;
1074 /* Analyze a packet's return value and update the packet config
1084 static enum packet_support packet_config_support (struct packet_config *config);
1085 static enum packet_support packet_support (int packet);
1088 show_packet_config_cmd (struct packet_config *config)
1090 char *support = "internal-error";
1092 switch (packet_config_support (config))
1095 support = "enabled";
1097 case PACKET_DISABLE:
1098 support = "disabled";
1100 case PACKET_SUPPORT_UNKNOWN:
1101 support = "unknown";
1104 switch (config->detect)
1106 case AUTO_BOOLEAN_AUTO:
1107 printf_filtered (_("Support for the `%s' packet "
1108 "is auto-detected, currently %s.\n"),
1109 config->name, support);
1111 case AUTO_BOOLEAN_TRUE:
1112 case AUTO_BOOLEAN_FALSE:
1113 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1114 config->name, support);
1120 add_packet_config_cmd (struct packet_config *config, const char *name,
1121 const char *title, int legacy)
1127 config->name = name;
1128 config->title = title;
1129 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1131 show_doc = xstrprintf ("Show current use of remote "
1132 "protocol `%s' (%s) packet",
1134 /* set/show TITLE-packet {auto,on,off} */
1135 cmd_name = xstrprintf ("%s-packet", title);
1136 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1137 &config->detect, set_doc,
1138 show_doc, NULL, /* help_doc */
1140 show_remote_protocol_packet_cmd,
1141 &remote_set_cmdlist, &remote_show_cmdlist);
1142 /* The command code copies the documentation strings. */
1145 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1150 legacy_name = xstrprintf ("%s-packet", name);
1151 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1152 &remote_set_cmdlist);
1153 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1154 &remote_show_cmdlist);
1158 static enum packet_result
1159 packet_check_result (const char *buf)
1163 /* The stub recognized the packet request. Check that the
1164 operation succeeded. */
1166 && isxdigit (buf[1]) && isxdigit (buf[2])
1168 /* "Enn" - definitly an error. */
1169 return PACKET_ERROR;
1171 /* Always treat "E." as an error. This will be used for
1172 more verbose error messages, such as E.memtypes. */
1173 if (buf[0] == 'E' && buf[1] == '.')
1174 return PACKET_ERROR;
1176 /* The packet may or may not be OK. Just assume it is. */
1180 /* The stub does not support the packet. */
1181 return PACKET_UNKNOWN;
1184 static enum packet_result
1185 packet_ok (const char *buf, struct packet_config *config)
1187 enum packet_result result;
1189 if (config->detect != AUTO_BOOLEAN_TRUE
1190 && config->support == PACKET_DISABLE)
1191 internal_error (__FILE__, __LINE__,
1192 _("packet_ok: attempt to use a disabled packet"));
1194 result = packet_check_result (buf);
1199 /* The stub recognized the packet request. */
1200 if (config->support == PACKET_SUPPORT_UNKNOWN)
1203 fprintf_unfiltered (gdb_stdlog,
1204 "Packet %s (%s) is supported\n",
1205 config->name, config->title);
1206 config->support = PACKET_ENABLE;
1209 case PACKET_UNKNOWN:
1210 /* The stub does not support the packet. */
1211 if (config->detect == AUTO_BOOLEAN_AUTO
1212 && config->support == PACKET_ENABLE)
1214 /* If the stub previously indicated that the packet was
1215 supported then there is a protocol error. */
1216 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1217 config->name, config->title);
1219 else if (config->detect == AUTO_BOOLEAN_TRUE)
1221 /* The user set it wrong. */
1222 error (_("Enabled packet %s (%s) not recognized by stub"),
1223 config->name, config->title);
1227 fprintf_unfiltered (gdb_stdlog,
1228 "Packet %s (%s) is NOT supported\n",
1229 config->name, config->title);
1230 config->support = PACKET_DISABLE;
1250 PACKET_vFile_pwrite,
1252 PACKET_vFile_unlink,
1253 PACKET_vFile_readlink,
1256 PACKET_qXfer_features,
1257 PACKET_qXfer_libraries,
1258 PACKET_qXfer_libraries_svr4,
1259 PACKET_qXfer_memory_map,
1260 PACKET_qXfer_spu_read,
1261 PACKET_qXfer_spu_write,
1262 PACKET_qXfer_osdata,
1263 PACKET_qXfer_threads,
1264 PACKET_qXfer_statictrace_read,
1265 PACKET_qXfer_traceframe_info,
1271 PACKET_QPassSignals,
1272 PACKET_QProgramSignals,
1274 PACKET_qSearch_memory,
1277 PACKET_QStartNoAckMode,
1279 PACKET_qXfer_siginfo_read,
1280 PACKET_qXfer_siginfo_write,
1283 /* Support for conditional tracepoints. */
1284 PACKET_ConditionalTracepoints,
1286 /* Support for target-side breakpoint conditions. */
1287 PACKET_ConditionalBreakpoints,
1289 /* Support for target-side breakpoint commands. */
1290 PACKET_BreakpointCommands,
1292 /* Support for fast tracepoints. */
1293 PACKET_FastTracepoints,
1295 /* Support for static tracepoints. */
1296 PACKET_StaticTracepoints,
1298 /* Support for installing tracepoints while a trace experiment is
1300 PACKET_InstallInTrace,
1304 PACKET_TracepointSource,
1307 PACKET_QDisableRandomization,
1309 PACKET_QTBuffer_size,
1312 PACKET_qXfer_btrace,
1314 /* Support for the QNonStop packet. */
1317 /* Support for multi-process extensions. */
1318 PACKET_multiprocess_feature,
1320 /* Support for enabling and disabling tracepoints while a trace
1321 experiment is running. */
1322 PACKET_EnableDisableTracepoints_feature,
1324 /* Support for collecting strings using the tracenz bytecode. */
1325 PACKET_tracenz_feature,
1327 /* Support for continuing to run a trace experiment while GDB is
1329 PACKET_DisconnectedTracing_feature,
1331 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1332 PACKET_augmented_libraries_svr4_read_feature,
1334 /* Support for the qXfer:btrace-conf:read packet. */
1335 PACKET_qXfer_btrace_conf,
1337 /* Support for the Qbtrace-conf:bts:size packet. */
1338 PACKET_Qbtrace_conf_bts_size,
1340 /* Support for swbreak+ feature. */
1341 PACKET_swbreak_feature,
1343 /* Support for hwbreak+ feature. */
1344 PACKET_hwbreak_feature,
1349 static struct packet_config remote_protocol_packets[PACKET_MAX];
1351 /* Returns the packet's corresponding "set remote foo-packet" command
1352 state. See struct packet_config for more details. */
1354 static enum auto_boolean
1355 packet_set_cmd_state (int packet)
1357 return remote_protocol_packets[packet].detect;
1360 /* Returns whether a given packet or feature is supported. This takes
1361 into account the state of the corresponding "set remote foo-packet"
1362 command, which may be used to bypass auto-detection. */
1364 static enum packet_support
1365 packet_config_support (struct packet_config *config)
1367 switch (config->detect)
1369 case AUTO_BOOLEAN_TRUE:
1370 return PACKET_ENABLE;
1371 case AUTO_BOOLEAN_FALSE:
1372 return PACKET_DISABLE;
1373 case AUTO_BOOLEAN_AUTO:
1374 return config->support;
1376 gdb_assert_not_reached (_("bad switch"));
1380 /* Same as packet_config_support, but takes the packet's enum value as
1383 static enum packet_support
1384 packet_support (int packet)
1386 struct packet_config *config = &remote_protocol_packets[packet];
1388 return packet_config_support (config);
1392 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1393 struct cmd_list_element *c,
1396 struct packet_config *packet;
1398 for (packet = remote_protocol_packets;
1399 packet < &remote_protocol_packets[PACKET_MAX];
1402 if (&packet->detect == c->var)
1404 show_packet_config_cmd (packet);
1408 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1412 /* Should we try one of the 'Z' requests? */
1416 Z_PACKET_SOFTWARE_BP,
1417 Z_PACKET_HARDWARE_BP,
1424 /* For compatibility with older distributions. Provide a ``set remote
1425 Z-packet ...'' command that updates all the Z packet types. */
1427 static enum auto_boolean remote_Z_packet_detect;
1430 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1431 struct cmd_list_element *c)
1435 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1436 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1440 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1441 struct cmd_list_element *c,
1446 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1448 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1452 /* Returns true if the multi-process extensions are in effect. */
1455 remote_multi_process_p (struct remote_state *rs)
1457 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1460 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1461 static struct async_signal_handler *async_sigint_remote_twice_token;
1462 static struct async_signal_handler *async_sigint_remote_token;
1465 /* Asynchronous signal handle registered as event loop source for
1466 when we have pending events ready to be passed to the core. */
1468 static struct async_event_handler *remote_async_inferior_event_token;
1472 static ptid_t magic_null_ptid;
1473 static ptid_t not_sent_ptid;
1474 static ptid_t any_thread_ptid;
1476 /* Find out if the stub attached to PID (and hence GDB should offer to
1477 detach instead of killing it when bailing out). */
1480 remote_query_attached (int pid)
1482 struct remote_state *rs = get_remote_state ();
1483 size_t size = get_remote_packet_size ();
1485 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1488 if (remote_multi_process_p (rs))
1489 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1491 xsnprintf (rs->buf, size, "qAttached");
1494 getpkt (&rs->buf, &rs->buf_size, 0);
1496 switch (packet_ok (rs->buf,
1497 &remote_protocol_packets[PACKET_qAttached]))
1500 if (strcmp (rs->buf, "1") == 0)
1504 warning (_("Remote failure reply: %s"), rs->buf);
1506 case PACKET_UNKNOWN:
1513 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1514 has been invented by GDB, instead of reported by the target. Since
1515 we can be connected to a remote system before before knowing about
1516 any inferior, mark the target with execution when we find the first
1517 inferior. If ATTACHED is 1, then we had just attached to this
1518 inferior. If it is 0, then we just created this inferior. If it
1519 is -1, then try querying the remote stub to find out if it had
1520 attached to the inferior or not. */
1522 static struct inferior *
1523 remote_add_inferior (int fake_pid_p, int pid, int attached)
1525 struct inferior *inf;
1527 /* Check whether this process we're learning about is to be
1528 considered attached, or if is to be considered to have been
1529 spawned by the stub. */
1531 attached = remote_query_attached (pid);
1533 if (gdbarch_has_global_solist (target_gdbarch ()))
1535 /* If the target shares code across all inferiors, then every
1536 attach adds a new inferior. */
1537 inf = add_inferior (pid);
1539 /* ... and every inferior is bound to the same program space.
1540 However, each inferior may still have its own address
1542 inf->aspace = maybe_new_address_space ();
1543 inf->pspace = current_program_space;
1547 /* In the traditional debugging scenario, there's a 1-1 match
1548 between program/address spaces. We simply bind the inferior
1549 to the program space's address space. */
1550 inf = current_inferior ();
1551 inferior_appeared (inf, pid);
1554 inf->attach_flag = attached;
1555 inf->fake_pid_p = fake_pid_p;
1560 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1561 according to RUNNING. */
1564 remote_add_thread (ptid_t ptid, int running)
1566 struct remote_state *rs = get_remote_state ();
1568 /* GDB historically didn't pull threads in the initial connection
1569 setup. If the remote target doesn't even have a concept of
1570 threads (e.g., a bare-metal target), even if internally we
1571 consider that a single-threaded target, mentioning a new thread
1572 might be confusing to the user. Be silent then, preserving the
1573 age old behavior. */
1574 if (rs->starting_up)
1575 add_thread_silent (ptid);
1579 set_executing (ptid, running);
1580 set_running (ptid, running);
1583 /* Come here when we learn about a thread id from the remote target.
1584 It may be the first time we hear about such thread, so take the
1585 opportunity to add it to GDB's thread list. In case this is the
1586 first time we're noticing its corresponding inferior, add it to
1587 GDB's inferior list as well. */
1590 remote_notice_new_inferior (ptid_t currthread, int running)
1592 /* If this is a new thread, add it to GDB's thread list.
1593 If we leave it up to WFI to do this, bad things will happen. */
1595 if (in_thread_list (currthread) && is_exited (currthread))
1597 /* We're seeing an event on a thread id we knew had exited.
1598 This has to be a new thread reusing the old id. Add it. */
1599 remote_add_thread (currthread, running);
1603 if (!in_thread_list (currthread))
1605 struct inferior *inf = NULL;
1606 int pid = ptid_get_pid (currthread);
1608 if (ptid_is_pid (inferior_ptid)
1609 && pid == ptid_get_pid (inferior_ptid))
1611 /* inferior_ptid has no thread member yet. This can happen
1612 with the vAttach -> remote_wait,"TAAthread:" path if the
1613 stub doesn't support qC. This is the first stop reported
1614 after an attach, so this is the main thread. Update the
1615 ptid in the thread list. */
1616 if (in_thread_list (pid_to_ptid (pid)))
1617 thread_change_ptid (inferior_ptid, currthread);
1620 remote_add_thread (currthread, running);
1621 inferior_ptid = currthread;
1626 if (ptid_equal (magic_null_ptid, inferior_ptid))
1628 /* inferior_ptid is not set yet. This can happen with the
1629 vRun -> remote_wait,"TAAthread:" path if the stub
1630 doesn't support qC. This is the first stop reported
1631 after an attach, so this is the main thread. Update the
1632 ptid in the thread list. */
1633 thread_change_ptid (inferior_ptid, currthread);
1637 /* When connecting to a target remote, or to a target
1638 extended-remote which already was debugging an inferior, we
1639 may not know about it yet. Add it before adding its child
1640 thread, so notifications are emitted in a sensible order. */
1641 if (!in_inferior_list (ptid_get_pid (currthread)))
1643 struct remote_state *rs = get_remote_state ();
1644 int fake_pid_p = !remote_multi_process_p (rs);
1646 inf = remote_add_inferior (fake_pid_p,
1647 ptid_get_pid (currthread), -1);
1650 /* This is really a new thread. Add it. */
1651 remote_add_thread (currthread, running);
1653 /* If we found a new inferior, let the common code do whatever
1654 it needs to with it (e.g., read shared libraries, insert
1655 breakpoints), unless we're just setting up an all-stop
1659 struct remote_state *rs = get_remote_state ();
1661 if (non_stop || !rs->starting_up)
1662 notice_new_inferior (currthread, running, 0);
1667 /* Return the private thread data, creating it if necessary. */
1669 static struct private_thread_info *
1670 demand_private_info (ptid_t ptid)
1672 struct thread_info *info = find_thread_ptid (ptid);
1678 info->priv = xmalloc (sizeof (*(info->priv)));
1679 info->private_dtor = free_private_thread_info;
1680 info->priv->core = -1;
1681 info->priv->extra = 0;
1687 /* Call this function as a result of
1688 1) A halt indication (T packet) containing a thread id
1689 2) A direct query of currthread
1690 3) Successful execution of set thread */
1693 record_currthread (struct remote_state *rs, ptid_t currthread)
1695 rs->general_thread = currthread;
1698 /* If 'QPassSignals' is supported, tell the remote stub what signals
1699 it can simply pass through to the inferior without reporting. */
1702 remote_pass_signals (struct target_ops *self,
1703 int numsigs, unsigned char *pass_signals)
1705 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1707 char *pass_packet, *p;
1709 struct remote_state *rs = get_remote_state ();
1711 gdb_assert (numsigs < 256);
1712 for (i = 0; i < numsigs; i++)
1714 if (pass_signals[i])
1717 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1718 strcpy (pass_packet, "QPassSignals:");
1719 p = pass_packet + strlen (pass_packet);
1720 for (i = 0; i < numsigs; i++)
1722 if (pass_signals[i])
1725 *p++ = tohex (i >> 4);
1726 *p++ = tohex (i & 15);
1735 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1737 putpkt (pass_packet);
1738 getpkt (&rs->buf, &rs->buf_size, 0);
1739 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1740 if (rs->last_pass_packet)
1741 xfree (rs->last_pass_packet);
1742 rs->last_pass_packet = pass_packet;
1745 xfree (pass_packet);
1749 /* If 'QProgramSignals' is supported, tell the remote stub what
1750 signals it should pass through to the inferior when detaching. */
1753 remote_program_signals (struct target_ops *self,
1754 int numsigs, unsigned char *signals)
1756 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1760 struct remote_state *rs = get_remote_state ();
1762 gdb_assert (numsigs < 256);
1763 for (i = 0; i < numsigs; i++)
1768 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1769 strcpy (packet, "QProgramSignals:");
1770 p = packet + strlen (packet);
1771 for (i = 0; i < numsigs; i++)
1773 if (signal_pass_state (i))
1776 *p++ = tohex (i >> 4);
1777 *p++ = tohex (i & 15);
1786 if (!rs->last_program_signals_packet
1787 || strcmp (rs->last_program_signals_packet, packet) != 0)
1790 getpkt (&rs->buf, &rs->buf_size, 0);
1791 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1792 xfree (rs->last_program_signals_packet);
1793 rs->last_program_signals_packet = packet;
1800 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1801 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1802 thread. If GEN is set, set the general thread, if not, then set
1803 the step/continue thread. */
1805 set_thread (struct ptid ptid, int gen)
1807 struct remote_state *rs = get_remote_state ();
1808 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1809 char *buf = rs->buf;
1810 char *endbuf = rs->buf + get_remote_packet_size ();
1812 if (ptid_equal (state, ptid))
1816 *buf++ = gen ? 'g' : 'c';
1817 if (ptid_equal (ptid, magic_null_ptid))
1818 xsnprintf (buf, endbuf - buf, "0");
1819 else if (ptid_equal (ptid, any_thread_ptid))
1820 xsnprintf (buf, endbuf - buf, "0");
1821 else if (ptid_equal (ptid, minus_one_ptid))
1822 xsnprintf (buf, endbuf - buf, "-1");
1824 write_ptid (buf, endbuf, ptid);
1826 getpkt (&rs->buf, &rs->buf_size, 0);
1828 rs->general_thread = ptid;
1830 rs->continue_thread = ptid;
1834 set_general_thread (struct ptid ptid)
1836 set_thread (ptid, 1);
1840 set_continue_thread (struct ptid ptid)
1842 set_thread (ptid, 0);
1845 /* Change the remote current process. Which thread within the process
1846 ends up selected isn't important, as long as it is the same process
1847 as what INFERIOR_PTID points to.
1849 This comes from that fact that there is no explicit notion of
1850 "selected process" in the protocol. The selected process for
1851 general operations is the process the selected general thread
1855 set_general_process (void)
1857 struct remote_state *rs = get_remote_state ();
1859 /* If the remote can't handle multiple processes, don't bother. */
1860 if (!rs->extended || !remote_multi_process_p (rs))
1863 /* We only need to change the remote current thread if it's pointing
1864 at some other process. */
1865 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1866 set_general_thread (inferior_ptid);
1870 /* Return nonzero if this is the main thread that we made up ourselves
1871 to model non-threaded targets as single-threaded. */
1874 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1876 struct remote_state *rs = get_remote_state ();
1879 if (ptid_equal (ptid, magic_null_ptid))
1880 /* The main thread is always alive. */
1883 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
1884 /* The main thread is always alive. This can happen after a
1885 vAttach, if the remote side doesn't support
1892 /* Return nonzero if the thread PTID is still alive on the remote
1896 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1898 struct remote_state *rs = get_remote_state ();
1901 /* Check if this is a thread that we made up ourselves to model
1902 non-threaded targets as single-threaded. */
1903 if (remote_thread_always_alive (ops, ptid))
1907 endp = rs->buf + get_remote_packet_size ();
1910 write_ptid (p, endp, ptid);
1913 getpkt (&rs->buf, &rs->buf_size, 0);
1914 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1917 /* About these extended threadlist and threadinfo packets. They are
1918 variable length packets but, the fields within them are often fixed
1919 length. They are redundent enough to send over UDP as is the
1920 remote protocol in general. There is a matching unit test module
1923 /* WARNING: This threadref data structure comes from the remote O.S.,
1924 libstub protocol encoding, and remote.c. It is not particularly
1927 /* Right now, the internal structure is int. We want it to be bigger.
1928 Plan to fix this. */
1930 typedef int gdb_threadref; /* Internal GDB thread reference. */
1932 /* gdb_ext_thread_info is an internal GDB data structure which is
1933 equivalent to the reply of the remote threadinfo packet. */
1935 struct gdb_ext_thread_info
1937 threadref threadid; /* External form of thread reference. */
1938 int active; /* Has state interesting to GDB?
1940 char display[256]; /* Brief state display, name,
1941 blocked/suspended. */
1942 char shortname[32]; /* To be used to name threads. */
1943 char more_display[256]; /* Long info, statistics, queue depth,
1947 /* The volume of remote transfers can be limited by submitting
1948 a mask containing bits specifying the desired information.
1949 Use a union of these values as the 'selection' parameter to
1950 get_thread_info. FIXME: Make these TAG names more thread specific. */
1952 #define TAG_THREADID 1
1953 #define TAG_EXISTS 2
1954 #define TAG_DISPLAY 4
1955 #define TAG_THREADNAME 8
1956 #define TAG_MOREDISPLAY 16
1958 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1960 static char *unpack_nibble (char *buf, int *val);
1962 static char *unpack_byte (char *buf, int *value);
1964 static char *pack_int (char *buf, int value);
1966 static char *unpack_int (char *buf, int *value);
1968 static char *unpack_string (char *src, char *dest, int length);
1970 static char *pack_threadid (char *pkt, threadref *id);
1972 static char *unpack_threadid (char *inbuf, threadref *id);
1974 void int_to_threadref (threadref *id, int value);
1976 static int threadref_to_int (threadref *ref);
1978 static void copy_threadref (threadref *dest, threadref *src);
1980 static int threadmatch (threadref *dest, threadref *src);
1982 static char *pack_threadinfo_request (char *pkt, int mode,
1985 static int remote_unpack_thread_info_response (char *pkt,
1986 threadref *expectedref,
1987 struct gdb_ext_thread_info
1991 static int remote_get_threadinfo (threadref *threadid,
1992 int fieldset, /*TAG mask */
1993 struct gdb_ext_thread_info *info);
1995 static char *pack_threadlist_request (char *pkt, int startflag,
1997 threadref *nextthread);
1999 static int parse_threadlist_response (char *pkt,
2001 threadref *original_echo,
2002 threadref *resultlist,
2005 static int remote_get_threadlist (int startflag,
2006 threadref *nextthread,
2010 threadref *threadlist);
2012 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2014 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2015 void *context, int looplimit);
2017 static int remote_newthread_step (threadref *ref, void *context);
2020 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2021 buffer we're allowed to write to. Returns
2022 BUF+CHARACTERS_WRITTEN. */
2025 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2028 struct remote_state *rs = get_remote_state ();
2030 if (remote_multi_process_p (rs))
2032 pid = ptid_get_pid (ptid);
2034 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2036 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2038 tid = ptid_get_lwp (ptid);
2040 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2042 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2047 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2048 passed the last parsed char. Returns null_ptid on error. */
2051 read_ptid (char *buf, char **obuf)
2055 ULONGEST pid = 0, tid = 0;
2059 /* Multi-process ptid. */
2060 pp = unpack_varlen_hex (p + 1, &pid);
2062 error (_("invalid remote ptid: %s"), p);
2065 pp = unpack_varlen_hex (p + 1, &tid);
2068 return ptid_build (pid, tid, 0);
2071 /* No multi-process. Just a tid. */
2072 pp = unpack_varlen_hex (p, &tid);
2074 /* Since the stub is not sending a process id, then default to
2075 what's in inferior_ptid, unless it's null at this point. If so,
2076 then since there's no way to know the pid of the reported
2077 threads, use the magic number. */
2078 if (ptid_equal (inferior_ptid, null_ptid))
2079 pid = ptid_get_pid (magic_null_ptid);
2081 pid = ptid_get_pid (inferior_ptid);
2085 return ptid_build (pid, tid, 0);
2091 if (ch >= 'a' && ch <= 'f')
2092 return ch - 'a' + 10;
2093 if (ch >= '0' && ch <= '9')
2095 if (ch >= 'A' && ch <= 'F')
2096 return ch - 'A' + 10;
2101 stub_unpack_int (char *buff, int fieldlength)
2108 nibble = stubhex (*buff++);
2112 retval = retval << 4;
2118 unpack_nibble (char *buf, int *val)
2120 *val = fromhex (*buf++);
2125 unpack_byte (char *buf, int *value)
2127 *value = stub_unpack_int (buf, 2);
2132 pack_int (char *buf, int value)
2134 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2135 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2136 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2137 buf = pack_hex_byte (buf, (value & 0xff));
2142 unpack_int (char *buf, int *value)
2144 *value = stub_unpack_int (buf, 8);
2148 #if 0 /* Currently unused, uncomment when needed. */
2149 static char *pack_string (char *pkt, char *string);
2152 pack_string (char *pkt, char *string)
2157 len = strlen (string);
2159 len = 200; /* Bigger than most GDB packets, junk??? */
2160 pkt = pack_hex_byte (pkt, len);
2164 if ((ch == '\0') || (ch == '#'))
2165 ch = '*'; /* Protect encapsulation. */
2170 #endif /* 0 (unused) */
2173 unpack_string (char *src, char *dest, int length)
2182 pack_threadid (char *pkt, threadref *id)
2185 unsigned char *altid;
2187 altid = (unsigned char *) id;
2188 limit = pkt + BUF_THREAD_ID_SIZE;
2190 pkt = pack_hex_byte (pkt, *altid++);
2196 unpack_threadid (char *inbuf, threadref *id)
2199 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2202 altref = (char *) id;
2204 while (inbuf < limit)
2206 x = stubhex (*inbuf++);
2207 y = stubhex (*inbuf++);
2208 *altref++ = (x << 4) | y;
2213 /* Externally, threadrefs are 64 bits but internally, they are still
2214 ints. This is due to a mismatch of specifications. We would like
2215 to use 64bit thread references internally. This is an adapter
2219 int_to_threadref (threadref *id, int value)
2221 unsigned char *scan;
2223 scan = (unsigned char *) id;
2229 *scan++ = (value >> 24) & 0xff;
2230 *scan++ = (value >> 16) & 0xff;
2231 *scan++ = (value >> 8) & 0xff;
2232 *scan++ = (value & 0xff);
2236 threadref_to_int (threadref *ref)
2239 unsigned char *scan;
2245 value = (value << 8) | ((*scan++) & 0xff);
2250 copy_threadref (threadref *dest, threadref *src)
2253 unsigned char *csrc, *cdest;
2255 csrc = (unsigned char *) src;
2256 cdest = (unsigned char *) dest;
2263 threadmatch (threadref *dest, threadref *src)
2265 /* Things are broken right now, so just assume we got a match. */
2267 unsigned char *srcp, *destp;
2269 srcp = (char *) src;
2270 destp = (char *) dest;
2274 result &= (*srcp++ == *destp++) ? 1 : 0;
2281 threadid:1, # always request threadid
2288 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2291 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2293 *pkt++ = 'q'; /* Info Query */
2294 *pkt++ = 'P'; /* process or thread info */
2295 pkt = pack_int (pkt, mode); /* mode */
2296 pkt = pack_threadid (pkt, id); /* threadid */
2297 *pkt = '\0'; /* terminate */
2301 /* These values tag the fields in a thread info response packet. */
2302 /* Tagging the fields allows us to request specific fields and to
2303 add more fields as time goes by. */
2305 #define TAG_THREADID 1 /* Echo the thread identifier. */
2306 #define TAG_EXISTS 2 /* Is this process defined enough to
2307 fetch registers and its stack? */
2308 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2309 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2310 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2314 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2315 struct gdb_ext_thread_info *info)
2317 struct remote_state *rs = get_remote_state ();
2321 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2324 /* info->threadid = 0; FIXME: implement zero_threadref. */
2326 info->display[0] = '\0';
2327 info->shortname[0] = '\0';
2328 info->more_display[0] = '\0';
2330 /* Assume the characters indicating the packet type have been
2332 pkt = unpack_int (pkt, &mask); /* arg mask */
2333 pkt = unpack_threadid (pkt, &ref);
2336 warning (_("Incomplete response to threadinfo request."));
2337 if (!threadmatch (&ref, expectedref))
2338 { /* This is an answer to a different request. */
2339 warning (_("ERROR RMT Thread info mismatch."));
2342 copy_threadref (&info->threadid, &ref);
2344 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2346 /* Packets are terminated with nulls. */
2347 while ((pkt < limit) && mask && *pkt)
2349 pkt = unpack_int (pkt, &tag); /* tag */
2350 pkt = unpack_byte (pkt, &length); /* length */
2351 if (!(tag & mask)) /* Tags out of synch with mask. */
2353 warning (_("ERROR RMT: threadinfo tag mismatch."));
2357 if (tag == TAG_THREADID)
2361 warning (_("ERROR RMT: length of threadid is not 16."));
2365 pkt = unpack_threadid (pkt, &ref);
2366 mask = mask & ~TAG_THREADID;
2369 if (tag == TAG_EXISTS)
2371 info->active = stub_unpack_int (pkt, length);
2373 mask = mask & ~(TAG_EXISTS);
2376 warning (_("ERROR RMT: 'exists' length too long."));
2382 if (tag == TAG_THREADNAME)
2384 pkt = unpack_string (pkt, &info->shortname[0], length);
2385 mask = mask & ~TAG_THREADNAME;
2388 if (tag == TAG_DISPLAY)
2390 pkt = unpack_string (pkt, &info->display[0], length);
2391 mask = mask & ~TAG_DISPLAY;
2394 if (tag == TAG_MOREDISPLAY)
2396 pkt = unpack_string (pkt, &info->more_display[0], length);
2397 mask = mask & ~TAG_MOREDISPLAY;
2400 warning (_("ERROR RMT: unknown thread info tag."));
2401 break; /* Not a tag we know about. */
2407 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2408 struct gdb_ext_thread_info *info)
2410 struct remote_state *rs = get_remote_state ();
2413 pack_threadinfo_request (rs->buf, fieldset, threadid);
2415 getpkt (&rs->buf, &rs->buf_size, 0);
2417 if (rs->buf[0] == '\0')
2420 result = remote_unpack_thread_info_response (rs->buf + 2,
2425 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2428 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2429 threadref *nextthread)
2431 *pkt++ = 'q'; /* info query packet */
2432 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2433 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2434 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2435 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2440 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2443 parse_threadlist_response (char *pkt, int result_limit,
2444 threadref *original_echo, threadref *resultlist,
2447 struct remote_state *rs = get_remote_state ();
2449 int count, resultcount, done;
2452 /* Assume the 'q' and 'M chars have been stripped. */
2453 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2454 /* done parse past here */
2455 pkt = unpack_byte (pkt, &count); /* count field */
2456 pkt = unpack_nibble (pkt, &done);
2457 /* The first threadid is the argument threadid. */
2458 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2459 while ((count-- > 0) && (pkt < limit))
2461 pkt = unpack_threadid (pkt, resultlist++);
2462 if (resultcount++ >= result_limit)
2470 /* Fetch the next batch of threads from the remote. Returns -1 if the
2471 qL packet is not supported, 0 on error and 1 on success. */
2474 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2475 int *done, int *result_count, threadref *threadlist)
2477 struct remote_state *rs = get_remote_state ();
2480 /* Trancate result limit to be smaller than the packet size. */
2481 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2482 >= get_remote_packet_size ())
2483 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2485 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2487 getpkt (&rs->buf, &rs->buf_size, 0);
2488 if (*rs->buf == '\0')
2490 /* Packet not supported. */
2495 parse_threadlist_response (rs->buf + 2, result_limit,
2496 &rs->echo_nextthread, threadlist, done);
2498 if (!threadmatch (&rs->echo_nextthread, nextthread))
2500 /* FIXME: This is a good reason to drop the packet. */
2501 /* Possably, there is a duplicate response. */
2503 retransmit immediatly - race conditions
2504 retransmit after timeout - yes
2506 wait for packet, then exit
2508 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2509 return 0; /* I choose simply exiting. */
2511 if (*result_count <= 0)
2515 warning (_("RMT ERROR : failed to get remote thread list."));
2518 return result; /* break; */
2520 if (*result_count > result_limit)
2523 warning (_("RMT ERROR: threadlist response longer than requested."));
2529 /* Fetch the list of remote threads, with the qL packet, and call
2530 STEPFUNCTION for each thread found. Stops iterating and returns 1
2531 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2532 STEPFUNCTION returns false. If the packet is not supported,
2536 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2539 struct remote_state *rs = get_remote_state ();
2540 int done, i, result_count;
2548 if (loopcount++ > looplimit)
2551 warning (_("Remote fetch threadlist -infinite loop-."));
2554 result = remote_get_threadlist (startflag, &rs->nextthread,
2555 MAXTHREADLISTRESULTS,
2556 &done, &result_count,
2557 rs->resultthreadlist);
2560 /* Clear for later iterations. */
2562 /* Setup to resume next batch of thread references, set nextthread. */
2563 if (result_count >= 1)
2564 copy_threadref (&rs->nextthread,
2565 &rs->resultthreadlist[result_count - 1]);
2567 while (result_count--)
2569 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2579 /* A thread found on the remote target. */
2581 typedef struct thread_item
2583 /* The thread's PTID. */
2586 /* The thread's extra info. May be NULL. */
2589 /* The core the thread was running on. -1 if not known. */
2592 DEF_VEC_O(thread_item_t);
2594 /* Context passed around to the various methods listing remote
2595 threads. As new threads are found, they're added to the ITEMS
2598 struct threads_listing_context
2600 /* The threads found on the remote target. */
2601 VEC (thread_item_t) *items;
2604 /* Discard the contents of the constructed thread listing context. */
2607 clear_threads_listing_context (void *p)
2609 struct threads_listing_context *context = p;
2611 struct thread_item *item;
2613 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2614 xfree (item->extra);
2616 VEC_free (thread_item_t, context->items);
2620 remote_newthread_step (threadref *ref, void *data)
2622 struct threads_listing_context *context = data;
2623 struct thread_item item;
2624 int pid = ptid_get_pid (inferior_ptid);
2626 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2630 VEC_safe_push (thread_item_t, context->items, &item);
2632 return 1; /* continue iterator */
2635 #define CRAZY_MAX_THREADS 1000
2638 remote_current_thread (ptid_t oldpid)
2640 struct remote_state *rs = get_remote_state ();
2643 getpkt (&rs->buf, &rs->buf_size, 0);
2644 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2645 return read_ptid (&rs->buf[2], NULL);
2650 /* List remote threads using the deprecated qL packet. */
2653 remote_get_threads_with_ql (struct target_ops *ops,
2654 struct threads_listing_context *context)
2656 if (remote_threadlist_iterator (remote_newthread_step, context,
2657 CRAZY_MAX_THREADS) >= 0)
2663 #if defined(HAVE_LIBEXPAT)
2666 start_thread (struct gdb_xml_parser *parser,
2667 const struct gdb_xml_element *element,
2668 void *user_data, VEC(gdb_xml_value_s) *attributes)
2670 struct threads_listing_context *data = user_data;
2672 struct thread_item item;
2674 struct gdb_xml_value *attr;
2676 id = xml_find_attribute (attributes, "id")->value;
2677 item.ptid = read_ptid (id, NULL);
2679 attr = xml_find_attribute (attributes, "core");
2681 item.core = *(ULONGEST *) attr->value;
2687 VEC_safe_push (thread_item_t, data->items, &item);
2691 end_thread (struct gdb_xml_parser *parser,
2692 const struct gdb_xml_element *element,
2693 void *user_data, const char *body_text)
2695 struct threads_listing_context *data = user_data;
2697 if (body_text && *body_text)
2698 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2701 const struct gdb_xml_attribute thread_attributes[] = {
2702 { "id", GDB_XML_AF_NONE, NULL, NULL },
2703 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2704 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2707 const struct gdb_xml_element thread_children[] = {
2708 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2711 const struct gdb_xml_element threads_children[] = {
2712 { "thread", thread_attributes, thread_children,
2713 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2714 start_thread, end_thread },
2715 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2718 const struct gdb_xml_element threads_elements[] = {
2719 { "threads", NULL, threads_children,
2720 GDB_XML_EF_NONE, NULL, NULL },
2721 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2726 /* List remote threads using qXfer:threads:read. */
2729 remote_get_threads_with_qxfer (struct target_ops *ops,
2730 struct threads_listing_context *context)
2732 #if defined(HAVE_LIBEXPAT)
2733 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2735 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2736 struct cleanup *back_to = make_cleanup (xfree, xml);
2738 if (xml != NULL && *xml != '\0')
2740 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2741 threads_elements, xml, context);
2744 do_cleanups (back_to);
2752 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2755 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2756 struct threads_listing_context *context)
2758 struct remote_state *rs = get_remote_state ();
2760 if (rs->use_threadinfo_query)
2764 putpkt ("qfThreadInfo");
2765 getpkt (&rs->buf, &rs->buf_size, 0);
2767 if (bufp[0] != '\0') /* q packet recognized */
2769 while (*bufp++ == 'm') /* reply contains one or more TID */
2773 struct thread_item item;
2775 item.ptid = read_ptid (bufp, &bufp);
2779 VEC_safe_push (thread_item_t, context->items, &item);
2781 while (*bufp++ == ','); /* comma-separated list */
2782 putpkt ("qsThreadInfo");
2783 getpkt (&rs->buf, &rs->buf_size, 0);
2790 /* Packet not recognized. */
2791 rs->use_threadinfo_query = 0;
2798 /* Implement the to_update_thread_list function for the remote
2802 remote_update_thread_list (struct target_ops *ops)
2804 struct remote_state *rs = get_remote_state ();
2805 struct threads_listing_context context;
2806 struct cleanup *old_chain;
2809 context.items = NULL;
2810 old_chain = make_cleanup (clear_threads_listing_context, &context);
2812 /* We have a few different mechanisms to fetch the thread list. Try
2813 them all, starting with the most preferred one first, falling
2814 back to older methods. */
2815 if (remote_get_threads_with_qxfer (ops, &context)
2816 || remote_get_threads_with_qthreadinfo (ops, &context)
2817 || remote_get_threads_with_ql (ops, &context))
2820 struct thread_item *item;
2821 struct thread_info *tp, *tmp;
2825 if (VEC_empty (thread_item_t, context.items)
2826 && remote_thread_always_alive (ops, inferior_ptid))
2828 /* Some targets don't really support threads, but still
2829 reply an (empty) thread list in response to the thread
2830 listing packets, instead of replying "packet not
2831 supported". Exit early so we don't delete the main
2833 do_cleanups (old_chain);
2837 /* CONTEXT now holds the current thread list on the remote
2838 target end. Delete GDB-side threads no longer found on the
2840 ALL_NON_EXITED_THREADS_SAFE (tp, tmp)
2843 VEC_iterate (thread_item_t, context.items, i, item);
2846 if (ptid_equal (item->ptid, tp->ptid))
2850 if (i == VEC_length (thread_item_t, context.items))
2853 delete_thread (tp->ptid);
2857 /* And now add threads we don't know about yet to our list. */
2859 VEC_iterate (thread_item_t, context.items, i, item);
2862 if (!ptid_equal (item->ptid, null_ptid))
2864 struct private_thread_info *info;
2865 /* In non-stop mode, we assume new found threads are
2866 running until proven otherwise with a stop reply. In
2867 all-stop, we can only get here if all threads are
2869 int running = non_stop ? 1 : 0;
2871 remote_notice_new_inferior (item->ptid, running);
2873 info = demand_private_info (item->ptid);
2874 info->core = item->core;
2875 info->extra = item->extra;
2883 /* If no thread listing method is supported, then query whether
2884 each known thread is alive, one by one, with the T packet.
2885 If the target doesn't support threads at all, then this is a
2886 no-op. See remote_thread_alive. */
2890 do_cleanups (old_chain);
2894 * Collect a descriptive string about the given thread.
2895 * The target may say anything it wants to about the thread
2896 * (typically info about its blocked / runnable state, name, etc.).
2897 * This string will appear in the info threads display.
2899 * Optional: targets are not required to implement this function.
2903 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
2905 struct remote_state *rs = get_remote_state ();
2909 struct gdb_ext_thread_info threadinfo;
2910 static char display_buf[100]; /* arbitrary... */
2911 int n = 0; /* position in display_buf */
2913 if (rs->remote_desc == 0) /* paranoia */
2914 internal_error (__FILE__, __LINE__,
2915 _("remote_threads_extra_info"));
2917 if (ptid_equal (tp->ptid, magic_null_ptid)
2918 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
2919 /* This is the main thread which was added by GDB. The remote
2920 server doesn't know about it. */
2923 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2925 struct thread_info *info = find_thread_ptid (tp->ptid);
2927 if (info && info->priv)
2928 return info->priv->extra;
2933 if (rs->use_threadextra_query)
2936 char *endb = rs->buf + get_remote_packet_size ();
2938 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2940 write_ptid (b, endb, tp->ptid);
2943 getpkt (&rs->buf, &rs->buf_size, 0);
2944 if (rs->buf[0] != 0)
2946 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2947 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2948 display_buf [result] = '\0';
2953 /* If the above query fails, fall back to the old method. */
2954 rs->use_threadextra_query = 0;
2955 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2956 | TAG_MOREDISPLAY | TAG_DISPLAY;
2957 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
2958 if (remote_get_threadinfo (&id, set, &threadinfo))
2959 if (threadinfo.active)
2961 if (*threadinfo.shortname)
2962 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2963 " Name: %s,", threadinfo.shortname);
2964 if (*threadinfo.display)
2965 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2966 " State: %s,", threadinfo.display);
2967 if (*threadinfo.more_display)
2968 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2969 " Priority: %s", threadinfo.more_display);
2973 /* For purely cosmetic reasons, clear up trailing commas. */
2974 if (',' == display_buf[n-1])
2975 display_buf[n-1] = ' ';
2984 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
2985 struct static_tracepoint_marker *marker)
2987 struct remote_state *rs = get_remote_state ();
2990 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2992 p += hexnumstr (p, addr);
2994 getpkt (&rs->buf, &rs->buf_size, 0);
2998 error (_("Remote failure reply: %s"), p);
3002 parse_static_tracepoint_marker_definition (p, &p, marker);
3009 static VEC(static_tracepoint_marker_p) *
3010 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3013 struct remote_state *rs = get_remote_state ();
3014 VEC(static_tracepoint_marker_p) *markers = NULL;
3015 struct static_tracepoint_marker *marker = NULL;
3016 struct cleanup *old_chain;
3019 /* Ask for a first packet of static tracepoint marker
3022 getpkt (&rs->buf, &rs->buf_size, 0);
3025 error (_("Remote failure reply: %s"), p);
3027 old_chain = make_cleanup (free_current_marker, &marker);
3032 marker = XCNEW (struct static_tracepoint_marker);
3036 parse_static_tracepoint_marker_definition (p, &p, marker);
3038 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3040 VEC_safe_push (static_tracepoint_marker_p,
3046 release_static_tracepoint_marker (marker);
3047 memset (marker, 0, sizeof (*marker));
3050 while (*p++ == ','); /* comma-separated list */
3051 /* Ask for another packet of static tracepoint definition. */
3053 getpkt (&rs->buf, &rs->buf_size, 0);
3057 do_cleanups (old_chain);
3062 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3065 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3067 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3071 /* Restart the remote side; this is an extended protocol operation. */
3074 extended_remote_restart (void)
3076 struct remote_state *rs = get_remote_state ();
3078 /* Send the restart command; for reasons I don't understand the
3079 remote side really expects a number after the "R". */
3080 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3083 remote_fileio_reset ();
3086 /* Clean up connection to a remote debugger. */
3089 remote_close (struct target_ops *self)
3091 struct remote_state *rs = get_remote_state ();
3093 if (rs->remote_desc == NULL)
3094 return; /* already closed */
3096 /* Make sure we leave stdin registered in the event loop, and we
3097 don't leave the async SIGINT signal handler installed. */
3098 remote_terminal_ours (self);
3100 serial_close (rs->remote_desc);
3101 rs->remote_desc = NULL;
3103 /* We don't have a connection to the remote stub anymore. Get rid
3104 of all the inferiors and their threads we were controlling.
3105 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3106 will be unable to find the thread corresponding to (pid, 0, 0). */
3107 inferior_ptid = null_ptid;
3108 discard_all_inferiors ();
3110 /* We are closing the remote target, so we should discard
3111 everything of this target. */
3112 discard_pending_stop_replies_in_queue (rs);
3114 if (remote_async_inferior_event_token)
3115 delete_async_event_handler (&remote_async_inferior_event_token);
3117 remote_notif_state_xfree (rs->notif_state);
3119 trace_reset_local_state ();
3122 /* Query the remote side for the text, data and bss offsets. */
3127 struct remote_state *rs = get_remote_state ();
3130 int lose, num_segments = 0, do_sections, do_segments;
3131 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3132 struct section_offsets *offs;
3133 struct symfile_segment_data *data;
3135 if (symfile_objfile == NULL)
3138 putpkt ("qOffsets");
3139 getpkt (&rs->buf, &rs->buf_size, 0);
3142 if (buf[0] == '\000')
3143 return; /* Return silently. Stub doesn't support
3147 warning (_("Remote failure reply: %s"), buf);
3151 /* Pick up each field in turn. This used to be done with scanf, but
3152 scanf will make trouble if CORE_ADDR size doesn't match
3153 conversion directives correctly. The following code will work
3154 with any size of CORE_ADDR. */
3155 text_addr = data_addr = bss_addr = 0;
3159 if (startswith (ptr, "Text="))
3162 /* Don't use strtol, could lose on big values. */
3163 while (*ptr && *ptr != ';')
3164 text_addr = (text_addr << 4) + fromhex (*ptr++);
3166 if (startswith (ptr, ";Data="))
3169 while (*ptr && *ptr != ';')
3170 data_addr = (data_addr << 4) + fromhex (*ptr++);
3175 if (!lose && startswith (ptr, ";Bss="))
3178 while (*ptr && *ptr != ';')
3179 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3181 if (bss_addr != data_addr)
3182 warning (_("Target reported unsupported offsets: %s"), buf);
3187 else if (startswith (ptr, "TextSeg="))
3190 /* Don't use strtol, could lose on big values. */
3191 while (*ptr && *ptr != ';')
3192 text_addr = (text_addr << 4) + fromhex (*ptr++);
3195 if (startswith (ptr, ";DataSeg="))
3198 while (*ptr && *ptr != ';')
3199 data_addr = (data_addr << 4) + fromhex (*ptr++);
3207 error (_("Malformed response to offset query, %s"), buf);
3208 else if (*ptr != '\0')
3209 warning (_("Target reported unsupported offsets: %s"), buf);
3211 offs = ((struct section_offsets *)
3212 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3213 memcpy (offs, symfile_objfile->section_offsets,
3214 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3216 data = get_symfile_segment_data (symfile_objfile->obfd);
3217 do_segments = (data != NULL);
3218 do_sections = num_segments == 0;
3220 if (num_segments > 0)
3222 segments[0] = text_addr;
3223 segments[1] = data_addr;
3225 /* If we have two segments, we can still try to relocate everything
3226 by assuming that the .text and .data offsets apply to the whole
3227 text and data segments. Convert the offsets given in the packet
3228 to base addresses for symfile_map_offsets_to_segments. */
3229 else if (data && data->num_segments == 2)
3231 segments[0] = data->segment_bases[0] + text_addr;
3232 segments[1] = data->segment_bases[1] + data_addr;
3235 /* If the object file has only one segment, assume that it is text
3236 rather than data; main programs with no writable data are rare,
3237 but programs with no code are useless. Of course the code might
3238 have ended up in the data segment... to detect that we would need
3239 the permissions here. */
3240 else if (data && data->num_segments == 1)
3242 segments[0] = data->segment_bases[0] + text_addr;
3245 /* There's no way to relocate by segment. */
3251 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3252 offs, num_segments, segments);
3254 if (ret == 0 && !do_sections)
3255 error (_("Can not handle qOffsets TextSeg "
3256 "response with this symbol file"));
3263 free_symfile_segment_data (data);
3267 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3269 /* This is a temporary kludge to force data and bss to use the
3270 same offsets because that's what nlmconv does now. The real
3271 solution requires changes to the stub and remote.c that I
3272 don't have time to do right now. */
3274 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3275 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3278 objfile_relocate (symfile_objfile, offs);
3281 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3282 threads we know are stopped already. This is used during the
3283 initial remote connection in non-stop mode --- threads that are
3284 reported as already being stopped are left stopped. */
3287 set_stop_requested_callback (struct thread_info *thread, void *data)
3289 /* If we have a stop reply for this thread, it must be stopped. */
3290 if (peek_stop_reply (thread->ptid))
3291 set_stop_requested (thread->ptid, 1);
3296 /* Send interrupt_sequence to remote target. */
3298 send_interrupt_sequence (void)
3300 struct remote_state *rs = get_remote_state ();
3302 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3303 remote_serial_write ("\x03", 1);
3304 else if (interrupt_sequence_mode == interrupt_sequence_break)
3305 serial_send_break (rs->remote_desc);
3306 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3308 serial_send_break (rs->remote_desc);
3309 remote_serial_write ("g", 1);
3312 internal_error (__FILE__, __LINE__,
3313 _("Invalid value for interrupt_sequence_mode: %s."),
3314 interrupt_sequence_mode);
3318 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3319 and extract the PTID. Returns NULL_PTID if not found. */
3322 stop_reply_extract_thread (char *stop_reply)
3324 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3328 /* Txx r:val ; r:val (...) */
3331 /* Look for "register" named "thread". */
3336 p1 = strchr (p, ':');
3340 if (strncmp (p, "thread", p1 - p) == 0)
3341 return read_ptid (++p1, &p);
3343 p1 = strchr (p, ';');
3355 /* Determine the remote side's current thread. If we have a stop
3356 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3357 "thread" register we can extract the current thread from. If not,
3358 ask the remote which is the current thread with qC. The former
3359 method avoids a roundtrip. */
3362 get_current_thread (char *wait_status)
3366 /* Note we don't use remote_parse_stop_reply as that makes use of
3367 the target architecture, which we haven't yet fully determined at
3369 if (wait_status != NULL)
3370 ptid = stop_reply_extract_thread (wait_status);
3371 if (ptid_equal (ptid, null_ptid))
3372 ptid = remote_current_thread (inferior_ptid);
3377 /* Query the remote target for which is the current thread/process,
3378 add it to our tables, and update INFERIOR_PTID. The caller is
3379 responsible for setting the state such that the remote end is ready
3380 to return the current thread.
3382 This function is called after handling the '?' or 'vRun' packets,
3383 whose response is a stop reply from which we can also try
3384 extracting the thread. If the target doesn't support the explicit
3385 qC query, we infer the current thread from that stop reply, passed
3386 in in WAIT_STATUS, which may be NULL. */
3389 add_current_inferior_and_thread (char *wait_status)
3391 struct remote_state *rs = get_remote_state ();
3393 ptid_t ptid = null_ptid;
3395 inferior_ptid = null_ptid;
3397 /* Now, if we have thread information, update inferior_ptid. */
3398 ptid = get_current_thread (wait_status);
3400 if (!ptid_equal (ptid, null_ptid))
3402 if (!remote_multi_process_p (rs))
3405 inferior_ptid = ptid;
3409 /* Without this, some commands which require an active target
3410 (such as kill) won't work. This variable serves (at least)
3411 double duty as both the pid of the target process (if it has
3412 such), and as a flag indicating that a target is active. */
3413 inferior_ptid = magic_null_ptid;
3417 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3419 /* Add the main thread. */
3420 add_thread_silent (inferior_ptid);
3424 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3426 struct remote_state *rs = get_remote_state ();
3427 struct packet_config *noack_config;
3428 char *wait_status = NULL;
3430 immediate_quit++; /* Allow user to interrupt it. */
3433 if (interrupt_on_connect)
3434 send_interrupt_sequence ();
3436 /* Ack any packet which the remote side has already sent. */
3437 serial_write (rs->remote_desc, "+", 1);
3439 /* Signal other parts that we're going through the initial setup,
3440 and so things may not be stable yet. */
3441 rs->starting_up = 1;
3443 /* The first packet we send to the target is the optional "supported
3444 packets" request. If the target can answer this, it will tell us
3445 which later probes to skip. */
3446 remote_query_supported ();
3448 /* If the stub wants to get a QAllow, compose one and send it. */
3449 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3450 remote_set_permissions (target);
3452 /* Next, we possibly activate noack mode.
3454 If the QStartNoAckMode packet configuration is set to AUTO,
3455 enable noack mode if the stub reported a wish for it with
3458 If set to TRUE, then enable noack mode even if the stub didn't
3459 report it in qSupported. If the stub doesn't reply OK, the
3460 session ends with an error.
3462 If FALSE, then don't activate noack mode, regardless of what the
3463 stub claimed should be the default with qSupported. */
3465 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3466 if (packet_config_support (noack_config) != PACKET_DISABLE)
3468 putpkt ("QStartNoAckMode");
3469 getpkt (&rs->buf, &rs->buf_size, 0);
3470 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3476 /* Tell the remote that we are using the extended protocol. */
3478 getpkt (&rs->buf, &rs->buf_size, 0);
3481 /* Let the target know which signals it is allowed to pass down to
3483 update_signals_program_target ();
3485 /* Next, if the target can specify a description, read it. We do
3486 this before anything involving memory or registers. */
3487 target_find_description ();
3489 /* Next, now that we know something about the target, update the
3490 address spaces in the program spaces. */
3491 update_address_spaces ();
3493 /* On OSs where the list of libraries is global to all
3494 processes, we fetch them early. */
3495 if (gdbarch_has_global_solist (target_gdbarch ()))
3496 solib_add (NULL, from_tty, target, auto_solib_add);
3500 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3501 error (_("Non-stop mode requested, but remote "
3502 "does not support non-stop"));
3504 putpkt ("QNonStop:1");
3505 getpkt (&rs->buf, &rs->buf_size, 0);
3507 if (strcmp (rs->buf, "OK") != 0)
3508 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3510 /* Find about threads and processes the stub is already
3511 controlling. We default to adding them in the running state.
3512 The '?' query below will then tell us about which threads are
3514 remote_update_thread_list (target);
3516 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3518 /* Don't assume that the stub can operate in all-stop mode.
3519 Request it explicitly. */
3520 putpkt ("QNonStop:0");
3521 getpkt (&rs->buf, &rs->buf_size, 0);
3523 if (strcmp (rs->buf, "OK") != 0)
3524 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3527 /* Upload TSVs regardless of whether the target is running or not. The
3528 remote stub, such as GDBserver, may have some predefined or builtin
3529 TSVs, even if the target is not running. */
3530 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3532 struct uploaded_tsv *uploaded_tsvs = NULL;
3534 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3535 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3538 /* Check whether the target is running now. */
3540 getpkt (&rs->buf, &rs->buf_size, 0);
3546 struct inferior *inf;
3548 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3551 error (_("The target is not running (try extended-remote?)"));
3553 /* We're connected, but not running. Drop out before we
3554 call start_remote. */
3555 rs->starting_up = 0;
3560 /* Save the reply for later. */
3561 wait_status = alloca (strlen (rs->buf) + 1);
3562 strcpy (wait_status, rs->buf);
3565 /* Fetch thread list. */
3566 target_update_thread_list ();
3568 /* Let the stub know that we want it to return the thread. */
3569 set_continue_thread (minus_one_ptid);
3571 if (thread_count () == 0)
3573 /* Target has no concept of threads at all. GDB treats
3574 non-threaded target as single-threaded; add a main
3576 add_current_inferior_and_thread (wait_status);
3580 /* We have thread information; select the thread the target
3581 says should be current. If we're reconnecting to a
3582 multi-threaded program, this will ideally be the thread
3583 that last reported an event before GDB disconnected. */
3584 inferior_ptid = get_current_thread (wait_status);
3585 if (ptid_equal (inferior_ptid, null_ptid))
3587 /* Odd... The target was able to list threads, but not
3588 tell us which thread was current (no "thread"
3589 register in T stop reply?). Just pick the first
3590 thread in the thread list then. */
3591 inferior_ptid = thread_list->ptid;
3595 /* init_wait_for_inferior should be called before get_offsets in order
3596 to manage `inserted' flag in bp loc in a correct state.
3597 breakpoint_init_inferior, called from init_wait_for_inferior, set
3598 `inserted' flag to 0, while before breakpoint_re_set, called from
3599 start_remote, set `inserted' flag to 1. In the initialization of
3600 inferior, breakpoint_init_inferior should be called first, and then
3601 breakpoint_re_set can be called. If this order is broken, state of
3602 `inserted' flag is wrong, and cause some problems on breakpoint
3604 init_wait_for_inferior ();
3606 get_offsets (); /* Get text, data & bss offsets. */
3608 /* If we could not find a description using qXfer, and we know
3609 how to do it some other way, try again. This is not
3610 supported for non-stop; it could be, but it is tricky if
3611 there are no stopped threads when we connect. */
3612 if (remote_read_description_p (target)
3613 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3615 target_clear_description ();
3616 target_find_description ();
3619 /* Use the previously fetched status. */
3620 gdb_assert (wait_status != NULL);
3621 strcpy (rs->buf, wait_status);
3622 rs->cached_wait_status = 1;
3625 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3629 /* Clear WFI global state. Do this before finding about new
3630 threads and inferiors, and setting the current inferior.
3631 Otherwise we would clear the proceed status of the current
3632 inferior when we want its stop_soon state to be preserved
3633 (see notice_new_inferior). */
3634 init_wait_for_inferior ();
3636 /* In non-stop, we will either get an "OK", meaning that there
3637 are no stopped threads at this time; or, a regular stop
3638 reply. In the latter case, there may be more than one thread
3639 stopped --- we pull them all out using the vStopped
3641 if (strcmp (rs->buf, "OK") != 0)
3643 struct notif_client *notif = ¬if_client_stop;
3645 /* remote_notif_get_pending_replies acks this one, and gets
3647 rs->notif_state->pending_event[notif_client_stop.id]
3648 = remote_notif_parse (notif, rs->buf);
3649 remote_notif_get_pending_events (notif);
3651 /* Make sure that threads that were stopped remain
3653 iterate_over_threads (set_stop_requested_callback, NULL);
3656 if (target_can_async_p ())
3659 if (thread_count () == 0)
3662 error (_("The target is not running (try extended-remote?)"));
3664 /* We're connected, but not running. Drop out before we
3665 call start_remote. */
3666 rs->starting_up = 0;
3670 /* Let the stub know that we want it to return the thread. */
3672 /* Force the stub to choose a thread. */
3673 set_general_thread (null_ptid);
3676 inferior_ptid = remote_current_thread (minus_one_ptid);
3677 if (ptid_equal (inferior_ptid, minus_one_ptid))
3678 error (_("remote didn't report the current thread in non-stop mode"));
3680 get_offsets (); /* Get text, data & bss offsets. */
3682 /* In non-stop mode, any cached wait status will be stored in
3683 the stop reply queue. */
3684 gdb_assert (wait_status == NULL);
3686 /* Report all signals during attach/startup. */
3687 remote_pass_signals (target, 0, NULL);
3690 /* If we connected to a live target, do some additional setup. */
3691 if (target_has_execution)
3693 if (symfile_objfile) /* No use without a symbol-file. */
3694 remote_check_symbols ();
3697 /* Possibly the target has been engaged in a trace run started
3698 previously; find out where things are at. */
3699 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3701 struct uploaded_tp *uploaded_tps = NULL;
3703 if (current_trace_status ()->running)
3704 printf_filtered (_("Trace is already running on the target.\n"));
3706 remote_upload_tracepoints (target, &uploaded_tps);
3708 merge_uploaded_tracepoints (&uploaded_tps);
3711 /* The thread and inferior lists are now synchronized with the
3712 target, our symbols have been relocated, and we're merged the
3713 target's tracepoints with ours. We're done with basic start
3715 rs->starting_up = 0;
3717 /* Maybe breakpoints are global and need to be inserted now. */
3718 if (breakpoints_should_be_inserted_now ())
3719 insert_breakpoints ();
3722 /* Open a connection to a remote debugger.
3723 NAME is the filename used for communication. */
3726 remote_open (const char *name, int from_tty)
3728 remote_open_1 (name, from_tty, &remote_ops, 0);
3731 /* Open a connection to a remote debugger using the extended
3732 remote gdb protocol. NAME is the filename used for communication. */
3735 extended_remote_open (const char *name, int from_tty)
3737 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3740 /* Reset all packets back to "unknown support". Called when opening a
3741 new connection to a remote target. */
3744 reset_all_packet_configs_support (void)
3748 for (i = 0; i < PACKET_MAX; i++)
3749 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3752 /* Initialize all packet configs. */
3755 init_all_packet_configs (void)
3759 for (i = 0; i < PACKET_MAX; i++)
3761 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3762 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3766 /* Symbol look-up. */
3769 remote_check_symbols (void)
3771 struct remote_state *rs = get_remote_state ();
3772 char *msg, *reply, *tmp;
3773 struct bound_minimal_symbol sym;
3776 /* The remote side has no concept of inferiors that aren't running
3777 yet, it only knows about running processes. If we're connected
3778 but our current inferior is not running, we should not invite the
3779 remote target to request symbol lookups related to its
3780 (unrelated) current process. */
3781 if (!target_has_execution)
3784 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3787 /* Make sure the remote is pointing at the right process. Note
3788 there's no way to select "no process". */
3789 set_general_process ();
3791 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3792 because we need both at the same time. */
3793 msg = alloca (get_remote_packet_size ());
3795 /* Invite target to request symbol lookups. */
3797 putpkt ("qSymbol::");
3798 getpkt (&rs->buf, &rs->buf_size, 0);
3799 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3802 while (startswith (reply, "qSymbol:"))
3804 struct bound_minimal_symbol sym;
3807 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3809 sym = lookup_minimal_symbol (msg, NULL, NULL);
3810 if (sym.minsym == NULL)
3811 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3814 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3815 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
3817 /* If this is a function address, return the start of code
3818 instead of any data function descriptor. */
3819 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3823 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3824 phex_nz (sym_addr, addr_size), &reply[8]);
3828 getpkt (&rs->buf, &rs->buf_size, 0);
3833 static struct serial *
3834 remote_serial_open (const char *name)
3836 static int udp_warning = 0;
3838 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3839 of in ser-tcp.c, because it is the remote protocol assuming that the
3840 serial connection is reliable and not the serial connection promising
3842 if (!udp_warning && startswith (name, "udp:"))
3844 warning (_("The remote protocol may be unreliable over UDP.\n"
3845 "Some events may be lost, rendering further debugging "
3850 return serial_open (name);
3853 /* Inform the target of our permission settings. The permission flags
3854 work without this, but if the target knows the settings, it can do
3855 a couple things. First, it can add its own check, to catch cases
3856 that somehow manage to get by the permissions checks in target
3857 methods. Second, if the target is wired to disallow particular
3858 settings (for instance, a system in the field that is not set up to
3859 be able to stop at a breakpoint), it can object to any unavailable
3863 remote_set_permissions (struct target_ops *self)
3865 struct remote_state *rs = get_remote_state ();
3867 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3868 "WriteReg:%x;WriteMem:%x;"
3869 "InsertBreak:%x;InsertTrace:%x;"
3870 "InsertFastTrace:%x;Stop:%x",
3871 may_write_registers, may_write_memory,
3872 may_insert_breakpoints, may_insert_tracepoints,
3873 may_insert_fast_tracepoints, may_stop);
3875 getpkt (&rs->buf, &rs->buf_size, 0);
3877 /* If the target didn't like the packet, warn the user. Do not try
3878 to undo the user's settings, that would just be maddening. */
3879 if (strcmp (rs->buf, "OK") != 0)
3880 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3883 /* This type describes each known response to the qSupported
3885 struct protocol_feature
3887 /* The name of this protocol feature. */
3890 /* The default for this protocol feature. */
3891 enum packet_support default_support;
3893 /* The function to call when this feature is reported, or after
3894 qSupported processing if the feature is not supported.
3895 The first argument points to this structure. The second
3896 argument indicates whether the packet requested support be
3897 enabled, disabled, or probed (or the default, if this function
3898 is being called at the end of processing and this feature was
3899 not reported). The third argument may be NULL; if not NULL, it
3900 is a NUL-terminated string taken from the packet following
3901 this feature's name and an equals sign. */
3902 void (*func) (const struct protocol_feature *, enum packet_support,
3905 /* The corresponding packet for this feature. Only used if
3906 FUNC is remote_supported_packet. */
3911 remote_supported_packet (const struct protocol_feature *feature,
3912 enum packet_support support,
3913 const char *argument)
3917 warning (_("Remote qSupported response supplied an unexpected value for"
3918 " \"%s\"."), feature->name);
3922 remote_protocol_packets[feature->packet].support = support;
3926 remote_packet_size (const struct protocol_feature *feature,
3927 enum packet_support support, const char *value)
3929 struct remote_state *rs = get_remote_state ();
3934 if (support != PACKET_ENABLE)
3937 if (value == NULL || *value == '\0')
3939 warning (_("Remote target reported \"%s\" without a size."),
3945 packet_size = strtol (value, &value_end, 16);
3946 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3948 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3949 feature->name, value);
3953 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3955 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3956 packet_size, MAX_REMOTE_PACKET_SIZE);
3957 packet_size = MAX_REMOTE_PACKET_SIZE;
3960 /* Record the new maximum packet size. */
3961 rs->explicit_packet_size = packet_size;
3964 static const struct protocol_feature remote_protocol_features[] = {
3965 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3966 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3967 PACKET_qXfer_auxv },
3968 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3969 PACKET_qXfer_features },
3970 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3971 PACKET_qXfer_libraries },
3972 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3973 PACKET_qXfer_libraries_svr4 },
3974 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3975 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
3976 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3977 PACKET_qXfer_memory_map },
3978 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3979 PACKET_qXfer_spu_read },
3980 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3981 PACKET_qXfer_spu_write },
3982 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3983 PACKET_qXfer_osdata },
3984 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3985 PACKET_qXfer_threads },
3986 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3987 PACKET_qXfer_traceframe_info },
3988 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3989 PACKET_QPassSignals },
3990 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3991 PACKET_QProgramSignals },
3992 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3993 PACKET_QStartNoAckMode },
3994 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
3995 PACKET_multiprocess_feature },
3996 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
3997 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3998 PACKET_qXfer_siginfo_read },
3999 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4000 PACKET_qXfer_siginfo_write },
4001 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4002 PACKET_ConditionalTracepoints },
4003 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4004 PACKET_ConditionalBreakpoints },
4005 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4006 PACKET_BreakpointCommands },
4007 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4008 PACKET_FastTracepoints },
4009 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4010 PACKET_StaticTracepoints },
4011 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4012 PACKET_InstallInTrace},
4013 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4014 PACKET_DisconnectedTracing_feature },
4015 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4017 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4019 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4020 PACKET_TracepointSource },
4021 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4023 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4024 PACKET_EnableDisableTracepoints_feature },
4025 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4026 PACKET_qXfer_fdpic },
4027 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4029 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4030 PACKET_QDisableRandomization },
4031 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4032 { "QTBuffer:size", PACKET_DISABLE,
4033 remote_supported_packet, PACKET_QTBuffer_size},
4034 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4035 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4036 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4037 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4038 PACKET_qXfer_btrace },
4039 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4040 PACKET_qXfer_btrace_conf },
4041 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4042 PACKET_Qbtrace_conf_bts_size },
4043 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4044 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4047 static char *remote_support_xml;
4049 /* Register string appended to "xmlRegisters=" in qSupported query. */
4052 register_remote_support_xml (const char *xml)
4054 #if defined(HAVE_LIBEXPAT)
4055 if (remote_support_xml == NULL)
4056 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4059 char *copy = xstrdup (remote_support_xml + 13);
4060 char *p = strtok (copy, ",");
4064 if (strcmp (p, xml) == 0)
4071 while ((p = strtok (NULL, ",")) != NULL);
4074 remote_support_xml = reconcat (remote_support_xml,
4075 remote_support_xml, ",", xml,
4082 remote_query_supported_append (char *msg, const char *append)
4085 return reconcat (msg, msg, ";", append, (char *) NULL);
4087 return xstrdup (append);
4091 remote_query_supported (void)
4093 struct remote_state *rs = get_remote_state ();
4096 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4098 /* The packet support flags are handled differently for this packet
4099 than for most others. We treat an error, a disabled packet, and
4100 an empty response identically: any features which must be reported
4101 to be used will be automatically disabled. An empty buffer
4102 accomplishes this, since that is also the representation for a list
4103 containing no features. */
4106 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4109 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4111 q = remote_query_supported_append (q, "multiprocess+");
4113 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4114 q = remote_query_supported_append (q, "swbreak+");
4115 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4116 q = remote_query_supported_append (q, "hwbreak+");
4118 if (remote_support_xml)
4119 q = remote_query_supported_append (q, remote_support_xml);
4121 q = remote_query_supported_append (q, "qRelocInsn+");
4123 q = reconcat (q, "qSupported:", q, (char *) NULL);
4126 do_cleanups (old_chain);
4128 getpkt (&rs->buf, &rs->buf_size, 0);
4130 /* If an error occured, warn, but do not return - just reset the
4131 buffer to empty and go on to disable features. */
4132 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4135 warning (_("Remote failure reply: %s"), rs->buf);
4140 memset (seen, 0, sizeof (seen));
4145 enum packet_support is_supported;
4146 char *p, *end, *name_end, *value;
4148 /* First separate out this item from the rest of the packet. If
4149 there's another item after this, we overwrite the separator
4150 (terminated strings are much easier to work with). */
4152 end = strchr (p, ';');
4155 end = p + strlen (p);
4165 warning (_("empty item in \"qSupported\" response"));
4170 name_end = strchr (p, '=');
4173 /* This is a name=value entry. */
4174 is_supported = PACKET_ENABLE;
4175 value = name_end + 1;
4184 is_supported = PACKET_ENABLE;
4188 is_supported = PACKET_DISABLE;
4192 is_supported = PACKET_SUPPORT_UNKNOWN;
4196 warning (_("unrecognized item \"%s\" "
4197 "in \"qSupported\" response"), p);
4203 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4204 if (strcmp (remote_protocol_features[i].name, p) == 0)
4206 const struct protocol_feature *feature;
4209 feature = &remote_protocol_features[i];
4210 feature->func (feature, is_supported, value);
4215 /* If we increased the packet size, make sure to increase the global
4216 buffer size also. We delay this until after parsing the entire
4217 qSupported packet, because this is the same buffer we were
4219 if (rs->buf_size < rs->explicit_packet_size)
4221 rs->buf_size = rs->explicit_packet_size;
4222 rs->buf = xrealloc (rs->buf, rs->buf_size);
4225 /* Handle the defaults for unmentioned features. */
4226 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4229 const struct protocol_feature *feature;
4231 feature = &remote_protocol_features[i];
4232 feature->func (feature, feature->default_support, NULL);
4236 /* Remove any of the remote.c targets from target stack. Upper targets depend
4237 on it so remove them first. */
4240 remote_unpush_target (void)
4242 pop_all_targets_above (process_stratum - 1);
4246 remote_open_1 (const char *name, int from_tty,
4247 struct target_ops *target, int extended_p)
4249 struct remote_state *rs = get_remote_state ();
4252 error (_("To open a remote debug connection, you need to specify what\n"
4253 "serial device is attached to the remote system\n"
4254 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4256 /* See FIXME above. */
4257 if (!target_async_permitted)
4258 wait_forever_enabled_p = 1;
4260 /* If we're connected to a running target, target_preopen will kill it.
4261 Ask this question first, before target_preopen has a chance to kill
4263 if (rs->remote_desc != NULL && !have_inferiors ())
4266 && !query (_("Already connected to a remote target. Disconnect? ")))
4267 error (_("Still connected."));
4270 /* Here the possibly existing remote target gets unpushed. */
4271 target_preopen (from_tty);
4273 /* Make sure we send the passed signals list the next time we resume. */
4274 xfree (rs->last_pass_packet);
4275 rs->last_pass_packet = NULL;
4277 /* Make sure we send the program signals list the next time we
4279 xfree (rs->last_program_signals_packet);
4280 rs->last_program_signals_packet = NULL;
4282 remote_fileio_reset ();
4283 reopen_exec_file ();
4286 rs->remote_desc = remote_serial_open (name);
4287 if (!rs->remote_desc)
4288 perror_with_name (name);
4290 if (baud_rate != -1)
4292 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4294 /* The requested speed could not be set. Error out to
4295 top level after closing remote_desc. Take care to
4296 set remote_desc to NULL to avoid closing remote_desc
4298 serial_close (rs->remote_desc);
4299 rs->remote_desc = NULL;
4300 perror_with_name (name);
4304 serial_setparity (rs->remote_desc, serial_parity);
4305 serial_raw (rs->remote_desc);
4307 /* If there is something sitting in the buffer we might take it as a
4308 response to a command, which would be bad. */
4309 serial_flush_input (rs->remote_desc);
4313 puts_filtered ("Remote debugging using ");
4314 puts_filtered (name);
4315 puts_filtered ("\n");
4317 push_target (target); /* Switch to using remote target now. */
4319 /* Register extra event sources in the event loop. */
4320 remote_async_inferior_event_token
4321 = create_async_event_handler (remote_async_inferior_event_handler,
4323 rs->notif_state = remote_notif_state_allocate ();
4325 /* Reset the target state; these things will be queried either by
4326 remote_query_supported or as they are needed. */
4327 reset_all_packet_configs_support ();
4328 rs->cached_wait_status = 0;
4329 rs->explicit_packet_size = 0;
4331 rs->extended = extended_p;
4332 rs->waiting_for_stop_reply = 0;
4333 rs->ctrlc_pending_p = 0;
4335 rs->general_thread = not_sent_ptid;
4336 rs->continue_thread = not_sent_ptid;
4337 rs->remote_traceframe_number = -1;
4339 /* Probe for ability to use "ThreadInfo" query, as required. */
4340 rs->use_threadinfo_query = 1;
4341 rs->use_threadextra_query = 1;
4343 if (target_async_permitted)
4345 /* With this target we start out by owning the terminal. */
4346 remote_async_terminal_ours_p = 1;
4348 /* FIXME: cagney/1999-09-23: During the initial connection it is
4349 assumed that the target is already ready and able to respond to
4350 requests. Unfortunately remote_start_remote() eventually calls
4351 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4352 around this. Eventually a mechanism that allows
4353 wait_for_inferior() to expect/get timeouts will be
4355 wait_forever_enabled_p = 0;
4358 /* First delete any symbols previously loaded from shared libraries. */
4359 no_shared_libraries (NULL, 0);
4362 init_thread_list ();
4364 /* Start the remote connection. If error() or QUIT, discard this
4365 target (we'd otherwise be in an inconsistent state) and then
4366 propogate the error on up the exception chain. This ensures that
4367 the caller doesn't stumble along blindly assuming that the
4368 function succeeded. The CLI doesn't have this problem but other
4369 UI's, such as MI do.
4371 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4372 this function should return an error indication letting the
4373 caller restore the previous state. Unfortunately the command
4374 ``target remote'' is directly wired to this function making that
4375 impossible. On a positive note, the CLI side of this problem has
4376 been fixed - the function set_cmd_context() makes it possible for
4377 all the ``target ....'' commands to share a common callback
4378 function. See cli-dump.c. */
4383 remote_start_remote (from_tty, target, extended_p);
4385 CATCH (ex, RETURN_MASK_ALL)
4387 /* Pop the partially set up target - unless something else did
4388 already before throwing the exception. */
4389 if (rs->remote_desc != NULL)
4390 remote_unpush_target ();
4391 if (target_async_permitted)
4392 wait_forever_enabled_p = 1;
4393 throw_exception (ex);
4398 remote_btrace_reset ();
4400 if (target_async_permitted)
4401 wait_forever_enabled_p = 1;
4404 /* This takes a program previously attached to and detaches it. After
4405 this is done, GDB can be used to debug some other program. We
4406 better not have left any breakpoints in the target program or it'll
4407 die when it hits one. */
4410 remote_detach_1 (const char *args, int from_tty, int extended)
4412 int pid = ptid_get_pid (inferior_ptid);
4413 struct remote_state *rs = get_remote_state ();
4416 error (_("Argument given to \"detach\" when remotely debugging."));
4418 if (!target_has_execution)
4419 error (_("No process to detach from."));
4423 char *exec_file = get_exec_file (0);
4424 if (exec_file == NULL)
4426 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4427 target_pid_to_str (pid_to_ptid (pid)));
4428 gdb_flush (gdb_stdout);
4431 /* Tell the remote target to detach. */
4432 if (remote_multi_process_p (rs))
4433 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4435 strcpy (rs->buf, "D");
4438 getpkt (&rs->buf, &rs->buf_size, 0);
4440 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4442 else if (rs->buf[0] == '\0')
4443 error (_("Remote doesn't know how to detach"));
4445 error (_("Can't detach process."));
4447 if (from_tty && !extended)
4448 puts_filtered (_("Ending remote debugging.\n"));
4450 target_mourn_inferior ();
4454 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4456 remote_detach_1 (args, from_tty, 0);
4460 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4462 remote_detach_1 (args, from_tty, 1);
4465 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4468 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4471 error (_("Argument given to \"disconnect\" when remotely debugging."));
4473 /* Make sure we unpush even the extended remote targets; mourn
4474 won't do it. So call remote_mourn_1 directly instead of
4475 target_mourn_inferior. */
4476 remote_mourn_1 (target);
4479 puts_filtered ("Ending remote debugging.\n");
4482 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4483 be chatty about it. */
4486 extended_remote_attach_1 (struct target_ops *target, const char *args,
4489 struct remote_state *rs = get_remote_state ();
4491 char *wait_status = NULL;
4493 pid = parse_pid_to_attach (args);
4495 /* Remote PID can be freely equal to getpid, do not check it here the same
4496 way as in other targets. */
4498 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4499 error (_("This target does not support attaching to a process"));
4503 char *exec_file = get_exec_file (0);
4506 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4507 target_pid_to_str (pid_to_ptid (pid)));
4509 printf_unfiltered (_("Attaching to %s\n"),
4510 target_pid_to_str (pid_to_ptid (pid)));
4512 gdb_flush (gdb_stdout);
4515 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4517 getpkt (&rs->buf, &rs->buf_size, 0);
4519 switch (packet_ok (rs->buf,
4520 &remote_protocol_packets[PACKET_vAttach]))
4525 /* Save the reply for later. */
4526 wait_status = alloca (strlen (rs->buf) + 1);
4527 strcpy (wait_status, rs->buf);
4529 else if (strcmp (rs->buf, "OK") != 0)
4530 error (_("Attaching to %s failed with: %s"),
4531 target_pid_to_str (pid_to_ptid (pid)),
4534 case PACKET_UNKNOWN:
4535 error (_("This target does not support attaching to a process"));
4537 error (_("Attaching to %s failed"),
4538 target_pid_to_str (pid_to_ptid (pid)));
4541 set_current_inferior (remote_add_inferior (0, pid, 1));
4543 inferior_ptid = pid_to_ptid (pid);
4547 struct thread_info *thread;
4549 /* Get list of threads. */
4550 remote_update_thread_list (target);
4552 thread = first_thread_of_process (pid);
4554 inferior_ptid = thread->ptid;
4556 inferior_ptid = pid_to_ptid (pid);
4558 /* Invalidate our notion of the remote current thread. */
4559 record_currthread (rs, minus_one_ptid);
4563 /* Now, if we have thread information, update inferior_ptid. */
4564 inferior_ptid = remote_current_thread (inferior_ptid);
4566 /* Add the main thread to the thread list. */
4567 add_thread_silent (inferior_ptid);
4570 /* Next, if the target can specify a description, read it. We do
4571 this before anything involving memory or registers. */
4572 target_find_description ();
4576 /* Use the previously fetched status. */
4577 gdb_assert (wait_status != NULL);
4579 if (target_can_async_p ())
4581 struct notif_event *reply
4582 = remote_notif_parse (¬if_client_stop, wait_status);
4584 push_stop_reply ((struct stop_reply *) reply);
4590 gdb_assert (wait_status != NULL);
4591 strcpy (rs->buf, wait_status);
4592 rs->cached_wait_status = 1;
4596 gdb_assert (wait_status == NULL);
4600 extended_remote_attach (struct target_ops *ops, const char *args, int from_tty)
4602 extended_remote_attach_1 (ops, args, from_tty);
4605 /* Implementation of the to_post_attach method. */
4608 extended_remote_post_attach (struct target_ops *ops, int pid)
4610 /* In certain cases GDB might not have had the chance to start
4611 symbol lookup up until now. This could happen if the debugged
4612 binary is not using shared libraries, the vsyscall page is not
4613 present (on Linux) and the binary itself hadn't changed since the
4614 debugging process was started. */
4615 if (symfile_objfile != NULL)
4616 remote_check_symbols();
4620 /* Check for the availability of vCont. This function should also check
4624 remote_vcont_probe (struct remote_state *rs)
4628 strcpy (rs->buf, "vCont?");
4630 getpkt (&rs->buf, &rs->buf_size, 0);
4633 /* Make sure that the features we assume are supported. */
4634 if (startswith (buf, "vCont"))
4637 int support_s, support_S, support_c, support_C;
4643 rs->supports_vCont.t = 0;
4644 rs->supports_vCont.r = 0;
4645 while (p && *p == ';')
4648 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4650 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4652 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4654 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4656 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4657 rs->supports_vCont.t = 1;
4658 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4659 rs->supports_vCont.r = 1;
4661 p = strchr (p, ';');
4664 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4665 BUF will make packet_ok disable the packet. */
4666 if (!support_s || !support_S || !support_c || !support_C)
4670 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4673 /* Helper function for building "vCont" resumptions. Write a
4674 resumption to P. ENDP points to one-passed-the-end of the buffer
4675 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4676 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4677 resumed thread should be single-stepped and/or signalled. If PTID
4678 equals minus_one_ptid, then all threads are resumed; if PTID
4679 represents a process, then all threads of the process are resumed;
4680 the thread to be stepped and/or signalled is given in the global
4684 append_resumption (char *p, char *endp,
4685 ptid_t ptid, int step, enum gdb_signal siggnal)
4687 struct remote_state *rs = get_remote_state ();
4689 if (step && siggnal != GDB_SIGNAL_0)
4690 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4692 /* GDB is willing to range step. */
4693 && use_range_stepping
4694 /* Target supports range stepping. */
4695 && rs->supports_vCont.r
4696 /* We don't currently support range stepping multiple
4697 threads with a wildcard (though the protocol allows it,
4698 so stubs shouldn't make an active effort to forbid
4700 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4702 struct thread_info *tp;
4704 if (ptid_equal (ptid, minus_one_ptid))
4706 /* If we don't know about the target thread's tid, then
4707 we're resuming magic_null_ptid (see caller). */
4708 tp = find_thread_ptid (magic_null_ptid);
4711 tp = find_thread_ptid (ptid);
4712 gdb_assert (tp != NULL);
4714 if (tp->control.may_range_step)
4716 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4718 p += xsnprintf (p, endp - p, ";r%s,%s",
4719 phex_nz (tp->control.step_range_start,
4721 phex_nz (tp->control.step_range_end,
4725 p += xsnprintf (p, endp - p, ";s");
4728 p += xsnprintf (p, endp - p, ";s");
4729 else if (siggnal != GDB_SIGNAL_0)
4730 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4732 p += xsnprintf (p, endp - p, ";c");
4734 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4738 /* All (-1) threads of process. */
4739 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4741 p += xsnprintf (p, endp - p, ":");
4742 p = write_ptid (p, endp, nptid);
4744 else if (!ptid_equal (ptid, minus_one_ptid))
4746 p += xsnprintf (p, endp - p, ":");
4747 p = write_ptid (p, endp, ptid);
4753 /* Append a vCont continue-with-signal action for threads that have a
4754 non-zero stop signal. */
4757 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4759 struct thread_info *thread;
4761 ALL_NON_EXITED_THREADS (thread)
4762 if (ptid_match (thread->ptid, ptid)
4763 && !ptid_equal (inferior_ptid, thread->ptid)
4764 && thread->suspend.stop_signal != GDB_SIGNAL_0)
4766 p = append_resumption (p, endp, thread->ptid,
4767 0, thread->suspend.stop_signal);
4768 thread->suspend.stop_signal = GDB_SIGNAL_0;
4774 /* Resume the remote inferior by using a "vCont" packet. The thread
4775 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4776 resumed thread should be single-stepped and/or signalled. If PTID
4777 equals minus_one_ptid, then all threads are resumed; the thread to
4778 be stepped and/or signalled is given in the global INFERIOR_PTID.
4779 This function returns non-zero iff it resumes the inferior.
4781 This function issues a strict subset of all possible vCont commands at the
4785 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4787 struct remote_state *rs = get_remote_state ();
4791 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4792 remote_vcont_probe (rs);
4794 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
4798 endp = rs->buf + get_remote_packet_size ();
4800 /* If we could generate a wider range of packets, we'd have to worry
4801 about overflowing BUF. Should there be a generic
4802 "multi-part-packet" packet? */
4804 p += xsnprintf (p, endp - p, "vCont");
4806 if (ptid_equal (ptid, magic_null_ptid))
4808 /* MAGIC_NULL_PTID means that we don't have any active threads,
4809 so we don't have any TID numbers the inferior will
4810 understand. Make sure to only send forms that do not specify
4812 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4814 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4816 /* Resume all threads (of all processes, or of a single
4817 process), with preference for INFERIOR_PTID. This assumes
4818 inferior_ptid belongs to the set of all threads we are about
4820 if (step || siggnal != GDB_SIGNAL_0)
4822 /* Step inferior_ptid, with or without signal. */
4823 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4826 /* Also pass down any pending signaled resumption for other
4827 threads not the current. */
4828 p = append_pending_thread_resumptions (p, endp, ptid);
4830 /* And continue others without a signal. */
4831 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4835 /* Scheduler locking; resume only PTID. */
4836 append_resumption (p, endp, ptid, step, siggnal);
4839 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4844 /* In non-stop, the stub replies to vCont with "OK". The stop
4845 reply will be reported asynchronously by means of a `%Stop'
4847 getpkt (&rs->buf, &rs->buf_size, 0);
4848 if (strcmp (rs->buf, "OK") != 0)
4849 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4855 /* Tell the remote machine to resume. */
4858 remote_resume (struct target_ops *ops,
4859 ptid_t ptid, int step, enum gdb_signal siggnal)
4861 struct remote_state *rs = get_remote_state ();
4864 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4865 (explained in remote-notif.c:handle_notification) so
4866 remote_notif_process is not called. We need find a place where
4867 it is safe to start a 'vNotif' sequence. It is good to do it
4868 before resuming inferior, because inferior was stopped and no RSP
4869 traffic at that moment. */
4871 remote_notif_process (rs->notif_state, ¬if_client_stop);
4873 rs->last_sent_signal = siggnal;
4874 rs->last_sent_step = step;
4876 /* The vCont packet doesn't need to specify threads via Hc. */
4877 /* No reverse support (yet) for vCont. */
4878 if (execution_direction != EXEC_REVERSE)
4879 if (remote_vcont_resume (ptid, step, siggnal))
4882 /* All other supported resume packets do use Hc, so set the continue
4884 if (ptid_equal (ptid, minus_one_ptid))
4885 set_continue_thread (any_thread_ptid);
4887 set_continue_thread (ptid);
4890 if (execution_direction == EXEC_REVERSE)
4892 /* We don't pass signals to the target in reverse exec mode. */
4893 if (info_verbose && siggnal != GDB_SIGNAL_0)
4894 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4897 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
4898 error (_("Remote reverse-step not supported."));
4899 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
4900 error (_("Remote reverse-continue not supported."));
4902 strcpy (buf, step ? "bs" : "bc");
4904 else if (siggnal != GDB_SIGNAL_0)
4906 buf[0] = step ? 'S' : 'C';
4907 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4908 buf[2] = tohex (((int) siggnal) & 0xf);
4912 strcpy (buf, step ? "s" : "c");
4917 /* We are about to start executing the inferior, let's register it
4918 with the event loop. NOTE: this is the one place where all the
4919 execution commands end up. We could alternatively do this in each
4920 of the execution commands in infcmd.c. */
4921 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4922 into infcmd.c in order to allow inferior function calls to work
4923 NOT asynchronously. */
4924 if (target_can_async_p ())
4927 /* We've just told the target to resume. The remote server will
4928 wait for the inferior to stop, and then send a stop reply. In
4929 the mean time, we can't start another command/query ourselves
4930 because the stub wouldn't be ready to process it. This applies
4931 only to the base all-stop protocol, however. In non-stop (which
4932 only supports vCont), the stub replies with an "OK", and is
4933 immediate able to process further serial input. */
4935 rs->waiting_for_stop_reply = 1;
4939 /* Set up the signal handler for SIGINT, while the target is
4940 executing, ovewriting the 'regular' SIGINT signal handler. */
4942 async_initialize_sigint_signal_handler (void)
4944 signal (SIGINT, async_handle_remote_sigint);
4947 /* Signal handler for SIGINT, while the target is executing. */
4949 async_handle_remote_sigint (int sig)
4951 signal (sig, async_handle_remote_sigint_twice);
4952 /* Note we need to go through gdb_call_async_signal_handler in order
4953 to wake up the event loop on Windows. */
4954 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
4957 /* Signal handler for SIGINT, installed after SIGINT has already been
4958 sent once. It will take effect the second time that the user sends
4961 async_handle_remote_sigint_twice (int sig)
4963 signal (sig, async_handle_remote_sigint);
4964 /* See note in async_handle_remote_sigint. */
4965 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
4968 /* Perform the real interruption of the target execution, in response
4971 async_remote_interrupt (gdb_client_data arg)
4974 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
4976 target_stop (inferior_ptid);
4979 /* Perform interrupt, if the first attempt did not succeed. Just give
4980 up on the target alltogether. */
4982 async_remote_interrupt_twice (gdb_client_data arg)
4985 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
4990 /* Reinstall the usual SIGINT handlers, after the target has
4993 async_cleanup_sigint_signal_handler (void *dummy)
4995 signal (SIGINT, handle_sigint);
4998 /* Send ^C to target to halt it. Target will respond, and send us a
5000 static void (*ofunc) (int);
5002 /* The command line interface's stop routine. This function is installed
5003 as a signal handler for SIGINT. The first time a user requests a
5004 stop, we call remote_stop to send a break or ^C. If there is no
5005 response from the target (it didn't stop when the user requested it),
5006 we ask the user if he'd like to detach from the target. */
5008 sync_remote_interrupt (int signo)
5010 /* If this doesn't work, try more severe steps. */
5011 signal (signo, sync_remote_interrupt_twice);
5013 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5016 /* The user typed ^C twice. */
5019 sync_remote_interrupt_twice (int signo)
5021 signal (signo, ofunc);
5022 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5023 signal (signo, sync_remote_interrupt);
5026 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5027 thread, all threads of a remote process, or all threads of all
5031 remote_stop_ns (ptid_t ptid)
5033 struct remote_state *rs = get_remote_state ();
5035 char *endp = rs->buf + get_remote_packet_size ();
5037 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5038 remote_vcont_probe (rs);
5040 if (!rs->supports_vCont.t)
5041 error (_("Remote server does not support stopping threads"));
5043 if (ptid_equal (ptid, minus_one_ptid)
5044 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5045 p += xsnprintf (p, endp - p, "vCont;t");
5050 p += xsnprintf (p, endp - p, "vCont;t:");
5052 if (ptid_is_pid (ptid))
5053 /* All (-1) threads of process. */
5054 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5057 /* Small optimization: if we already have a stop reply for
5058 this thread, no use in telling the stub we want this
5060 if (peek_stop_reply (ptid))
5066 write_ptid (p, endp, nptid);
5069 /* In non-stop, we get an immediate OK reply. The stop reply will
5070 come in asynchronously by notification. */
5072 getpkt (&rs->buf, &rs->buf_size, 0);
5073 if (strcmp (rs->buf, "OK") != 0)
5074 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5077 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5078 remote target. It is undefined which thread of which process
5079 reports the stop. */
5082 remote_stop_as (ptid_t ptid)
5084 struct remote_state *rs = get_remote_state ();
5086 rs->ctrlc_pending_p = 1;
5088 /* If the inferior is stopped already, but the core didn't know
5089 about it yet, just ignore the request. The cached wait status
5090 will be collected in remote_wait. */
5091 if (rs->cached_wait_status)
5094 /* Send interrupt_sequence to remote target. */
5095 send_interrupt_sequence ();
5098 /* This is the generic stop called via the target vector. When a target
5099 interrupt is requested, either by the command line or the GUI, we
5100 will eventually end up here. */
5103 remote_stop (struct target_ops *self, ptid_t ptid)
5106 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5109 remote_stop_ns (ptid);
5111 remote_stop_as (ptid);
5114 /* Ask the user what to do when an interrupt is received. */
5117 interrupt_query (void)
5119 target_terminal_ours ();
5121 if (target_is_async_p ())
5123 signal (SIGINT, handle_sigint);
5128 if (query (_("Interrupted while waiting for the program.\n\
5129 Give up (and stop debugging it)? ")))
5131 remote_unpush_target ();
5136 target_terminal_inferior ();
5139 /* Enable/disable target terminal ownership. Most targets can use
5140 terminal groups to control terminal ownership. Remote targets are
5141 different in that explicit transfer of ownership to/from GDB/target
5145 remote_terminal_inferior (struct target_ops *self)
5147 if (!target_async_permitted)
5148 /* Nothing to do. */
5151 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5152 idempotent. The event-loop GDB talking to an asynchronous target
5153 with a synchronous command calls this function from both
5154 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5155 transfer the terminal to the target when it shouldn't this guard
5157 if (!remote_async_terminal_ours_p)
5159 delete_file_handler (input_fd);
5160 remote_async_terminal_ours_p = 0;
5161 async_initialize_sigint_signal_handler ();
5162 /* NOTE: At this point we could also register our selves as the
5163 recipient of all input. Any characters typed could then be
5164 passed on down to the target. */
5168 remote_terminal_ours (struct target_ops *self)
5170 if (!target_async_permitted)
5171 /* Nothing to do. */
5174 /* See FIXME in remote_terminal_inferior. */
5175 if (remote_async_terminal_ours_p)
5177 async_cleanup_sigint_signal_handler (NULL);
5178 add_file_handler (input_fd, stdin_event_handler, 0);
5179 remote_async_terminal_ours_p = 1;
5183 remote_console_output (char *msg)
5187 for (p = msg; p[0] && p[1]; p += 2)
5190 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5194 fputs_unfiltered (tb, gdb_stdtarg);
5196 gdb_flush (gdb_stdtarg);
5199 typedef struct cached_reg
5202 gdb_byte data[MAX_REGISTER_SIZE];
5205 DEF_VEC_O(cached_reg_t);
5207 typedef struct stop_reply
5209 struct notif_event base;
5211 /* The identifier of the thread about this event */
5214 /* The remote state this event is associated with. When the remote
5215 connection, represented by a remote_state object, is closed,
5216 all the associated stop_reply events should be released. */
5217 struct remote_state *rs;
5219 struct target_waitstatus ws;
5221 /* Expedited registers. This makes remote debugging a bit more
5222 efficient for those targets that provide critical registers as
5223 part of their normal status mechanism (as another roundtrip to
5224 fetch them is avoided). */
5225 VEC(cached_reg_t) *regcache;
5227 enum target_stop_reason stop_reason;
5229 CORE_ADDR watch_data_address;
5234 DECLARE_QUEUE_P (stop_reply_p);
5235 DEFINE_QUEUE_P (stop_reply_p);
5236 /* The list of already fetched and acknowledged stop events. This
5237 queue is used for notification Stop, and other notifications
5238 don't need queue for their events, because the notification events
5239 of Stop can't be consumed immediately, so that events should be
5240 queued first, and be consumed by remote_wait_{ns,as} one per
5241 time. Other notifications can consume their events immediately,
5242 so queue is not needed for them. */
5243 static QUEUE (stop_reply_p) *stop_reply_queue;
5246 stop_reply_xfree (struct stop_reply *r)
5248 notif_event_xfree ((struct notif_event *) r);
5252 remote_notif_stop_parse (struct notif_client *self, char *buf,
5253 struct notif_event *event)
5255 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5259 remote_notif_stop_ack (struct notif_client *self, char *buf,
5260 struct notif_event *event)
5262 struct stop_reply *stop_reply = (struct stop_reply *) event;
5265 putpkt ((char *) self->ack_command);
5267 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5268 /* We got an unknown stop reply. */
5269 error (_("Unknown stop reply"));
5271 push_stop_reply (stop_reply);
5275 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5277 /* We can't get pending events in remote_notif_process for
5278 notification stop, and we have to do this in remote_wait_ns
5279 instead. If we fetch all queued events from stub, remote stub
5280 may exit and we have no chance to process them back in
5282 mark_async_event_handler (remote_async_inferior_event_token);
5287 stop_reply_dtr (struct notif_event *event)
5289 struct stop_reply *r = (struct stop_reply *) event;
5291 VEC_free (cached_reg_t, r->regcache);
5294 static struct notif_event *
5295 remote_notif_stop_alloc_reply (void)
5297 struct notif_event *r
5298 = (struct notif_event *) XNEW (struct stop_reply);
5300 r->dtr = stop_reply_dtr;
5305 /* A client of notification Stop. */
5307 struct notif_client notif_client_stop =
5311 remote_notif_stop_parse,
5312 remote_notif_stop_ack,
5313 remote_notif_stop_can_get_pending_events,
5314 remote_notif_stop_alloc_reply,
5318 /* A parameter to pass data in and out. */
5320 struct queue_iter_param
5323 struct stop_reply *output;
5326 /* Remove stop replies in the queue if its pid is equal to the given
5330 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5331 QUEUE_ITER (stop_reply_p) *iter,
5335 struct queue_iter_param *param = data;
5336 struct inferior *inf = param->input;
5338 if (ptid_get_pid (event->ptid) == inf->pid)
5340 stop_reply_xfree (event);
5341 QUEUE_remove_elem (stop_reply_p, q, iter);
5347 /* Discard all pending stop replies of inferior INF. */
5350 discard_pending_stop_replies (struct inferior *inf)
5353 struct queue_iter_param param;
5354 struct stop_reply *reply;
5355 struct remote_state *rs = get_remote_state ();
5356 struct remote_notif_state *rns = rs->notif_state;
5358 /* This function can be notified when an inferior exists. When the
5359 target is not remote, the notification state is NULL. */
5360 if (rs->remote_desc == NULL)
5363 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5365 /* Discard the in-flight notification. */
5366 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5368 stop_reply_xfree (reply);
5369 rns->pending_event[notif_client_stop.id] = NULL;
5373 param.output = NULL;
5374 /* Discard the stop replies we have already pulled with
5376 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5377 remove_stop_reply_for_inferior, ¶m);
5380 /* If its remote state is equal to the given remote state,
5381 remove EVENT from the stop reply queue. */
5384 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5385 QUEUE_ITER (stop_reply_p) *iter,
5389 struct queue_iter_param *param = data;
5390 struct remote_state *rs = param->input;
5392 if (event->rs == rs)
5394 stop_reply_xfree (event);
5395 QUEUE_remove_elem (stop_reply_p, q, iter);
5401 /* Discard the stop replies for RS in stop_reply_queue. */
5404 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5406 struct queue_iter_param param;
5409 param.output = NULL;
5410 /* Discard the stop replies we have already pulled with
5412 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5413 remove_stop_reply_of_remote_state, ¶m);
5416 /* A parameter to pass data in and out. */
5419 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5420 QUEUE_ITER (stop_reply_p) *iter,
5424 struct queue_iter_param *param = data;
5425 ptid_t *ptid = param->input;
5427 if (ptid_match (event->ptid, *ptid))
5429 param->output = event;
5430 QUEUE_remove_elem (stop_reply_p, q, iter);
5437 /* Remove the first reply in 'stop_reply_queue' which matches
5440 static struct stop_reply *
5441 remote_notif_remove_queued_reply (ptid_t ptid)
5443 struct queue_iter_param param;
5445 param.input = &ptid;
5446 param.output = NULL;
5448 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5449 remote_notif_remove_once_on_match, ¶m);
5451 fprintf_unfiltered (gdb_stdlog,
5452 "notif: discard queued event: 'Stop' in %s\n",
5453 target_pid_to_str (ptid));
5455 return param.output;
5458 /* Look for a queued stop reply belonging to PTID. If one is found,
5459 remove it from the queue, and return it. Returns NULL if none is
5460 found. If there are still queued events left to process, tell the
5461 event loop to get back to target_wait soon. */
5463 static struct stop_reply *
5464 queued_stop_reply (ptid_t ptid)
5466 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5468 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5469 /* There's still at least an event left. */
5470 mark_async_event_handler (remote_async_inferior_event_token);
5475 /* Push a fully parsed stop reply in the stop reply queue. Since we
5476 know that we now have at least one queued event left to pass to the
5477 core side, tell the event loop to get back to target_wait soon. */
5480 push_stop_reply (struct stop_reply *new_event)
5482 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5485 fprintf_unfiltered (gdb_stdlog,
5486 "notif: push 'Stop' %s to queue %d\n",
5487 target_pid_to_str (new_event->ptid),
5488 QUEUE_length (stop_reply_p,
5491 mark_async_event_handler (remote_async_inferior_event_token);
5495 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5496 QUEUE_ITER (stop_reply_p) *iter,
5497 struct stop_reply *event,
5500 ptid_t *ptid = data;
5502 return !(ptid_equal (*ptid, event->ptid)
5503 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5506 /* Returns true if we have a stop reply for PTID. */
5509 peek_stop_reply (ptid_t ptid)
5511 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5512 stop_reply_match_ptid_and_ws, &ptid);
5515 /* Skip PACKET until the next semi-colon (or end of string). */
5518 skip_to_semicolon (char *p)
5520 while (*p != '\0' && *p != ';')
5525 /* Parse the stop reply in BUF. Either the function succeeds, and the
5526 result is stored in EVENT, or throws an error. */
5529 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5531 struct remote_arch_state *rsa = get_remote_arch_state ();
5535 event->ptid = null_ptid;
5536 event->rs = get_remote_state ();
5537 event->ws.kind = TARGET_WAITKIND_IGNORE;
5538 event->ws.value.integer = 0;
5539 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5540 event->regcache = NULL;
5545 case 'T': /* Status with PC, SP, FP, ... */
5546 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5547 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5549 n... = register number
5550 r... = register contents
5553 p = &buf[3]; /* after Txx */
5559 p1 = strchr (p, ':');
5561 error (_("Malformed packet(a) (missing colon): %s\n\
5565 error (_("Malformed packet(a) (missing register number): %s\n\
5569 /* Some "registers" are actually extended stop information.
5570 Note if you're adding a new entry here: GDB 7.9 and
5571 earlier assume that all register "numbers" that start
5572 with an hex digit are real register numbers. Make sure
5573 the server only sends such a packet if it knows the
5574 client understands it. */
5576 if (strncmp (p, "thread", p1 - p) == 0)
5577 event->ptid = read_ptid (++p1, &p);
5578 else if ((strncmp (p, "watch", p1 - p) == 0)
5579 || (strncmp (p, "rwatch", p1 - p) == 0)
5580 || (strncmp (p, "awatch", p1 - p) == 0))
5582 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
5583 p = unpack_varlen_hex (++p1, &addr);
5584 event->watch_data_address = (CORE_ADDR) addr;
5586 else if (strncmp (p, "swbreak", p1 - p) == 0)
5588 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5590 /* Make sure the stub doesn't forget to indicate support
5592 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5593 error (_("Unexpected swbreak stop reason"));
5595 /* The value part is documented as "must be empty",
5596 though we ignore it, in case we ever decide to make
5597 use of it in a backward compatible way. */
5598 p = skip_to_semicolon (p1 + 1);
5600 else if (strncmp (p, "hwbreak", p1 - p) == 0)
5602 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5604 /* Make sure the stub doesn't forget to indicate support
5606 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5607 error (_("Unexpected hwbreak stop reason"));
5610 p = skip_to_semicolon (p1 + 1);
5612 else if (strncmp (p, "library", p1 - p) == 0)
5614 event->ws.kind = TARGET_WAITKIND_LOADED;
5615 p = skip_to_semicolon (p1 + 1);
5617 else if (strncmp (p, "replaylog", p1 - p) == 0)
5619 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5620 /* p1 will indicate "begin" or "end", but it makes
5621 no difference for now, so ignore it. */
5622 p = skip_to_semicolon (p1 + 1);
5624 else if (strncmp (p, "core", p1 - p) == 0)
5628 p = unpack_varlen_hex (++p1, &c);
5636 /* Maybe a real ``P'' register number. */
5637 p_temp = unpack_varlen_hex (p, &pnum);
5638 /* If the first invalid character is the colon, we got a
5639 register number. Otherwise, it's an unknown stop
5643 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5644 cached_reg_t cached_reg;
5647 error (_("Remote sent bad register number %s: %s\n\
5649 hex_string (pnum), p, buf);
5651 cached_reg.num = reg->regnum;
5654 fieldsize = hex2bin (p, cached_reg.data,
5655 register_size (target_gdbarch (),
5658 if (fieldsize < register_size (target_gdbarch (),
5660 warning (_("Remote reply is too short: %s"), buf);
5662 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5666 /* Not a number. Silently skip unknown optional
5668 p = skip_to_semicolon (p1 + 1);
5673 error (_("Remote register badly formatted: %s\nhere: %s"),
5678 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5682 case 'S': /* Old style status, just signal only. */
5686 event->ws.kind = TARGET_WAITKIND_STOPPED;
5687 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5688 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5689 event->ws.value.sig = (enum gdb_signal) sig;
5691 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5694 case 'W': /* Target exited. */
5701 /* GDB used to accept only 2 hex chars here. Stubs should
5702 only send more if they detect GDB supports multi-process
5704 p = unpack_varlen_hex (&buf[1], &value);
5708 /* The remote process exited. */
5709 event->ws.kind = TARGET_WAITKIND_EXITED;
5710 event->ws.value.integer = value;
5714 /* The remote process exited with a signal. */
5715 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5716 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5717 event->ws.value.sig = (enum gdb_signal) value;
5719 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5722 /* If no process is specified, assume inferior_ptid. */
5723 pid = ptid_get_pid (inferior_ptid);
5732 else if (startswith (p, "process:"))
5736 p += sizeof ("process:") - 1;
5737 unpack_varlen_hex (p, &upid);
5741 error (_("unknown stop reply packet: %s"), buf);
5744 error (_("unknown stop reply packet: %s"), buf);
5745 event->ptid = pid_to_ptid (pid);
5750 if (non_stop && ptid_equal (event->ptid, null_ptid))
5751 error (_("No process or thread specified in stop reply: %s"), buf);
5754 /* When the stub wants to tell GDB about a new notification reply, it
5755 sends a notification (%Stop, for example). Those can come it at
5756 any time, hence, we have to make sure that any pending
5757 putpkt/getpkt sequence we're making is finished, before querying
5758 the stub for more events with the corresponding ack command
5759 (vStopped, for example). E.g., if we started a vStopped sequence
5760 immediately upon receiving the notification, something like this
5768 1.6) <-- (registers reply to step #1.3)
5770 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5773 To solve this, whenever we parse a %Stop notification successfully,
5774 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5775 doing whatever we were doing:
5781 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5782 2.5) <-- (registers reply to step #2.3)
5784 Eventualy after step #2.5, we return to the event loop, which
5785 notices there's an event on the
5786 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5787 associated callback --- the function below. At this point, we're
5788 always safe to start a vStopped sequence. :
5791 2.7) <-- T05 thread:2
5797 remote_notif_get_pending_events (struct notif_client *nc)
5799 struct remote_state *rs = get_remote_state ();
5801 if (rs->notif_state->pending_event[nc->id] != NULL)
5804 fprintf_unfiltered (gdb_stdlog,
5805 "notif: process: '%s' ack pending event\n",
5809 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5810 rs->notif_state->pending_event[nc->id] = NULL;
5814 getpkt (&rs->buf, &rs->buf_size, 0);
5815 if (strcmp (rs->buf, "OK") == 0)
5818 remote_notif_ack (nc, rs->buf);
5824 fprintf_unfiltered (gdb_stdlog,
5825 "notif: process: '%s' no pending reply\n",
5830 /* Called when it is decided that STOP_REPLY holds the info of the
5831 event that is to be returned to the core. This function always
5832 destroys STOP_REPLY. */
5835 process_stop_reply (struct stop_reply *stop_reply,
5836 struct target_waitstatus *status)
5840 *status = stop_reply->ws;
5841 ptid = stop_reply->ptid;
5843 /* If no thread/process was reported by the stub, assume the current
5845 if (ptid_equal (ptid, null_ptid))
5846 ptid = inferior_ptid;
5848 if (status->kind != TARGET_WAITKIND_EXITED
5849 && status->kind != TARGET_WAITKIND_SIGNALLED)
5851 struct remote_state *rs = get_remote_state ();
5853 /* Expedited registers. */
5854 if (stop_reply->regcache)
5856 struct regcache *regcache
5857 = get_thread_arch_regcache (ptid, target_gdbarch ());
5862 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5864 regcache_raw_supply (regcache, reg->num, reg->data);
5865 VEC_free (cached_reg_t, stop_reply->regcache);
5868 rs->stop_reason = stop_reply->stop_reason;
5869 rs->remote_watch_data_address = stop_reply->watch_data_address;
5871 remote_notice_new_inferior (ptid, 0);
5872 demand_private_info (ptid)->core = stop_reply->core;
5875 stop_reply_xfree (stop_reply);
5879 /* The non-stop mode version of target_wait. */
5882 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5884 struct remote_state *rs = get_remote_state ();
5885 struct stop_reply *stop_reply;
5889 /* If in non-stop mode, get out of getpkt even if a
5890 notification is received. */
5892 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5893 0 /* forever */, &is_notif);
5896 if (ret != -1 && !is_notif)
5899 case 'E': /* Error of some sort. */
5900 /* We're out of sync with the target now. Did it continue
5901 or not? We can't tell which thread it was in non-stop,
5902 so just ignore this. */
5903 warning (_("Remote failure reply: %s"), rs->buf);
5905 case 'O': /* Console output. */
5906 remote_console_output (rs->buf + 1);
5909 warning (_("Invalid remote reply: %s"), rs->buf);
5913 /* Acknowledge a pending stop reply that may have arrived in the
5915 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
5916 remote_notif_get_pending_events (¬if_client_stop);
5918 /* If indeed we noticed a stop reply, we're done. */
5919 stop_reply = queued_stop_reply (ptid);
5920 if (stop_reply != NULL)
5921 return process_stop_reply (stop_reply, status);
5923 /* Still no event. If we're just polling for an event, then
5924 return to the event loop. */
5925 if (options & TARGET_WNOHANG)
5927 status->kind = TARGET_WAITKIND_IGNORE;
5928 return minus_one_ptid;
5931 /* Otherwise do a blocking wait. */
5932 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5933 1 /* forever */, &is_notif);
5937 /* Wait until the remote machine stops, then return, storing status in
5938 STATUS just as `wait' would. */
5941 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5943 struct remote_state *rs = get_remote_state ();
5944 ptid_t event_ptid = null_ptid;
5946 struct stop_reply *stop_reply;
5950 status->kind = TARGET_WAITKIND_IGNORE;
5951 status->value.integer = 0;
5953 stop_reply = queued_stop_reply (ptid);
5954 if (stop_reply != NULL)
5955 return process_stop_reply (stop_reply, status);
5957 if (rs->cached_wait_status)
5958 /* Use the cached wait status, but only once. */
5959 rs->cached_wait_status = 0;
5965 if (!target_is_async_p ())
5967 ofunc = signal (SIGINT, sync_remote_interrupt);
5968 /* If the user hit C-c before this packet, or between packets,
5969 pretend that it was hit right here. */
5970 if (check_quit_flag ())
5973 sync_remote_interrupt (SIGINT);
5977 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5978 _never_ wait for ever -> test on target_is_async_p().
5979 However, before we do that we need to ensure that the caller
5980 knows how to take the target into/out of async mode. */
5981 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5982 wait_forever_enabled_p, &is_notif);
5984 if (!target_is_async_p ())
5985 signal (SIGINT, ofunc);
5987 /* GDB gets a notification. Return to core as this event is
5989 if (ret != -1 && is_notif)
5990 return minus_one_ptid;
5995 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5997 /* We got something. */
5998 rs->waiting_for_stop_reply = 0;
6000 /* Assume that the target has acknowledged Ctrl-C unless we receive
6001 an 'F' or 'O' packet. */
6002 if (buf[0] != 'F' && buf[0] != 'O')
6003 rs->ctrlc_pending_p = 0;
6007 case 'E': /* Error of some sort. */
6008 /* We're out of sync with the target now. Did it continue or
6009 not? Not is more likely, so report a stop. */
6010 warning (_("Remote failure reply: %s"), buf);
6011 status->kind = TARGET_WAITKIND_STOPPED;
6012 status->value.sig = GDB_SIGNAL_0;
6014 case 'F': /* File-I/O request. */
6015 remote_fileio_request (buf, rs->ctrlc_pending_p);
6016 rs->ctrlc_pending_p = 0;
6018 case 'T': case 'S': case 'X': case 'W':
6020 struct stop_reply *stop_reply
6021 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6024 event_ptid = process_stop_reply (stop_reply, status);
6027 case 'O': /* Console output. */
6028 remote_console_output (buf + 1);
6030 /* The target didn't really stop; keep waiting. */
6031 rs->waiting_for_stop_reply = 1;
6035 if (rs->last_sent_signal != GDB_SIGNAL_0)
6037 /* Zero length reply means that we tried 'S' or 'C' and the
6038 remote system doesn't support it. */
6039 target_terminal_ours_for_output ();
6041 ("Can't send signals to this remote system. %s not sent.\n",
6042 gdb_signal_to_name (rs->last_sent_signal));
6043 rs->last_sent_signal = GDB_SIGNAL_0;
6044 target_terminal_inferior ();
6046 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6047 putpkt ((char *) buf);
6049 /* We just told the target to resume, so a stop reply is in
6051 rs->waiting_for_stop_reply = 1;
6054 /* else fallthrough */
6056 warning (_("Invalid remote reply: %s"), buf);
6058 rs->waiting_for_stop_reply = 1;
6062 if (status->kind == TARGET_WAITKIND_IGNORE)
6064 /* Nothing interesting happened. If we're doing a non-blocking
6065 poll, we're done. Otherwise, go back to waiting. */
6066 if (options & TARGET_WNOHANG)
6067 return minus_one_ptid;
6071 else if (status->kind != TARGET_WAITKIND_EXITED
6072 && status->kind != TARGET_WAITKIND_SIGNALLED)
6074 if (!ptid_equal (event_ptid, null_ptid))
6075 record_currthread (rs, event_ptid);
6077 event_ptid = inferior_ptid;
6080 /* A process exit. Invalidate our notion of current thread. */
6081 record_currthread (rs, minus_one_ptid);
6086 /* Wait until the remote machine stops, then return, storing status in
6087 STATUS just as `wait' would. */
6090 remote_wait (struct target_ops *ops,
6091 ptid_t ptid, struct target_waitstatus *status, int options)
6096 event_ptid = remote_wait_ns (ptid, status, options);
6098 event_ptid = remote_wait_as (ptid, status, options);
6100 if (target_is_async_p ())
6102 /* If there are are events left in the queue tell the event loop
6104 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6105 mark_async_event_handler (remote_async_inferior_event_token);
6111 /* Fetch a single register using a 'p' packet. */
6114 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6116 struct remote_state *rs = get_remote_state ();
6118 char regp[MAX_REGISTER_SIZE];
6121 if (packet_support (PACKET_p) == PACKET_DISABLE)
6124 if (reg->pnum == -1)
6129 p += hexnumstr (p, reg->pnum);
6132 getpkt (&rs->buf, &rs->buf_size, 0);
6136 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6140 case PACKET_UNKNOWN:
6143 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6144 gdbarch_register_name (get_regcache_arch (regcache),
6149 /* If this register is unfetchable, tell the regcache. */
6152 regcache_raw_supply (regcache, reg->regnum, NULL);
6156 /* Otherwise, parse and supply the value. */
6162 error (_("fetch_register_using_p: early buf termination"));
6164 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6167 regcache_raw_supply (regcache, reg->regnum, regp);
6171 /* Fetch the registers included in the target's 'g' packet. */
6174 send_g_packet (void)
6176 struct remote_state *rs = get_remote_state ();
6179 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6180 remote_send (&rs->buf, &rs->buf_size);
6182 /* We can get out of synch in various cases. If the first character
6183 in the buffer is not a hex character, assume that has happened
6184 and try to fetch another packet to read. */
6185 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6186 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6187 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6188 && rs->buf[0] != 'x') /* New: unavailable register value. */
6191 fprintf_unfiltered (gdb_stdlog,
6192 "Bad register packet; fetching a new packet\n");
6193 getpkt (&rs->buf, &rs->buf_size, 0);
6196 buf_len = strlen (rs->buf);
6198 /* Sanity check the received packet. */
6199 if (buf_len % 2 != 0)
6200 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6206 process_g_packet (struct regcache *regcache)
6208 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6209 struct remote_state *rs = get_remote_state ();
6210 struct remote_arch_state *rsa = get_remote_arch_state ();
6215 buf_len = strlen (rs->buf);
6217 /* Further sanity checks, with knowledge of the architecture. */
6218 if (buf_len > 2 * rsa->sizeof_g_packet)
6219 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6221 /* Save the size of the packet sent to us by the target. It is used
6222 as a heuristic when determining the max size of packets that the
6223 target can safely receive. */
6224 if (rsa->actual_register_packet_size == 0)
6225 rsa->actual_register_packet_size = buf_len;
6227 /* If this is smaller than we guessed the 'g' packet would be,
6228 update our records. A 'g' reply that doesn't include a register's
6229 value implies either that the register is not available, or that
6230 the 'p' packet must be used. */
6231 if (buf_len < 2 * rsa->sizeof_g_packet)
6233 rsa->sizeof_g_packet = buf_len / 2;
6235 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6237 if (rsa->regs[i].pnum == -1)
6240 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6241 rsa->regs[i].in_g_packet = 0;
6243 rsa->regs[i].in_g_packet = 1;
6247 regs = alloca (rsa->sizeof_g_packet);
6249 /* Unimplemented registers read as all bits zero. */
6250 memset (regs, 0, rsa->sizeof_g_packet);
6252 /* Reply describes registers byte by byte, each byte encoded as two
6253 hex characters. Suck them all up, then supply them to the
6254 register cacheing/storage mechanism. */
6257 for (i = 0; i < rsa->sizeof_g_packet; i++)
6259 if (p[0] == 0 || p[1] == 0)
6260 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6261 internal_error (__FILE__, __LINE__,
6262 _("unexpected end of 'g' packet reply"));
6264 if (p[0] == 'x' && p[1] == 'x')
6265 regs[i] = 0; /* 'x' */
6267 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6271 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6273 struct packet_reg *r = &rsa->regs[i];
6277 if (r->offset * 2 >= strlen (rs->buf))
6278 /* This shouldn't happen - we adjusted in_g_packet above. */
6279 internal_error (__FILE__, __LINE__,
6280 _("unexpected end of 'g' packet reply"));
6281 else if (rs->buf[r->offset * 2] == 'x')
6283 gdb_assert (r->offset * 2 < strlen (rs->buf));
6284 /* The register isn't available, mark it as such (at
6285 the same time setting the value to zero). */
6286 regcache_raw_supply (regcache, r->regnum, NULL);
6289 regcache_raw_supply (regcache, r->regnum,
6296 fetch_registers_using_g (struct regcache *regcache)
6299 process_g_packet (regcache);
6302 /* Make the remote selected traceframe match GDB's selected
6306 set_remote_traceframe (void)
6309 struct remote_state *rs = get_remote_state ();
6311 if (rs->remote_traceframe_number == get_traceframe_number ())
6314 /* Avoid recursion, remote_trace_find calls us again. */
6315 rs->remote_traceframe_number = get_traceframe_number ();
6317 newnum = target_trace_find (tfind_number,
6318 get_traceframe_number (), 0, 0, NULL);
6320 /* Should not happen. If it does, all bets are off. */
6321 if (newnum != get_traceframe_number ())
6322 warning (_("could not set remote traceframe"));
6326 remote_fetch_registers (struct target_ops *ops,
6327 struct regcache *regcache, int regnum)
6329 struct remote_arch_state *rsa = get_remote_arch_state ();
6332 set_remote_traceframe ();
6333 set_general_thread (inferior_ptid);
6337 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6339 gdb_assert (reg != NULL);
6341 /* If this register might be in the 'g' packet, try that first -
6342 we are likely to read more than one register. If this is the
6343 first 'g' packet, we might be overly optimistic about its
6344 contents, so fall back to 'p'. */
6345 if (reg->in_g_packet)
6347 fetch_registers_using_g (regcache);
6348 if (reg->in_g_packet)
6352 if (fetch_register_using_p (regcache, reg))
6355 /* This register is not available. */
6356 regcache_raw_supply (regcache, reg->regnum, NULL);
6361 fetch_registers_using_g (regcache);
6363 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6364 if (!rsa->regs[i].in_g_packet)
6365 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6367 /* This register is not available. */
6368 regcache_raw_supply (regcache, i, NULL);
6372 /* Prepare to store registers. Since we may send them all (using a
6373 'G' request), we have to read out the ones we don't want to change
6377 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6379 struct remote_arch_state *rsa = get_remote_arch_state ();
6381 gdb_byte buf[MAX_REGISTER_SIZE];
6383 /* Make sure the entire registers array is valid. */
6384 switch (packet_support (PACKET_P))
6386 case PACKET_DISABLE:
6387 case PACKET_SUPPORT_UNKNOWN:
6388 /* Make sure all the necessary registers are cached. */
6389 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6390 if (rsa->regs[i].in_g_packet)
6391 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6398 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6399 packet was not recognized. */
6402 store_register_using_P (const struct regcache *regcache,
6403 struct packet_reg *reg)
6405 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6406 struct remote_state *rs = get_remote_state ();
6407 /* Try storing a single register. */
6408 char *buf = rs->buf;
6409 gdb_byte regp[MAX_REGISTER_SIZE];
6412 if (packet_support (PACKET_P) == PACKET_DISABLE)
6415 if (reg->pnum == -1)
6418 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6419 p = buf + strlen (buf);
6420 regcache_raw_collect (regcache, reg->regnum, regp);
6421 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6423 getpkt (&rs->buf, &rs->buf_size, 0);
6425 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6430 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6431 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6432 case PACKET_UNKNOWN:
6435 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6439 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6440 contents of the register cache buffer. FIXME: ignores errors. */
6443 store_registers_using_G (const struct regcache *regcache)
6445 struct remote_state *rs = get_remote_state ();
6446 struct remote_arch_state *rsa = get_remote_arch_state ();
6450 /* Extract all the registers in the regcache copying them into a
6455 regs = alloca (rsa->sizeof_g_packet);
6456 memset (regs, 0, rsa->sizeof_g_packet);
6457 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6459 struct packet_reg *r = &rsa->regs[i];
6462 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6466 /* Command describes registers byte by byte,
6467 each byte encoded as two hex characters. */
6470 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6472 bin2hex (regs, p, rsa->sizeof_g_packet);
6474 getpkt (&rs->buf, &rs->buf_size, 0);
6475 if (packet_check_result (rs->buf) == PACKET_ERROR)
6476 error (_("Could not write registers; remote failure reply '%s'"),
6480 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6481 of the register cache buffer. FIXME: ignores errors. */
6484 remote_store_registers (struct target_ops *ops,
6485 struct regcache *regcache, int regnum)
6487 struct remote_arch_state *rsa = get_remote_arch_state ();
6490 set_remote_traceframe ();
6491 set_general_thread (inferior_ptid);
6495 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6497 gdb_assert (reg != NULL);
6499 /* Always prefer to store registers using the 'P' packet if
6500 possible; we often change only a small number of registers.
6501 Sometimes we change a larger number; we'd need help from a
6502 higher layer to know to use 'G'. */
6503 if (store_register_using_P (regcache, reg))
6506 /* For now, don't complain if we have no way to write the
6507 register. GDB loses track of unavailable registers too
6508 easily. Some day, this may be an error. We don't have
6509 any way to read the register, either... */
6510 if (!reg->in_g_packet)
6513 store_registers_using_G (regcache);
6517 store_registers_using_G (regcache);
6519 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6520 if (!rsa->regs[i].in_g_packet)
6521 if (!store_register_using_P (regcache, &rsa->regs[i]))
6522 /* See above for why we do not issue an error here. */
6527 /* Return the number of hex digits in num. */
6530 hexnumlen (ULONGEST num)
6534 for (i = 0; num != 0; i++)
6540 /* Set BUF to the minimum number of hex digits representing NUM. */
6543 hexnumstr (char *buf, ULONGEST num)
6545 int len = hexnumlen (num);
6547 return hexnumnstr (buf, num, len);
6551 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6554 hexnumnstr (char *buf, ULONGEST num, int width)
6560 for (i = width - 1; i >= 0; i--)
6562 buf[i] = "0123456789abcdef"[(num & 0xf)];
6569 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6572 remote_address_masked (CORE_ADDR addr)
6574 unsigned int address_size = remote_address_size;
6576 /* If "remoteaddresssize" was not set, default to target address size. */
6578 address_size = gdbarch_addr_bit (target_gdbarch ());
6580 if (address_size > 0
6581 && address_size < (sizeof (ULONGEST) * 8))
6583 /* Only create a mask when that mask can safely be constructed
6584 in a ULONGEST variable. */
6587 mask = (mask << address_size) - 1;
6593 /* Determine whether the remote target supports binary downloading.
6594 This is accomplished by sending a no-op memory write of zero length
6595 to the target at the specified address. It does not suffice to send
6596 the whole packet, since many stubs strip the eighth bit and
6597 subsequently compute a wrong checksum, which causes real havoc with
6600 NOTE: This can still lose if the serial line is not eight-bit
6601 clean. In cases like this, the user should clear "remote
6605 check_binary_download (CORE_ADDR addr)
6607 struct remote_state *rs = get_remote_state ();
6609 switch (packet_support (PACKET_X))
6611 case PACKET_DISABLE:
6615 case PACKET_SUPPORT_UNKNOWN:
6621 p += hexnumstr (p, (ULONGEST) addr);
6623 p += hexnumstr (p, (ULONGEST) 0);
6627 putpkt_binary (rs->buf, (int) (p - rs->buf));
6628 getpkt (&rs->buf, &rs->buf_size, 0);
6630 if (rs->buf[0] == '\0')
6633 fprintf_unfiltered (gdb_stdlog,
6634 "binary downloading NOT "
6635 "supported by target\n");
6636 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6641 fprintf_unfiltered (gdb_stdlog,
6642 "binary downloading supported by target\n");
6643 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6650 /* Write memory data directly to the remote machine.
6651 This does not inform the data cache; the data cache uses this.
6652 HEADER is the starting part of the packet.
6653 MEMADDR is the address in the remote memory space.
6654 MYADDR is the address of the buffer in our space.
6655 LEN is the number of bytes.
6656 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6657 should send data as binary ('X'), or hex-encoded ('M').
6659 The function creates packet of the form
6660 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6662 where encoding of <DATA> is termined by PACKET_FORMAT.
6664 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6667 Return the transferred status, error or OK (an
6668 'enum target_xfer_status' value). Save the number of bytes
6669 transferred in *XFERED_LEN. Only transfer a single packet. */
6671 static enum target_xfer_status
6672 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6673 const gdb_byte *myaddr, ULONGEST len,
6674 ULONGEST *xfered_len, char packet_format,
6677 struct remote_state *rs = get_remote_state ();
6687 if (packet_format != 'X' && packet_format != 'M')
6688 internal_error (__FILE__, __LINE__,
6689 _("remote_write_bytes_aux: bad packet format"));
6692 return TARGET_XFER_EOF;
6694 payload_size = get_memory_write_packet_size ();
6696 /* The packet buffer will be large enough for the payload;
6697 get_memory_packet_size ensures this. */
6700 /* Compute the size of the actual payload by subtracting out the
6701 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6703 payload_size -= strlen ("$,:#NN");
6705 /* The comma won't be used. */
6707 header_length = strlen (header);
6708 payload_size -= header_length;
6709 payload_size -= hexnumlen (memaddr);
6711 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6713 strcat (rs->buf, header);
6714 p = rs->buf + strlen (header);
6716 /* Compute a best guess of the number of bytes actually transfered. */
6717 if (packet_format == 'X')
6719 /* Best guess at number of bytes that will fit. */
6720 todo = min (len, payload_size);
6722 payload_size -= hexnumlen (todo);
6723 todo = min (todo, payload_size);
6727 /* Num bytes that will fit. */
6728 todo = min (len, payload_size / 2);
6730 payload_size -= hexnumlen (todo);
6731 todo = min (todo, payload_size / 2);
6735 internal_error (__FILE__, __LINE__,
6736 _("minimum packet size too small to write data"));
6738 /* If we already need another packet, then try to align the end
6739 of this packet to a useful boundary. */
6740 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6741 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6743 /* Append "<memaddr>". */
6744 memaddr = remote_address_masked (memaddr);
6745 p += hexnumstr (p, (ULONGEST) memaddr);
6752 /* Append <len>. Retain the location/size of <len>. It may need to
6753 be adjusted once the packet body has been created. */
6755 plenlen = hexnumstr (p, (ULONGEST) todo);
6763 /* Append the packet body. */
6764 if (packet_format == 'X')
6766 /* Binary mode. Send target system values byte by byte, in
6767 increasing byte addresses. Only escape certain critical
6769 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6770 &nr_bytes, payload_size);
6772 /* If not all TODO bytes fit, then we'll need another packet. Make
6773 a second try to keep the end of the packet aligned. Don't do
6774 this if the packet is tiny. */
6775 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6779 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6781 if (new_nr_bytes != nr_bytes)
6782 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6783 (gdb_byte *) p, &nr_bytes,
6787 p += payload_length;
6788 if (use_length && nr_bytes < todo)
6790 /* Escape chars have filled up the buffer prematurely,
6791 and we have actually sent fewer bytes than planned.
6792 Fix-up the length field of the packet. Use the same
6793 number of characters as before. */
6794 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6795 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6800 /* Normal mode: Send target system values byte by byte, in
6801 increasing byte addresses. Each byte is encoded as a two hex
6803 nr_bytes = bin2hex (myaddr, p, todo);
6807 putpkt_binary (rs->buf, (int) (p - rs->buf));
6808 getpkt (&rs->buf, &rs->buf_size, 0);
6810 if (rs->buf[0] == 'E')
6811 return TARGET_XFER_E_IO;
6813 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6814 fewer bytes than we'd planned. */
6815 *xfered_len = (ULONGEST) nr_bytes;
6816 return TARGET_XFER_OK;
6819 /* Write memory data directly to the remote machine.
6820 This does not inform the data cache; the data cache uses this.
6821 MEMADDR is the address in the remote memory space.
6822 MYADDR is the address of the buffer in our space.
6823 LEN is the number of bytes.
6825 Return the transferred status, error or OK (an
6826 'enum target_xfer_status' value). Save the number of bytes
6827 transferred in *XFERED_LEN. Only transfer a single packet. */
6829 static enum target_xfer_status
6830 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6831 ULONGEST *xfered_len)
6833 char *packet_format = 0;
6835 /* Check whether the target supports binary download. */
6836 check_binary_download (memaddr);
6838 switch (packet_support (PACKET_X))
6841 packet_format = "X";
6843 case PACKET_DISABLE:
6844 packet_format = "M";
6846 case PACKET_SUPPORT_UNKNOWN:
6847 internal_error (__FILE__, __LINE__,
6848 _("remote_write_bytes: bad internal state"));
6850 internal_error (__FILE__, __LINE__, _("bad switch"));
6853 return remote_write_bytes_aux (packet_format,
6854 memaddr, myaddr, len, xfered_len,
6855 packet_format[0], 1);
6858 /* Read memory data directly from the remote machine.
6859 This does not use the data cache; the data cache uses this.
6860 MEMADDR is the address in the remote memory space.
6861 MYADDR is the address of the buffer in our space.
6862 LEN is the number of bytes.
6864 Return the transferred status, error or OK (an
6865 'enum target_xfer_status' value). Save the number of bytes
6866 transferred in *XFERED_LEN. */
6868 static enum target_xfer_status
6869 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6870 ULONGEST *xfered_len)
6872 struct remote_state *rs = get_remote_state ();
6873 int max_buf_size; /* Max size of packet output buffer. */
6878 max_buf_size = get_memory_read_packet_size ();
6879 /* The packet buffer will be large enough for the payload;
6880 get_memory_packet_size ensures this. */
6882 /* Number if bytes that will fit. */
6883 todo = min (len, max_buf_size / 2);
6885 /* Construct "m"<memaddr>","<len>". */
6886 memaddr = remote_address_masked (memaddr);
6889 p += hexnumstr (p, (ULONGEST) memaddr);
6891 p += hexnumstr (p, (ULONGEST) todo);
6894 getpkt (&rs->buf, &rs->buf_size, 0);
6895 if (rs->buf[0] == 'E'
6896 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6897 && rs->buf[3] == '\0')
6898 return TARGET_XFER_E_IO;
6899 /* Reply describes memory byte by byte, each byte encoded as two hex
6902 i = hex2bin (p, myaddr, todo);
6903 /* Return what we have. Let higher layers handle partial reads. */
6904 *xfered_len = (ULONGEST) i;
6905 return TARGET_XFER_OK;
6908 /* Using the set of read-only target sections of remote, read live
6911 For interface/parameters/return description see target.h,
6914 static enum target_xfer_status
6915 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6916 ULONGEST memaddr, ULONGEST len,
6917 ULONGEST *xfered_len)
6919 struct target_section *secp;
6920 struct target_section_table *table;
6922 secp = target_section_by_addr (ops, memaddr);
6924 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6925 secp->the_bfd_section)
6928 struct target_section *p;
6929 ULONGEST memend = memaddr + len;
6931 table = target_get_section_table (ops);
6933 for (p = table->sections; p < table->sections_end; p++)
6935 if (memaddr >= p->addr)
6937 if (memend <= p->endaddr)
6939 /* Entire transfer is within this section. */
6940 return remote_read_bytes_1 (memaddr, readbuf, len,
6943 else if (memaddr >= p->endaddr)
6945 /* This section ends before the transfer starts. */
6950 /* This section overlaps the transfer. Just do half. */
6951 len = p->endaddr - memaddr;
6952 return remote_read_bytes_1 (memaddr, readbuf, len,
6959 return TARGET_XFER_EOF;
6962 /* Similar to remote_read_bytes_1, but it reads from the remote stub
6963 first if the requested memory is unavailable in traceframe.
6964 Otherwise, fall back to remote_read_bytes_1. */
6966 static enum target_xfer_status
6967 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6968 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
6971 return TARGET_XFER_EOF;
6973 if (get_traceframe_number () != -1)
6975 VEC(mem_range_s) *available;
6977 /* If we fail to get the set of available memory, then the
6978 target does not support querying traceframe info, and so we
6979 attempt reading from the traceframe anyway (assuming the
6980 target implements the old QTro packet then). */
6981 if (traceframe_available_memory (&available, memaddr, len))
6983 struct cleanup *old_chain;
6985 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6987 if (VEC_empty (mem_range_s, available)
6988 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6990 enum target_xfer_status res;
6992 /* Don't read into the traceframe's available
6994 if (!VEC_empty (mem_range_s, available))
6996 LONGEST oldlen = len;
6998 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
6999 gdb_assert (len <= oldlen);
7002 do_cleanups (old_chain);
7004 /* This goes through the topmost target again. */
7005 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7007 if (res == TARGET_XFER_OK)
7008 return TARGET_XFER_OK;
7011 /* No use trying further, we know some memory starting
7012 at MEMADDR isn't available. */
7014 return TARGET_XFER_UNAVAILABLE;
7018 /* Don't try to read more than how much is available, in
7019 case the target implements the deprecated QTro packet to
7020 cater for older GDBs (the target's knowledge of read-only
7021 sections may be outdated by now). */
7022 len = VEC_index (mem_range_s, available, 0)->length;
7024 do_cleanups (old_chain);
7028 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
7033 /* Sends a packet with content determined by the printf format string
7034 FORMAT and the remaining arguments, then gets the reply. Returns
7035 whether the packet was a success, a failure, or unknown. */
7037 static enum packet_result remote_send_printf (const char *format, ...)
7038 ATTRIBUTE_PRINTF (1, 2);
7040 static enum packet_result
7041 remote_send_printf (const char *format, ...)
7043 struct remote_state *rs = get_remote_state ();
7044 int max_size = get_remote_packet_size ();
7047 va_start (ap, format);
7050 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7051 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7053 if (putpkt (rs->buf) < 0)
7054 error (_("Communication problem with target."));
7057 getpkt (&rs->buf, &rs->buf_size, 0);
7059 return packet_check_result (rs->buf);
7063 restore_remote_timeout (void *p)
7065 int value = *(int *)p;
7067 remote_timeout = value;
7070 /* Flash writing can take quite some time. We'll set
7071 effectively infinite timeout for flash operations.
7072 In future, we'll need to decide on a better approach. */
7073 static const int remote_flash_timeout = 1000;
7076 remote_flash_erase (struct target_ops *ops,
7077 ULONGEST address, LONGEST length)
7079 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7080 int saved_remote_timeout = remote_timeout;
7081 enum packet_result ret;
7082 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7083 &saved_remote_timeout);
7085 remote_timeout = remote_flash_timeout;
7087 ret = remote_send_printf ("vFlashErase:%s,%s",
7088 phex (address, addr_size),
7092 case PACKET_UNKNOWN:
7093 error (_("Remote target does not support flash erase"));
7095 error (_("Error erasing flash with vFlashErase packet"));
7100 do_cleanups (back_to);
7103 static enum target_xfer_status
7104 remote_flash_write (struct target_ops *ops, ULONGEST address,
7105 ULONGEST length, ULONGEST *xfered_len,
7106 const gdb_byte *data)
7108 int saved_remote_timeout = remote_timeout;
7109 enum target_xfer_status ret;
7110 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7111 &saved_remote_timeout);
7113 remote_timeout = remote_flash_timeout;
7114 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7116 do_cleanups (back_to);
7122 remote_flash_done (struct target_ops *ops)
7124 int saved_remote_timeout = remote_timeout;
7126 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7127 &saved_remote_timeout);
7129 remote_timeout = remote_flash_timeout;
7130 ret = remote_send_printf ("vFlashDone");
7131 do_cleanups (back_to);
7135 case PACKET_UNKNOWN:
7136 error (_("Remote target does not support vFlashDone"));
7138 error (_("Error finishing flash operation"));
7145 remote_files_info (struct target_ops *ignore)
7147 puts_filtered ("Debugging a target over a serial line.\n");
7150 /* Stuff for dealing with the packets which are part of this protocol.
7151 See comment at top of file for details. */
7153 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7154 error to higher layers. Called when a serial error is detected.
7155 The exception message is STRING, followed by a colon and a blank,
7156 the system error message for errno at function entry and final dot
7157 for output compatibility with throw_perror_with_name. */
7160 unpush_and_perror (const char *string)
7162 int saved_errno = errno;
7164 remote_unpush_target ();
7165 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7166 safe_strerror (saved_errno));
7169 /* Read a single character from the remote end. */
7172 readchar (int timeout)
7175 struct remote_state *rs = get_remote_state ();
7177 ch = serial_readchar (rs->remote_desc, timeout);
7182 switch ((enum serial_rc) ch)
7185 remote_unpush_target ();
7186 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7189 unpush_and_perror (_("Remote communication error. "
7190 "Target disconnected."));
7192 case SERIAL_TIMEOUT:
7198 /* Wrapper for serial_write that closes the target and throws if
7202 remote_serial_write (const char *str, int len)
7204 struct remote_state *rs = get_remote_state ();
7206 if (serial_write (rs->remote_desc, str, len))
7208 unpush_and_perror (_("Remote communication error. "
7209 "Target disconnected."));
7213 /* Send the command in *BUF to the remote machine, and read the reply
7214 into *BUF. Report an error if we get an error reply. Resize
7215 *BUF using xrealloc if necessary to hold the result, and update
7219 remote_send (char **buf,
7223 getpkt (buf, sizeof_buf, 0);
7225 if ((*buf)[0] == 'E')
7226 error (_("Remote failure reply: %s"), *buf);
7229 /* Return a pointer to an xmalloc'ed string representing an escaped
7230 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7231 etc. The caller is responsible for releasing the returned
7235 escape_buffer (const char *buf, int n)
7237 struct cleanup *old_chain;
7238 struct ui_file *stb;
7241 stb = mem_fileopen ();
7242 old_chain = make_cleanup_ui_file_delete (stb);
7244 fputstrn_unfiltered (buf, n, '\\', stb);
7245 str = ui_file_xstrdup (stb, NULL);
7246 do_cleanups (old_chain);
7250 /* Display a null-terminated packet on stdout, for debugging, using C
7254 print_packet (const char *buf)
7256 puts_filtered ("\"");
7257 fputstr_filtered (buf, '"', gdb_stdout);
7258 puts_filtered ("\"");
7262 putpkt (const char *buf)
7264 return putpkt_binary (buf, strlen (buf));
7267 /* Send a packet to the remote machine, with error checking. The data
7268 of the packet is in BUF. The string in BUF can be at most
7269 get_remote_packet_size () - 5 to account for the $, # and checksum,
7270 and for a possible /0 if we are debugging (remote_debug) and want
7271 to print the sent packet as a string. */
7274 putpkt_binary (const char *buf, int cnt)
7276 struct remote_state *rs = get_remote_state ();
7278 unsigned char csum = 0;
7279 char *buf2 = alloca (cnt + 6);
7286 /* Catch cases like trying to read memory or listing threads while
7287 we're waiting for a stop reply. The remote server wouldn't be
7288 ready to handle this request, so we'd hang and timeout. We don't
7289 have to worry about this in synchronous mode, because in that
7290 case it's not possible to issue a command while the target is
7291 running. This is not a problem in non-stop mode, because in that
7292 case, the stub is always ready to process serial input. */
7293 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7295 error (_("Cannot execute this command while the target is running.\n"
7296 "Use the \"interrupt\" command to stop the target\n"
7297 "and then try again."));
7300 /* We're sending out a new packet. Make sure we don't look at a
7301 stale cached response. */
7302 rs->cached_wait_status = 0;
7304 /* Copy the packet into buffer BUF2, encapsulating it
7305 and giving it a checksum. */
7310 for (i = 0; i < cnt; i++)
7316 *p++ = tohex ((csum >> 4) & 0xf);
7317 *p++ = tohex (csum & 0xf);
7319 /* Send it over and over until we get a positive ack. */
7323 int started_error_output = 0;
7327 struct cleanup *old_chain;
7331 str = escape_buffer (buf2, p - buf2);
7332 old_chain = make_cleanup (xfree, str);
7333 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7334 gdb_flush (gdb_stdlog);
7335 do_cleanups (old_chain);
7337 remote_serial_write (buf2, p - buf2);
7339 /* If this is a no acks version of the remote protocol, send the
7340 packet and move on. */
7344 /* Read until either a timeout occurs (-2) or '+' is read.
7345 Handle any notification that arrives in the mean time. */
7348 ch = readchar (remote_timeout);
7356 case SERIAL_TIMEOUT:
7359 if (started_error_output)
7361 putchar_unfiltered ('\n');
7362 started_error_output = 0;
7371 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7375 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7377 case SERIAL_TIMEOUT:
7381 break; /* Retransmit buffer. */
7385 fprintf_unfiltered (gdb_stdlog,
7386 "Packet instead of Ack, ignoring it\n");
7387 /* It's probably an old response sent because an ACK
7388 was lost. Gobble up the packet and ack it so it
7389 doesn't get retransmitted when we resend this
7392 remote_serial_write ("+", 1);
7393 continue; /* Now, go look for +. */
7400 /* If we got a notification, handle it, and go back to looking
7402 /* We've found the start of a notification. Now
7403 collect the data. */
7404 val = read_frame (&rs->buf, &rs->buf_size);
7409 struct cleanup *old_chain;
7412 str = escape_buffer (rs->buf, val);
7413 old_chain = make_cleanup (xfree, str);
7414 fprintf_unfiltered (gdb_stdlog,
7415 " Notification received: %s\n",
7417 do_cleanups (old_chain);
7419 handle_notification (rs->notif_state, rs->buf);
7420 /* We're in sync now, rewait for the ack. */
7427 if (!started_error_output)
7429 started_error_output = 1;
7430 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7432 fputc_unfiltered (ch & 0177, gdb_stdlog);
7433 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7442 if (!started_error_output)
7444 started_error_output = 1;
7445 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7447 fputc_unfiltered (ch & 0177, gdb_stdlog);
7451 break; /* Here to retransmit. */
7455 /* This is wrong. If doing a long backtrace, the user should be
7456 able to get out next time we call QUIT, without anything as
7457 violent as interrupt_query. If we want to provide a way out of
7458 here without getting to the next QUIT, it should be based on
7459 hitting ^C twice as in remote_wait. */
7470 /* Come here after finding the start of a frame when we expected an
7471 ack. Do our best to discard the rest of this packet. */
7480 c = readchar (remote_timeout);
7483 case SERIAL_TIMEOUT:
7484 /* Nothing we can do. */
7487 /* Discard the two bytes of checksum and stop. */
7488 c = readchar (remote_timeout);
7490 c = readchar (remote_timeout);
7493 case '*': /* Run length encoding. */
7494 /* Discard the repeat count. */
7495 c = readchar (remote_timeout);
7500 /* A regular character. */
7506 /* Come here after finding the start of the frame. Collect the rest
7507 into *BUF, verifying the checksum, length, and handling run-length
7508 compression. NUL terminate the buffer. If there is not enough room,
7509 expand *BUF using xrealloc.
7511 Returns -1 on error, number of characters in buffer (ignoring the
7512 trailing NULL) on success. (could be extended to return one of the
7513 SERIAL status indications). */
7516 read_frame (char **buf_p,
7523 struct remote_state *rs = get_remote_state ();
7530 c = readchar (remote_timeout);
7533 case SERIAL_TIMEOUT:
7535 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7539 fputs_filtered ("Saw new packet start in middle of old one\n",
7541 return -1; /* Start a new packet, count retries. */
7544 unsigned char pktcsum;
7550 check_0 = readchar (remote_timeout);
7552 check_1 = readchar (remote_timeout);
7554 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7557 fputs_filtered ("Timeout in checksum, retrying\n",
7561 else if (check_0 < 0 || check_1 < 0)
7564 fputs_filtered ("Communication error in checksum\n",
7569 /* Don't recompute the checksum; with no ack packets we
7570 don't have any way to indicate a packet retransmission
7575 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7576 if (csum == pktcsum)
7581 struct cleanup *old_chain;
7584 str = escape_buffer (buf, bc);
7585 old_chain = make_cleanup (xfree, str);
7586 fprintf_unfiltered (gdb_stdlog,
7587 "Bad checksum, sentsum=0x%x, "
7588 "csum=0x%x, buf=%s\n",
7589 pktcsum, csum, str);
7590 do_cleanups (old_chain);
7592 /* Number of characters in buffer ignoring trailing
7596 case '*': /* Run length encoding. */
7601 c = readchar (remote_timeout);
7603 repeat = c - ' ' + 3; /* Compute repeat count. */
7605 /* The character before ``*'' is repeated. */
7607 if (repeat > 0 && repeat <= 255 && bc > 0)
7609 if (bc + repeat - 1 >= *sizeof_buf - 1)
7611 /* Make some more room in the buffer. */
7612 *sizeof_buf += repeat;
7613 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7617 memset (&buf[bc], buf[bc - 1], repeat);
7623 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7627 if (bc >= *sizeof_buf - 1)
7629 /* Make some more room in the buffer. */
7631 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7642 /* Read a packet from the remote machine, with error checking, and
7643 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7644 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7645 rather than timing out; this is used (in synchronous mode) to wait
7646 for a target that is is executing user code to stop. */
7647 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7648 don't have to change all the calls to getpkt to deal with the
7649 return value, because at the moment I don't know what the right
7650 thing to do it for those. */
7658 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7662 /* Read a packet from the remote machine, with error checking, and
7663 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7664 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7665 rather than timing out; this is used (in synchronous mode) to wait
7666 for a target that is is executing user code to stop. If FOREVER ==
7667 0, this function is allowed to time out gracefully and return an
7668 indication of this to the caller. Otherwise return the number of
7669 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7670 enough reason to return to the caller. *IS_NOTIF is an output
7671 boolean that indicates whether *BUF holds a notification or not
7672 (a regular packet). */
7675 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7676 int expecting_notif, int *is_notif)
7678 struct remote_state *rs = get_remote_state ();
7684 /* We're reading a new response. Make sure we don't look at a
7685 previously cached response. */
7686 rs->cached_wait_status = 0;
7688 strcpy (*buf, "timeout");
7691 timeout = watchdog > 0 ? watchdog : -1;
7692 else if (expecting_notif)
7693 timeout = 0; /* There should already be a char in the buffer. If
7696 timeout = remote_timeout;
7700 /* Process any number of notifications, and then return when
7704 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
7706 for (tries = 1; tries <= MAX_TRIES; tries++)
7708 /* This can loop forever if the remote side sends us
7709 characters continuously, but if it pauses, we'll get
7710 SERIAL_TIMEOUT from readchar because of timeout. Then
7711 we'll count that as a retry.
7713 Note that even when forever is set, we will only wait
7714 forever prior to the start of a packet. After that, we
7715 expect characters to arrive at a brisk pace. They should
7716 show up within remote_timeout intervals. */
7718 c = readchar (timeout);
7719 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7721 if (c == SERIAL_TIMEOUT)
7723 if (expecting_notif)
7724 return -1; /* Don't complain, it's normal to not get
7725 anything in this case. */
7727 if (forever) /* Watchdog went off? Kill the target. */
7730 remote_unpush_target ();
7731 throw_error (TARGET_CLOSE_ERROR,
7732 _("Watchdog timeout has expired. "
7733 "Target detached."));
7736 fputs_filtered ("Timed out.\n", gdb_stdlog);
7740 /* We've found the start of a packet or notification.
7741 Now collect the data. */
7742 val = read_frame (buf, sizeof_buf);
7747 remote_serial_write ("-", 1);
7750 if (tries > MAX_TRIES)
7752 /* We have tried hard enough, and just can't receive the
7753 packet/notification. Give up. */
7754 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7756 /* Skip the ack char if we're in no-ack mode. */
7757 if (!rs->noack_mode)
7758 remote_serial_write ("+", 1);
7762 /* If we got an ordinary packet, return that to our caller. */
7767 struct cleanup *old_chain;
7770 str = escape_buffer (*buf, val);
7771 old_chain = make_cleanup (xfree, str);
7772 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7773 do_cleanups (old_chain);
7776 /* Skip the ack char if we're in no-ack mode. */
7777 if (!rs->noack_mode)
7778 remote_serial_write ("+", 1);
7779 if (is_notif != NULL)
7784 /* If we got a notification, handle it, and go back to looking
7788 gdb_assert (c == '%');
7792 struct cleanup *old_chain;
7795 str = escape_buffer (*buf, val);
7796 old_chain = make_cleanup (xfree, str);
7797 fprintf_unfiltered (gdb_stdlog,
7798 " Notification received: %s\n",
7800 do_cleanups (old_chain);
7802 if (is_notif != NULL)
7805 handle_notification (rs->notif_state, *buf);
7807 /* Notifications require no acknowledgement. */
7809 if (expecting_notif)
7816 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7818 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7822 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7825 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7831 remote_kill (struct target_ops *ops)
7834 /* Catch errors so the user can quit from gdb even when we
7835 aren't on speaking terms with the remote system. */
7840 CATCH (ex, RETURN_MASK_ERROR)
7842 if (ex.error == TARGET_CLOSE_ERROR)
7844 /* If we got an (EOF) error that caused the target
7845 to go away, then we're done, that's what we wanted.
7846 "k" is susceptible to cause a premature EOF, given
7847 that the remote server isn't actually required to
7848 reply to "k", and it can happen that it doesn't
7849 even get to reply ACK to the "k". */
7853 /* Otherwise, something went wrong. We didn't actually kill
7854 the target. Just propagate the exception, and let the
7855 user or higher layers decide what to do. */
7856 throw_exception (ex);
7860 /* We've killed the remote end, we get to mourn it. Since this is
7861 target remote, single-process, mourning the inferior also
7862 unpushes remote_ops. */
7863 target_mourn_inferior ();
7867 remote_vkill (int pid, struct remote_state *rs)
7869 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
7872 /* Tell the remote target to detach. */
7873 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7875 getpkt (&rs->buf, &rs->buf_size, 0);
7877 switch (packet_ok (rs->buf,
7878 &remote_protocol_packets[PACKET_vKill]))
7884 case PACKET_UNKNOWN:
7887 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7892 extended_remote_kill (struct target_ops *ops)
7895 int pid = ptid_get_pid (inferior_ptid);
7896 struct remote_state *rs = get_remote_state ();
7898 res = remote_vkill (pid, rs);
7899 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7901 /* Don't try 'k' on a multi-process aware stub -- it has no way
7902 to specify the pid. */
7906 getpkt (&rs->buf, &rs->buf_size, 0);
7907 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7910 /* Don't wait for it to die. I'm not really sure it matters whether
7911 we do or not. For the existing stubs, kill is a noop. */
7917 error (_("Can't kill process"));
7919 target_mourn_inferior ();
7923 remote_mourn (struct target_ops *ops)
7925 remote_mourn_1 (ops);
7928 /* Worker function for remote_mourn. */
7930 remote_mourn_1 (struct target_ops *target)
7932 unpush_target (target);
7934 /* remote_close takes care of doing most of the clean up. */
7935 generic_mourn_inferior ();
7939 extended_remote_mourn_1 (struct target_ops *target)
7941 struct remote_state *rs = get_remote_state ();
7943 /* In case we got here due to an error, but we're going to stay
7945 rs->waiting_for_stop_reply = 0;
7947 /* If the current general thread belonged to the process we just
7948 detached from or has exited, the remote side current general
7949 thread becomes undefined. Considering a case like this:
7951 - We just got here due to a detach.
7952 - The process that we're detaching from happens to immediately
7953 report a global breakpoint being hit in non-stop mode, in the
7954 same thread we had selected before.
7955 - GDB attaches to this process again.
7956 - This event happens to be the next event we handle.
7958 GDB would consider that the current general thread didn't need to
7959 be set on the stub side (with Hg), since for all it knew,
7960 GENERAL_THREAD hadn't changed.
7962 Notice that although in all-stop mode, the remote server always
7963 sets the current thread to the thread reporting the stop event,
7964 that doesn't happen in non-stop mode; in non-stop, the stub *must
7965 not* change the current thread when reporting a breakpoint hit,
7966 due to the decoupling of event reporting and event handling.
7968 To keep things simple, we always invalidate our notion of the
7970 record_currthread (rs, minus_one_ptid);
7972 /* Unlike "target remote", we do not want to unpush the target; then
7973 the next time the user says "run", we won't be connected. */
7975 /* Call common code to mark the inferior as not running. */
7976 generic_mourn_inferior ();
7978 if (!have_inferiors ())
7980 if (!remote_multi_process_p (rs))
7982 /* Check whether the target is running now - some remote stubs
7983 automatically restart after kill. */
7985 getpkt (&rs->buf, &rs->buf_size, 0);
7987 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7989 /* Assume that the target has been restarted. Set
7990 inferior_ptid so that bits of core GDB realizes
7991 there's something here, e.g., so that the user can
7992 say "kill" again. */
7993 inferior_ptid = magic_null_ptid;
8000 extended_remote_mourn (struct target_ops *ops)
8002 extended_remote_mourn_1 (ops);
8006 extended_remote_supports_disable_randomization (struct target_ops *self)
8008 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8012 extended_remote_disable_randomization (int val)
8014 struct remote_state *rs = get_remote_state ();
8017 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8020 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8022 error (_("Target does not support QDisableRandomization."));
8023 if (strcmp (reply, "OK") != 0)
8024 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8028 extended_remote_run (char *args)
8030 struct remote_state *rs = get_remote_state ();
8033 /* If the user has disabled vRun support, or we have detected that
8034 support is not available, do not try it. */
8035 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8038 strcpy (rs->buf, "vRun;");
8039 len = strlen (rs->buf);
8041 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8042 error (_("Remote file name too long for run packet"));
8043 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8044 strlen (remote_exec_file));
8046 gdb_assert (args != NULL);
8049 struct cleanup *back_to;
8053 argv = gdb_buildargv (args);
8054 back_to = make_cleanup_freeargv (argv);
8055 for (i = 0; argv[i] != NULL; i++)
8057 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8058 error (_("Argument list too long for run packet"));
8059 rs->buf[len++] = ';';
8060 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8063 do_cleanups (back_to);
8066 rs->buf[len++] = '\0';
8069 getpkt (&rs->buf, &rs->buf_size, 0);
8071 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8074 /* We have a wait response. All is well. */
8076 case PACKET_UNKNOWN:
8079 if (remote_exec_file[0] == '\0')
8080 error (_("Running the default executable on the remote target failed; "
8081 "try \"set remote exec-file\"?"));
8083 error (_("Running \"%s\" on the remote target failed"),
8086 gdb_assert_not_reached (_("bad switch"));
8090 /* In the extended protocol we want to be able to do things like
8091 "run" and have them basically work as expected. So we need
8092 a special create_inferior function. We support changing the
8093 executable file and the command line arguments, but not the
8097 extended_remote_create_inferior (struct target_ops *ops,
8098 char *exec_file, char *args,
8099 char **env, int from_tty)
8103 struct remote_state *rs = get_remote_state ();
8105 /* If running asynchronously, register the target file descriptor
8106 with the event loop. */
8107 if (target_can_async_p ())
8110 /* Disable address space randomization if requested (and supported). */
8111 if (extended_remote_supports_disable_randomization (ops))
8112 extended_remote_disable_randomization (disable_randomization);
8114 /* Now restart the remote server. */
8115 run_worked = extended_remote_run (args) != -1;
8118 /* vRun was not supported. Fail if we need it to do what the
8120 if (remote_exec_file[0])
8121 error (_("Remote target does not support \"set remote exec-file\""));
8123 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8125 /* Fall back to "R". */
8126 extended_remote_restart ();
8129 if (!have_inferiors ())
8131 /* Clean up from the last time we ran, before we mark the target
8132 running again. This will mark breakpoints uninserted, and
8133 get_offsets may insert breakpoints. */
8134 init_thread_list ();
8135 init_wait_for_inferior ();
8138 /* vRun's success return is a stop reply. */
8139 stop_reply = run_worked ? rs->buf : NULL;
8140 add_current_inferior_and_thread (stop_reply);
8142 /* Get updated offsets, if the stub uses qOffsets. */
8147 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8148 the list of conditions (in agent expression bytecode format), if any, the
8149 target needs to evaluate. The output is placed into the packet buffer
8150 started from BUF and ended at BUF_END. */
8153 remote_add_target_side_condition (struct gdbarch *gdbarch,
8154 struct bp_target_info *bp_tgt, char *buf,
8157 struct agent_expr *aexpr = NULL;
8160 char *buf_start = buf;
8162 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8165 buf += strlen (buf);
8166 xsnprintf (buf, buf_end - buf, "%s", ";");
8169 /* Send conditions to the target and free the vector. */
8171 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8174 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8175 buf += strlen (buf);
8176 for (i = 0; i < aexpr->len; ++i)
8177 buf = pack_hex_byte (buf, aexpr->buf[i]);
8184 remote_add_target_side_commands (struct gdbarch *gdbarch,
8185 struct bp_target_info *bp_tgt, char *buf)
8187 struct agent_expr *aexpr = NULL;
8190 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8193 buf += strlen (buf);
8195 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8196 buf += strlen (buf);
8198 /* Concatenate all the agent expressions that are commands into the
8201 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8204 sprintf (buf, "X%x,", aexpr->len);
8205 buf += strlen (buf);
8206 for (i = 0; i < aexpr->len; ++i)
8207 buf = pack_hex_byte (buf, aexpr->buf[i]);
8212 /* Insert a breakpoint. On targets that have software breakpoint
8213 support, we ask the remote target to do the work; on targets
8214 which don't, we insert a traditional memory breakpoint. */
8217 remote_insert_breakpoint (struct target_ops *ops,
8218 struct gdbarch *gdbarch,
8219 struct bp_target_info *bp_tgt)
8221 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8222 If it succeeds, then set the support to PACKET_ENABLE. If it
8223 fails, and the user has explicitly requested the Z support then
8224 report an error, otherwise, mark it disabled and go on. */
8226 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8228 CORE_ADDR addr = bp_tgt->reqstd_address;
8229 struct remote_state *rs;
8232 struct condition_list *cond = NULL;
8234 /* Make sure the remote is pointing at the right process, if
8236 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8237 set_general_process ();
8239 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8241 rs = get_remote_state ();
8243 endbuf = rs->buf + get_remote_packet_size ();
8248 addr = (ULONGEST) remote_address_masked (addr);
8249 p += hexnumstr (p, addr);
8250 xsnprintf (p, endbuf - p, ",%d", bpsize);
8252 if (remote_supports_cond_breakpoints (ops))
8253 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8255 if (remote_can_run_breakpoint_commands (ops))
8256 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8259 getpkt (&rs->buf, &rs->buf_size, 0);
8261 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8266 bp_tgt->placed_address = addr;
8267 bp_tgt->placed_size = bpsize;
8269 case PACKET_UNKNOWN:
8274 /* If this breakpoint has target-side commands but this stub doesn't
8275 support Z0 packets, throw error. */
8276 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8277 throw_error (NOT_SUPPORTED_ERROR, _("\
8278 Target doesn't support breakpoints that have target side commands."));
8280 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8284 remote_remove_breakpoint (struct target_ops *ops,
8285 struct gdbarch *gdbarch,
8286 struct bp_target_info *bp_tgt)
8288 CORE_ADDR addr = bp_tgt->placed_address;
8289 struct remote_state *rs = get_remote_state ();
8291 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8294 char *endbuf = rs->buf + get_remote_packet_size ();
8296 /* Make sure the remote is pointing at the right process, if
8298 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8299 set_general_process ();
8305 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8306 p += hexnumstr (p, addr);
8307 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8310 getpkt (&rs->buf, &rs->buf_size, 0);
8312 return (rs->buf[0] == 'E');
8315 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8319 watchpoint_to_Z_packet (int type)
8324 return Z_PACKET_WRITE_WP;
8327 return Z_PACKET_READ_WP;
8330 return Z_PACKET_ACCESS_WP;
8333 internal_error (__FILE__, __LINE__,
8334 _("hw_bp_to_z: bad watchpoint type %d"), type);
8339 remote_insert_watchpoint (struct target_ops *self,
8340 CORE_ADDR addr, int len, int type,
8341 struct expression *cond)
8343 struct remote_state *rs = get_remote_state ();
8344 char *endbuf = rs->buf + get_remote_packet_size ();
8346 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8348 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8351 /* Make sure the remote is pointing at the right process, if
8353 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8354 set_general_process ();
8356 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8357 p = strchr (rs->buf, '\0');
8358 addr = remote_address_masked (addr);
8359 p += hexnumstr (p, (ULONGEST) addr);
8360 xsnprintf (p, endbuf - p, ",%x", len);
8363 getpkt (&rs->buf, &rs->buf_size, 0);
8365 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8369 case PACKET_UNKNOWN:
8374 internal_error (__FILE__, __LINE__,
8375 _("remote_insert_watchpoint: reached end of function"));
8379 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8380 CORE_ADDR start, int length)
8382 CORE_ADDR diff = remote_address_masked (addr - start);
8384 return diff < length;
8389 remote_remove_watchpoint (struct target_ops *self,
8390 CORE_ADDR addr, int len, int type,
8391 struct expression *cond)
8393 struct remote_state *rs = get_remote_state ();
8394 char *endbuf = rs->buf + get_remote_packet_size ();
8396 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8398 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8401 /* Make sure the remote is pointing at the right process, if
8403 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8404 set_general_process ();
8406 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8407 p = strchr (rs->buf, '\0');
8408 addr = remote_address_masked (addr);
8409 p += hexnumstr (p, (ULONGEST) addr);
8410 xsnprintf (p, endbuf - p, ",%x", len);
8412 getpkt (&rs->buf, &rs->buf_size, 0);
8414 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8417 case PACKET_UNKNOWN:
8422 internal_error (__FILE__, __LINE__,
8423 _("remote_remove_watchpoint: reached end of function"));
8427 int remote_hw_watchpoint_limit = -1;
8428 int remote_hw_watchpoint_length_limit = -1;
8429 int remote_hw_breakpoint_limit = -1;
8432 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8433 CORE_ADDR addr, int len)
8435 if (remote_hw_watchpoint_length_limit == 0)
8437 else if (remote_hw_watchpoint_length_limit < 0)
8439 else if (len <= remote_hw_watchpoint_length_limit)
8446 remote_check_watch_resources (struct target_ops *self,
8447 int type, int cnt, int ot)
8449 if (type == bp_hardware_breakpoint)
8451 if (remote_hw_breakpoint_limit == 0)
8453 else if (remote_hw_breakpoint_limit < 0)
8455 else if (cnt <= remote_hw_breakpoint_limit)
8460 if (remote_hw_watchpoint_limit == 0)
8462 else if (remote_hw_watchpoint_limit < 0)
8466 else if (cnt <= remote_hw_watchpoint_limit)
8472 /* The to_stopped_by_sw_breakpoint method of target remote. */
8475 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8477 struct remote_state *rs = get_remote_state ();
8479 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8482 /* The to_supports_stopped_by_sw_breakpoint method of target
8486 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8488 struct remote_state *rs = get_remote_state ();
8490 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8493 /* The to_stopped_by_hw_breakpoint method of target remote. */
8496 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8498 struct remote_state *rs = get_remote_state ();
8500 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8503 /* The to_supports_stopped_by_hw_breakpoint method of target
8507 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8509 struct remote_state *rs = get_remote_state ();
8511 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8515 remote_stopped_by_watchpoint (struct target_ops *ops)
8517 struct remote_state *rs = get_remote_state ();
8519 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
8523 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8525 struct remote_state *rs = get_remote_state ();
8528 if (remote_stopped_by_watchpoint (target))
8530 *addr_p = rs->remote_watch_data_address;
8539 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8540 struct bp_target_info *bp_tgt)
8542 CORE_ADDR addr = bp_tgt->reqstd_address;
8543 struct remote_state *rs;
8548 /* The length field should be set to the size of a breakpoint
8549 instruction, even though we aren't inserting one ourselves. */
8551 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8553 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8556 /* Make sure the remote is pointing at the right process, if
8558 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8559 set_general_process ();
8561 rs = get_remote_state ();
8563 endbuf = rs->buf + get_remote_packet_size ();
8569 addr = remote_address_masked (addr);
8570 p += hexnumstr (p, (ULONGEST) addr);
8571 xsnprintf (p, endbuf - p, ",%x", bpsize);
8573 if (remote_supports_cond_breakpoints (self))
8574 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8576 if (remote_can_run_breakpoint_commands (self))
8577 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8580 getpkt (&rs->buf, &rs->buf_size, 0);
8582 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8585 if (rs->buf[1] == '.')
8587 message = strchr (rs->buf + 2, '.');
8589 error (_("Remote failure reply: %s"), message + 1);
8592 case PACKET_UNKNOWN:
8595 bp_tgt->placed_address = addr;
8596 bp_tgt->placed_size = bpsize;
8599 internal_error (__FILE__, __LINE__,
8600 _("remote_insert_hw_breakpoint: reached end of function"));
8605 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8606 struct bp_target_info *bp_tgt)
8609 struct remote_state *rs = get_remote_state ();
8611 char *endbuf = rs->buf + get_remote_packet_size ();
8613 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8616 /* Make sure the remote is pointing at the right process, if
8618 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8619 set_general_process ();
8625 addr = remote_address_masked (bp_tgt->placed_address);
8626 p += hexnumstr (p, (ULONGEST) addr);
8627 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8630 getpkt (&rs->buf, &rs->buf_size, 0);
8632 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8635 case PACKET_UNKNOWN:
8640 internal_error (__FILE__, __LINE__,
8641 _("remote_remove_hw_breakpoint: reached end of function"));
8644 /* Verify memory using the "qCRC:" request. */
8647 remote_verify_memory (struct target_ops *ops,
8648 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8650 struct remote_state *rs = get_remote_state ();
8651 unsigned long host_crc, target_crc;
8654 /* It doesn't make sense to use qCRC if the remote target is
8655 connected but not running. */
8656 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8658 enum packet_result result;
8660 /* Make sure the remote is pointing at the right process. */
8661 set_general_process ();
8663 /* FIXME: assumes lma can fit into long. */
8664 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8665 (long) lma, (long) size);
8668 /* Be clever; compute the host_crc before waiting for target
8670 host_crc = xcrc32 (data, size, 0xffffffff);
8672 getpkt (&rs->buf, &rs->buf_size, 0);
8674 result = packet_ok (rs->buf,
8675 &remote_protocol_packets[PACKET_qCRC]);
8676 if (result == PACKET_ERROR)
8678 else if (result == PACKET_OK)
8680 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8681 target_crc = target_crc * 16 + fromhex (*tmp);
8683 return (host_crc == target_crc);
8687 return simple_verify_memory (ops, data, lma, size);
8690 /* compare-sections command
8692 With no arguments, compares each loadable section in the exec bfd
8693 with the same memory range on the target, and reports mismatches.
8694 Useful for verifying the image on the target against the exec file. */
8697 compare_sections_command (char *args, int from_tty)
8700 struct cleanup *old_chain;
8702 const char *sectname;
8711 error (_("command cannot be used without an exec file"));
8713 /* Make sure the remote is pointing at the right process. */
8714 set_general_process ();
8716 if (args != NULL && strcmp (args, "-r") == 0)
8722 for (s = exec_bfd->sections; s; s = s->next)
8724 if (!(s->flags & SEC_LOAD))
8725 continue; /* Skip non-loadable section. */
8727 if (read_only && (s->flags & SEC_READONLY) == 0)
8728 continue; /* Skip writeable sections */
8730 size = bfd_get_section_size (s);
8732 continue; /* Skip zero-length section. */
8734 sectname = bfd_get_section_name (exec_bfd, s);
8735 if (args && strcmp (args, sectname) != 0)
8736 continue; /* Not the section selected by user. */
8738 matched = 1; /* Do this section. */
8741 sectdata = xmalloc (size);
8742 old_chain = make_cleanup (xfree, sectdata);
8743 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8745 res = target_verify_memory (sectdata, lma, size);
8748 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8749 paddress (target_gdbarch (), lma),
8750 paddress (target_gdbarch (), lma + size));
8752 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8753 paddress (target_gdbarch (), lma),
8754 paddress (target_gdbarch (), lma + size));
8756 printf_filtered ("matched.\n");
8759 printf_filtered ("MIS-MATCHED!\n");
8763 do_cleanups (old_chain);
8766 warning (_("One or more sections of the target image does not match\n\
8767 the loaded file\n"));
8768 if (args && !matched)
8769 printf_filtered (_("No loaded section named '%s'.\n"), args);
8772 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8773 into remote target. The number of bytes written to the remote
8774 target is returned, or -1 for error. */
8776 static enum target_xfer_status
8777 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8778 const char *annex, const gdb_byte *writebuf,
8779 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
8780 struct packet_config *packet)
8784 struct remote_state *rs = get_remote_state ();
8785 int max_size = get_memory_write_packet_size ();
8787 if (packet->support == PACKET_DISABLE)
8788 return TARGET_XFER_E_IO;
8790 /* Insert header. */
8791 i = snprintf (rs->buf, max_size,
8792 "qXfer:%s:write:%s:%s:",
8793 object_name, annex ? annex : "",
8794 phex_nz (offset, sizeof offset));
8795 max_size -= (i + 1);
8797 /* Escape as much data as fits into rs->buf. */
8798 buf_len = remote_escape_output
8799 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8801 if (putpkt_binary (rs->buf, i + buf_len) < 0
8802 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8803 || packet_ok (rs->buf, packet) != PACKET_OK)
8804 return TARGET_XFER_E_IO;
8806 unpack_varlen_hex (rs->buf, &n);
8809 return TARGET_XFER_OK;
8812 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8813 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8814 number of bytes read is returned, or 0 for EOF, or -1 for error.
8815 The number of bytes read may be less than LEN without indicating an
8816 EOF. PACKET is checked and updated to indicate whether the remote
8817 target supports this object. */
8819 static enum target_xfer_status
8820 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8822 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8823 ULONGEST *xfered_len,
8824 struct packet_config *packet)
8826 struct remote_state *rs = get_remote_state ();
8827 LONGEST i, n, packet_len;
8829 if (packet->support == PACKET_DISABLE)
8830 return TARGET_XFER_E_IO;
8832 /* Check whether we've cached an end-of-object packet that matches
8834 if (rs->finished_object)
8836 if (strcmp (object_name, rs->finished_object) == 0
8837 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8838 && offset == rs->finished_offset)
8839 return TARGET_XFER_EOF;
8842 /* Otherwise, we're now reading something different. Discard
8844 xfree (rs->finished_object);
8845 xfree (rs->finished_annex);
8846 rs->finished_object = NULL;
8847 rs->finished_annex = NULL;
8850 /* Request only enough to fit in a single packet. The actual data
8851 may not, since we don't know how much of it will need to be escaped;
8852 the target is free to respond with slightly less data. We subtract
8853 five to account for the response type and the protocol frame. */
8854 n = min (get_remote_packet_size () - 5, len);
8855 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8856 object_name, annex ? annex : "",
8857 phex_nz (offset, sizeof offset),
8858 phex_nz (n, sizeof n));
8859 i = putpkt (rs->buf);
8861 return TARGET_XFER_E_IO;
8864 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8865 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8866 return TARGET_XFER_E_IO;
8868 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8869 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8871 /* 'm' means there is (or at least might be) more data after this
8872 batch. That does not make sense unless there's at least one byte
8873 of data in this reply. */
8874 if (rs->buf[0] == 'm' && packet_len == 1)
8875 error (_("Remote qXfer reply contained no data."));
8877 /* Got some data. */
8878 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8879 packet_len - 1, readbuf, n);
8881 /* 'l' is an EOF marker, possibly including a final block of data,
8882 or possibly empty. If we have the final block of a non-empty
8883 object, record this fact to bypass a subsequent partial read. */
8884 if (rs->buf[0] == 'l' && offset + i > 0)
8886 rs->finished_object = xstrdup (object_name);
8887 rs->finished_annex = xstrdup (annex ? annex : "");
8888 rs->finished_offset = offset + i;
8892 return TARGET_XFER_EOF;
8896 return TARGET_XFER_OK;
8900 static enum target_xfer_status
8901 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8902 const char *annex, gdb_byte *readbuf,
8903 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8904 ULONGEST *xfered_len)
8906 struct remote_state *rs;
8911 set_remote_traceframe ();
8912 set_general_thread (inferior_ptid);
8914 rs = get_remote_state ();
8916 /* Handle memory using the standard memory routines. */
8917 if (object == TARGET_OBJECT_MEMORY)
8919 /* If the remote target is connected but not running, we should
8920 pass this request down to a lower stratum (e.g. the executable
8922 if (!target_has_execution)
8923 return TARGET_XFER_EOF;
8925 if (writebuf != NULL)
8926 return remote_write_bytes (offset, writebuf, len, xfered_len);
8928 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
8931 /* Handle SPU memory using qxfer packets. */
8932 if (object == TARGET_OBJECT_SPU)
8935 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8936 xfered_len, &remote_protocol_packets
8937 [PACKET_qXfer_spu_read]);
8939 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8940 xfered_len, &remote_protocol_packets
8941 [PACKET_qXfer_spu_write]);
8944 /* Handle extra signal info using qxfer packets. */
8945 if (object == TARGET_OBJECT_SIGNAL_INFO)
8948 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8949 xfered_len, &remote_protocol_packets
8950 [PACKET_qXfer_siginfo_read]);
8952 return remote_write_qxfer (ops, "siginfo", annex,
8953 writebuf, offset, len, xfered_len,
8954 &remote_protocol_packets
8955 [PACKET_qXfer_siginfo_write]);
8958 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8961 return remote_read_qxfer (ops, "statictrace", annex,
8962 readbuf, offset, len, xfered_len,
8963 &remote_protocol_packets
8964 [PACKET_qXfer_statictrace_read]);
8966 return TARGET_XFER_E_IO;
8969 /* Only handle flash writes. */
8970 if (writebuf != NULL)
8976 case TARGET_OBJECT_FLASH:
8977 return remote_flash_write (ops, offset, len, xfered_len,
8981 return TARGET_XFER_E_IO;
8985 /* Map pre-existing objects onto letters. DO NOT do this for new
8986 objects!!! Instead specify new query packets. */
8989 case TARGET_OBJECT_AVR:
8993 case TARGET_OBJECT_AUXV:
8994 gdb_assert (annex == NULL);
8995 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8997 &remote_protocol_packets[PACKET_qXfer_auxv]);
8999 case TARGET_OBJECT_AVAILABLE_FEATURES:
9000 return remote_read_qxfer
9001 (ops, "features", annex, readbuf, offset, len, xfered_len,
9002 &remote_protocol_packets[PACKET_qXfer_features]);
9004 case TARGET_OBJECT_LIBRARIES:
9005 return remote_read_qxfer
9006 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9007 &remote_protocol_packets[PACKET_qXfer_libraries]);
9009 case TARGET_OBJECT_LIBRARIES_SVR4:
9010 return remote_read_qxfer
9011 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9012 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9014 case TARGET_OBJECT_MEMORY_MAP:
9015 gdb_assert (annex == NULL);
9016 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9018 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9020 case TARGET_OBJECT_OSDATA:
9021 /* Should only get here if we're connected. */
9022 gdb_assert (rs->remote_desc);
9023 return remote_read_qxfer
9024 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9025 &remote_protocol_packets[PACKET_qXfer_osdata]);
9027 case TARGET_OBJECT_THREADS:
9028 gdb_assert (annex == NULL);
9029 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9031 &remote_protocol_packets[PACKET_qXfer_threads]);
9033 case TARGET_OBJECT_TRACEFRAME_INFO:
9034 gdb_assert (annex == NULL);
9035 return remote_read_qxfer
9036 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9037 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9039 case TARGET_OBJECT_FDPIC:
9040 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9042 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9044 case TARGET_OBJECT_OPENVMS_UIB:
9045 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9047 &remote_protocol_packets[PACKET_qXfer_uib]);
9049 case TARGET_OBJECT_BTRACE:
9050 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9052 &remote_protocol_packets[PACKET_qXfer_btrace]);
9054 case TARGET_OBJECT_BTRACE_CONF:
9055 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9057 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9060 return TARGET_XFER_E_IO;
9063 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9064 large enough let the caller deal with it. */
9065 if (len < get_remote_packet_size ())
9066 return TARGET_XFER_E_IO;
9067 len = get_remote_packet_size ();
9069 /* Except for querying the minimum buffer size, target must be open. */
9070 if (!rs->remote_desc)
9071 error (_("remote query is only available after target open"));
9073 gdb_assert (annex != NULL);
9074 gdb_assert (readbuf != NULL);
9080 /* We used one buffer char for the remote protocol q command and
9081 another for the query type. As the remote protocol encapsulation
9082 uses 4 chars plus one extra in case we are debugging
9083 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9086 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9088 /* Bad caller may have sent forbidden characters. */
9089 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9094 gdb_assert (annex[i] == '\0');
9096 i = putpkt (rs->buf);
9098 return TARGET_XFER_E_IO;
9100 getpkt (&rs->buf, &rs->buf_size, 0);
9101 strcpy ((char *) readbuf, rs->buf);
9103 *xfered_len = strlen ((char *) readbuf);
9104 return TARGET_XFER_OK;
9108 remote_search_memory (struct target_ops* ops,
9109 CORE_ADDR start_addr, ULONGEST search_space_len,
9110 const gdb_byte *pattern, ULONGEST pattern_len,
9111 CORE_ADDR *found_addrp)
9113 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9114 struct remote_state *rs = get_remote_state ();
9115 int max_size = get_memory_write_packet_size ();
9116 struct packet_config *packet =
9117 &remote_protocol_packets[PACKET_qSearch_memory];
9118 /* Number of packet bytes used to encode the pattern;
9119 this could be more than PATTERN_LEN due to escape characters. */
9120 int escaped_pattern_len;
9121 /* Amount of pattern that was encodable in the packet. */
9122 int used_pattern_len;
9125 ULONGEST found_addr;
9127 /* Don't go to the target if we don't have to.
9128 This is done before checking packet->support to avoid the possibility that
9129 a success for this edge case means the facility works in general. */
9130 if (pattern_len > search_space_len)
9132 if (pattern_len == 0)
9134 *found_addrp = start_addr;
9138 /* If we already know the packet isn't supported, fall back to the simple
9139 way of searching memory. */
9141 if (packet_config_support (packet) == PACKET_DISABLE)
9143 /* Target doesn't provided special support, fall back and use the
9144 standard support (copy memory and do the search here). */
9145 return simple_search_memory (ops, start_addr, search_space_len,
9146 pattern, pattern_len, found_addrp);
9149 /* Make sure the remote is pointing at the right process. */
9150 set_general_process ();
9152 /* Insert header. */
9153 i = snprintf (rs->buf, max_size,
9154 "qSearch:memory:%s;%s;",
9155 phex_nz (start_addr, addr_size),
9156 phex_nz (search_space_len, sizeof (search_space_len)));
9157 max_size -= (i + 1);
9159 /* Escape as much data as fits into rs->buf. */
9160 escaped_pattern_len =
9161 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9162 &used_pattern_len, max_size);
9164 /* Bail if the pattern is too large. */
9165 if (used_pattern_len != pattern_len)
9166 error (_("Pattern is too large to transmit to remote target."));
9168 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9169 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9170 || packet_ok (rs->buf, packet) != PACKET_OK)
9172 /* The request may not have worked because the command is not
9173 supported. If so, fall back to the simple way. */
9174 if (packet->support == PACKET_DISABLE)
9176 return simple_search_memory (ops, start_addr, search_space_len,
9177 pattern, pattern_len, found_addrp);
9182 if (rs->buf[0] == '0')
9184 else if (rs->buf[0] == '1')
9187 if (rs->buf[1] != ',')
9188 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9189 unpack_varlen_hex (rs->buf + 2, &found_addr);
9190 *found_addrp = found_addr;
9193 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9199 remote_rcmd (struct target_ops *self, const char *command,
9200 struct ui_file *outbuf)
9202 struct remote_state *rs = get_remote_state ();
9205 if (!rs->remote_desc)
9206 error (_("remote rcmd is only available after target open"));
9208 /* Send a NULL command across as an empty command. */
9209 if (command == NULL)
9212 /* The query prefix. */
9213 strcpy (rs->buf, "qRcmd,");
9214 p = strchr (rs->buf, '\0');
9216 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9217 > get_remote_packet_size ())
9218 error (_("\"monitor\" command ``%s'' is too long."), command);
9220 /* Encode the actual command. */
9221 bin2hex ((const gdb_byte *) command, p, strlen (command));
9223 if (putpkt (rs->buf) < 0)
9224 error (_("Communication problem with target."));
9226 /* get/display the response */
9231 /* XXX - see also remote_get_noisy_reply(). */
9232 QUIT; /* Allow user to bail out with ^C. */
9234 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9236 /* Timeout. Continue to (try to) read responses.
9237 This is better than stopping with an error, assuming the stub
9238 is still executing the (long) monitor command.
9239 If needed, the user can interrupt gdb using C-c, obtaining
9240 an effect similar to stop on timeout. */
9245 error (_("Target does not support this command."));
9246 if (buf[0] == 'O' && buf[1] != 'K')
9248 remote_console_output (buf + 1); /* 'O' message from stub. */
9251 if (strcmp (buf, "OK") == 0)
9253 if (strlen (buf) == 3 && buf[0] == 'E'
9254 && isdigit (buf[1]) && isdigit (buf[2]))
9256 error (_("Protocol error with Rcmd"));
9258 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9260 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9262 fputc_unfiltered (c, outbuf);
9268 static VEC(mem_region_s) *
9269 remote_memory_map (struct target_ops *ops)
9271 VEC(mem_region_s) *result = NULL;
9272 char *text = target_read_stralloc (¤t_target,
9273 TARGET_OBJECT_MEMORY_MAP, NULL);
9277 struct cleanup *back_to = make_cleanup (xfree, text);
9279 result = parse_memory_map (text);
9280 do_cleanups (back_to);
9287 packet_command (char *args, int from_tty)
9289 struct remote_state *rs = get_remote_state ();
9291 if (!rs->remote_desc)
9292 error (_("command can only be used with remote target"));
9295 error (_("remote-packet command requires packet text as argument"));
9297 puts_filtered ("sending: ");
9298 print_packet (args);
9299 puts_filtered ("\n");
9302 getpkt (&rs->buf, &rs->buf_size, 0);
9303 puts_filtered ("received: ");
9304 print_packet (rs->buf);
9305 puts_filtered ("\n");
9309 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9311 static void display_thread_info (struct gdb_ext_thread_info *info);
9313 static void threadset_test_cmd (char *cmd, int tty);
9315 static void threadalive_test (char *cmd, int tty);
9317 static void threadlist_test_cmd (char *cmd, int tty);
9319 int get_and_display_threadinfo (threadref *ref);
9321 static void threadinfo_test_cmd (char *cmd, int tty);
9323 static int thread_display_step (threadref *ref, void *context);
9325 static void threadlist_update_test_cmd (char *cmd, int tty);
9327 static void init_remote_threadtests (void);
9329 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9332 threadset_test_cmd (char *cmd, int tty)
9334 int sample_thread = SAMPLE_THREAD;
9336 printf_filtered (_("Remote threadset test\n"));
9337 set_general_thread (sample_thread);
9342 threadalive_test (char *cmd, int tty)
9344 int sample_thread = SAMPLE_THREAD;
9345 int pid = ptid_get_pid (inferior_ptid);
9346 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9348 if (remote_thread_alive (ptid))
9349 printf_filtered ("PASS: Thread alive test\n");
9351 printf_filtered ("FAIL: Thread alive test\n");
9354 void output_threadid (char *title, threadref *ref);
9357 output_threadid (char *title, threadref *ref)
9361 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9363 printf_filtered ("%s %s\n", title, (&hexid[0]));
9367 threadlist_test_cmd (char *cmd, int tty)
9370 threadref nextthread;
9371 int done, result_count;
9372 threadref threadlist[3];
9374 printf_filtered ("Remote Threadlist test\n");
9375 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9376 &result_count, &threadlist[0]))
9377 printf_filtered ("FAIL: threadlist test\n");
9380 threadref *scan = threadlist;
9381 threadref *limit = scan + result_count;
9383 while (scan < limit)
9384 output_threadid (" thread ", scan++);
9389 display_thread_info (struct gdb_ext_thread_info *info)
9391 output_threadid ("Threadid: ", &info->threadid);
9392 printf_filtered ("Name: %s\n ", info->shortname);
9393 printf_filtered ("State: %s\n", info->display);
9394 printf_filtered ("other: %s\n\n", info->more_display);
9398 get_and_display_threadinfo (threadref *ref)
9402 struct gdb_ext_thread_info threadinfo;
9404 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9405 | TAG_MOREDISPLAY | TAG_DISPLAY;
9406 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9407 display_thread_info (&threadinfo);
9412 threadinfo_test_cmd (char *cmd, int tty)
9414 int athread = SAMPLE_THREAD;
9418 int_to_threadref (&thread, athread);
9419 printf_filtered ("Remote Threadinfo test\n");
9420 if (!get_and_display_threadinfo (&thread))
9421 printf_filtered ("FAIL cannot get thread info\n");
9425 thread_display_step (threadref *ref, void *context)
9427 /* output_threadid(" threadstep ",ref); *//* simple test */
9428 return get_and_display_threadinfo (ref);
9432 threadlist_update_test_cmd (char *cmd, int tty)
9434 printf_filtered ("Remote Threadlist update test\n");
9435 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9439 init_remote_threadtests (void)
9441 add_com ("tlist", class_obscure, threadlist_test_cmd,
9442 _("Fetch and print the remote list of "
9443 "thread identifiers, one pkt only"));
9444 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9445 _("Fetch and display info about one thread"));
9446 add_com ("tset", class_obscure, threadset_test_cmd,
9447 _("Test setting to a different thread"));
9448 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9449 _("Iterate through updating all remote thread info"));
9450 add_com ("talive", class_obscure, threadalive_test,
9451 _(" Remote thread alive test "));
9456 /* Convert a thread ID to a string. Returns the string in a static
9460 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9462 static char buf[64];
9463 struct remote_state *rs = get_remote_state ();
9465 if (ptid_equal (ptid, null_ptid))
9466 return normal_pid_to_str (ptid);
9467 else if (ptid_is_pid (ptid))
9469 /* Printing an inferior target id. */
9471 /* When multi-process extensions are off, there's no way in the
9472 remote protocol to know the remote process id, if there's any
9473 at all. There's one exception --- when we're connected with
9474 target extended-remote, and we manually attached to a process
9475 with "attach PID". We don't record anywhere a flag that
9476 allows us to distinguish that case from the case of
9477 connecting with extended-remote and the stub already being
9478 attached to a process, and reporting yes to qAttached, hence
9479 no smart special casing here. */
9480 if (!remote_multi_process_p (rs))
9482 xsnprintf (buf, sizeof buf, "Remote target");
9486 return normal_pid_to_str (ptid);
9490 if (ptid_equal (magic_null_ptid, ptid))
9491 xsnprintf (buf, sizeof buf, "Thread <main>");
9492 else if (rs->extended && remote_multi_process_p (rs))
9493 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9494 ptid_get_pid (ptid), ptid_get_lwp (ptid));
9496 xsnprintf (buf, sizeof buf, "Thread %ld",
9497 ptid_get_lwp (ptid));
9502 /* Get the address of the thread local variable in OBJFILE which is
9503 stored at OFFSET within the thread local storage for thread PTID. */
9506 remote_get_thread_local_address (struct target_ops *ops,
9507 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9509 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
9511 struct remote_state *rs = get_remote_state ();
9513 char *endp = rs->buf + get_remote_packet_size ();
9514 enum packet_result result;
9516 strcpy (p, "qGetTLSAddr:");
9518 p = write_ptid (p, endp, ptid);
9520 p += hexnumstr (p, offset);
9522 p += hexnumstr (p, lm);
9526 getpkt (&rs->buf, &rs->buf_size, 0);
9527 result = packet_ok (rs->buf,
9528 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9529 if (result == PACKET_OK)
9533 unpack_varlen_hex (rs->buf, &result);
9536 else if (result == PACKET_UNKNOWN)
9537 throw_error (TLS_GENERIC_ERROR,
9538 _("Remote target doesn't support qGetTLSAddr packet"));
9540 throw_error (TLS_GENERIC_ERROR,
9541 _("Remote target failed to process qGetTLSAddr request"));
9544 throw_error (TLS_GENERIC_ERROR,
9545 _("TLS not supported or disabled on this target"));
9550 /* Provide thread local base, i.e. Thread Information Block address.
9551 Returns 1 if ptid is found and thread_local_base is non zero. */
9554 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
9556 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
9558 struct remote_state *rs = get_remote_state ();
9560 char *endp = rs->buf + get_remote_packet_size ();
9561 enum packet_result result;
9563 strcpy (p, "qGetTIBAddr:");
9565 p = write_ptid (p, endp, ptid);
9569 getpkt (&rs->buf, &rs->buf_size, 0);
9570 result = packet_ok (rs->buf,
9571 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9572 if (result == PACKET_OK)
9576 unpack_varlen_hex (rs->buf, &result);
9578 *addr = (CORE_ADDR) result;
9581 else if (result == PACKET_UNKNOWN)
9582 error (_("Remote target doesn't support qGetTIBAddr packet"));
9584 error (_("Remote target failed to process qGetTIBAddr request"));
9587 error (_("qGetTIBAddr not supported or disabled on this target"));
9592 /* Support for inferring a target description based on the current
9593 architecture and the size of a 'g' packet. While the 'g' packet
9594 can have any size (since optional registers can be left off the
9595 end), some sizes are easily recognizable given knowledge of the
9596 approximate architecture. */
9598 struct remote_g_packet_guess
9601 const struct target_desc *tdesc;
9603 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9604 DEF_VEC_O(remote_g_packet_guess_s);
9606 struct remote_g_packet_data
9608 VEC(remote_g_packet_guess_s) *guesses;
9611 static struct gdbarch_data *remote_g_packet_data_handle;
9614 remote_g_packet_data_init (struct obstack *obstack)
9616 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9620 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9621 const struct target_desc *tdesc)
9623 struct remote_g_packet_data *data
9624 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9625 struct remote_g_packet_guess new_guess, *guess;
9628 gdb_assert (tdesc != NULL);
9631 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9633 if (guess->bytes == bytes)
9634 internal_error (__FILE__, __LINE__,
9635 _("Duplicate g packet description added for size %d"),
9638 new_guess.bytes = bytes;
9639 new_guess.tdesc = tdesc;
9640 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9643 /* Return 1 if remote_read_description would do anything on this target
9644 and architecture, 0 otherwise. */
9647 remote_read_description_p (struct target_ops *target)
9649 struct remote_g_packet_data *data
9650 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9652 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9658 static const struct target_desc *
9659 remote_read_description (struct target_ops *target)
9661 struct remote_g_packet_data *data
9662 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9664 /* Do not try this during initial connection, when we do not know
9665 whether there is a running but stopped thread. */
9666 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9667 return target->beneath->to_read_description (target->beneath);
9669 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9671 struct remote_g_packet_guess *guess;
9673 int bytes = send_g_packet ();
9676 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9678 if (guess->bytes == bytes)
9679 return guess->tdesc;
9681 /* We discard the g packet. A minor optimization would be to
9682 hold on to it, and fill the register cache once we have selected
9683 an architecture, but it's too tricky to do safely. */
9686 return target->beneath->to_read_description (target->beneath);
9689 /* Remote file transfer support. This is host-initiated I/O, not
9690 target-initiated; for target-initiated, see remote-fileio.c. */
9692 /* If *LEFT is at least the length of STRING, copy STRING to
9693 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9694 decrease *LEFT. Otherwise raise an error. */
9697 remote_buffer_add_string (char **buffer, int *left, char *string)
9699 int len = strlen (string);
9702 error (_("Packet too long for target."));
9704 memcpy (*buffer, string, len);
9708 /* NUL-terminate the buffer as a convenience, if there is
9714 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
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_bytes (char **buffer, int *left, const gdb_byte *bytes,
9722 if (2 * len > *left)
9723 error (_("Packet too long for target."));
9725 bin2hex (bytes, *buffer, len);
9729 /* NUL-terminate the buffer as a convenience, if there is
9735 /* If *LEFT is large enough, convert VALUE to hex and add it to
9736 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9737 decrease *LEFT. Otherwise raise an error. */
9740 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9742 int len = hexnumlen (value);
9745 error (_("Packet too long for target."));
9747 hexnumstr (*buffer, value);
9751 /* NUL-terminate the buffer as a convenience, if there is
9757 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9758 value, *REMOTE_ERRNO to the remote error number or zero if none
9759 was included, and *ATTACHMENT to point to the start of the annex
9760 if any. The length of the packet isn't needed here; there may
9761 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9763 Return 0 if the packet could be parsed, -1 if it could not. If
9764 -1 is returned, the other variables may not be initialized. */
9767 remote_hostio_parse_result (char *buffer, int *retcode,
9768 int *remote_errno, char **attachment)
9775 if (buffer[0] != 'F')
9779 *retcode = strtol (&buffer[1], &p, 16);
9780 if (errno != 0 || p == &buffer[1])
9783 /* Check for ",errno". */
9787 *remote_errno = strtol (p + 1, &p2, 16);
9788 if (errno != 0 || p + 1 == p2)
9793 /* Check for ";attachment". If there is no attachment, the
9794 packet should end here. */
9797 *attachment = p + 1;
9800 else if (*p == '\0')
9806 /* Send a prepared I/O packet to the target and read its response.
9807 The prepared packet is in the global RS->BUF before this function
9808 is called, and the answer is there when we return.
9810 COMMAND_BYTES is the length of the request to send, which may include
9811 binary data. WHICH_PACKET is the packet configuration to check
9812 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9813 is set to the error number and -1 is returned. Otherwise the value
9814 returned by the function is returned.
9816 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9817 attachment is expected; an error will be reported if there's a
9818 mismatch. If one is found, *ATTACHMENT will be set to point into
9819 the packet buffer and *ATTACHMENT_LEN will be set to the
9820 attachment's length. */
9823 remote_hostio_send_command (int command_bytes, int which_packet,
9824 int *remote_errno, char **attachment,
9825 int *attachment_len)
9827 struct remote_state *rs = get_remote_state ();
9828 int ret, bytes_read;
9829 char *attachment_tmp;
9831 if (!rs->remote_desc
9832 || packet_support (which_packet) == PACKET_DISABLE)
9834 *remote_errno = FILEIO_ENOSYS;
9838 putpkt_binary (rs->buf, command_bytes);
9839 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9841 /* If it timed out, something is wrong. Don't try to parse the
9845 *remote_errno = FILEIO_EINVAL;
9849 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9852 *remote_errno = FILEIO_EINVAL;
9854 case PACKET_UNKNOWN:
9855 *remote_errno = FILEIO_ENOSYS;
9861 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9864 *remote_errno = FILEIO_EINVAL;
9868 /* Make sure we saw an attachment if and only if we expected one. */
9869 if ((attachment_tmp == NULL && attachment != NULL)
9870 || (attachment_tmp != NULL && attachment == NULL))
9872 *remote_errno = FILEIO_EINVAL;
9876 /* If an attachment was found, it must point into the packet buffer;
9877 work out how many bytes there were. */
9878 if (attachment_tmp != NULL)
9880 *attachment = attachment_tmp;
9881 *attachment_len = bytes_read - (*attachment - rs->buf);
9887 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9888 remote file descriptor, or -1 if an error occurs (and set
9892 remote_hostio_open (struct target_ops *self,
9893 const char *filename, int flags, int mode,
9896 struct remote_state *rs = get_remote_state ();
9898 int left = get_remote_packet_size () - 1;
9900 remote_buffer_add_string (&p, &left, "vFile:open:");
9902 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9904 remote_buffer_add_string (&p, &left, ",");
9906 remote_buffer_add_int (&p, &left, flags);
9907 remote_buffer_add_string (&p, &left, ",");
9909 remote_buffer_add_int (&p, &left, mode);
9911 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9912 remote_errno, NULL, NULL);
9915 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9916 Return the number of bytes written, or -1 if an error occurs (and
9917 set *REMOTE_ERRNO). */
9920 remote_hostio_pwrite (struct target_ops *self,
9921 int fd, const gdb_byte *write_buf, int len,
9922 ULONGEST offset, int *remote_errno)
9924 struct remote_state *rs = get_remote_state ();
9926 int left = get_remote_packet_size ();
9929 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9931 remote_buffer_add_int (&p, &left, fd);
9932 remote_buffer_add_string (&p, &left, ",");
9934 remote_buffer_add_int (&p, &left, offset);
9935 remote_buffer_add_string (&p, &left, ",");
9937 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9938 get_remote_packet_size () - (p - rs->buf));
9940 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9941 remote_errno, NULL, NULL);
9944 /* Read up to LEN bytes FD on the remote target into READ_BUF
9945 Return the number of bytes read, or -1 if an error occurs (and
9946 set *REMOTE_ERRNO). */
9949 remote_hostio_pread (struct target_ops *self,
9950 int fd, gdb_byte *read_buf, int len,
9951 ULONGEST offset, int *remote_errno)
9953 struct remote_state *rs = get_remote_state ();
9956 int left = get_remote_packet_size ();
9957 int ret, attachment_len;
9960 remote_buffer_add_string (&p, &left, "vFile:pread:");
9962 remote_buffer_add_int (&p, &left, fd);
9963 remote_buffer_add_string (&p, &left, ",");
9965 remote_buffer_add_int (&p, &left, len);
9966 remote_buffer_add_string (&p, &left, ",");
9968 remote_buffer_add_int (&p, &left, offset);
9970 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9971 remote_errno, &attachment,
9977 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9979 if (read_len != ret)
9980 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9985 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9986 (and set *REMOTE_ERRNO). */
9989 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
9991 struct remote_state *rs = get_remote_state ();
9993 int left = get_remote_packet_size () - 1;
9995 remote_buffer_add_string (&p, &left, "vFile:close:");
9997 remote_buffer_add_int (&p, &left, fd);
9999 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10000 remote_errno, NULL, NULL);
10003 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
10004 occurs (and set *REMOTE_ERRNO). */
10007 remote_hostio_unlink (struct target_ops *self,
10008 const char *filename, int *remote_errno)
10010 struct remote_state *rs = get_remote_state ();
10012 int left = get_remote_packet_size () - 1;
10014 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10016 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10017 strlen (filename));
10019 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10020 remote_errno, NULL, NULL);
10023 /* Read value of symbolic link FILENAME on the remote target. Return
10024 a null-terminated string allocated via xmalloc, or NULL if an error
10025 occurs (and set *REMOTE_ERRNO). */
10028 remote_hostio_readlink (struct target_ops *self,
10029 const char *filename, int *remote_errno)
10031 struct remote_state *rs = get_remote_state ();
10034 int left = get_remote_packet_size ();
10035 int len, attachment_len;
10039 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10041 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10042 strlen (filename));
10044 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10045 remote_errno, &attachment,
10051 ret = xmalloc (len + 1);
10053 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10054 (gdb_byte *) ret, len);
10055 if (read_len != len)
10056 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10062 /* Read information about the open file FD on the remote target
10063 into ST. Return 0 on success, or -1 if an error occurs (and
10064 set *REMOTE_ERRNO). */
10067 remote_hostio_fstat (struct target_ops *self,
10068 int fd, struct stat *st,
10071 struct remote_state *rs = get_remote_state ();
10073 int left = get_remote_packet_size ();
10074 int attachment_len, ret;
10076 struct fio_stat fst;
10079 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10081 remote_buffer_add_int (&p, &left, fd);
10083 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10084 remote_errno, &attachment,
10088 if (*remote_errno != FILEIO_ENOSYS)
10091 /* Strictly we should return -1, ENOSYS here, but when
10092 "set sysroot remote:" was implemented in August 2008
10093 BFD's need for a stat function was sidestepped with
10094 this hack. This was not remedied until March 2015
10095 so we retain the previous behavior to avoid breaking
10098 Note that the memset is a March 2015 addition; older
10099 GDBs set st_size *and nothing else* so the structure
10100 would have garbage in all other fields. This might
10101 break something but retaining the previous behavior
10102 here would be just too wrong. */
10104 memset (st, 0, sizeof (struct stat));
10105 st->st_size = INT_MAX;
10109 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10110 (gdb_byte *) &fst, sizeof (fst));
10112 if (read_len != ret)
10113 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10115 if (read_len != sizeof (fst))
10116 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10117 read_len, (int) sizeof (fst));
10119 remote_fileio_to_host_stat (&fst, st);
10125 remote_fileio_errno_to_host (int errnum)
10131 case FILEIO_ENOENT:
10139 case FILEIO_EACCES:
10141 case FILEIO_EFAULT:
10145 case FILEIO_EEXIST:
10147 case FILEIO_ENODEV:
10149 case FILEIO_ENOTDIR:
10151 case FILEIO_EISDIR:
10153 case FILEIO_EINVAL:
10155 case FILEIO_ENFILE:
10157 case FILEIO_EMFILE:
10161 case FILEIO_ENOSPC:
10163 case FILEIO_ESPIPE:
10167 case FILEIO_ENOSYS:
10169 case FILEIO_ENAMETOOLONG:
10170 return ENAMETOOLONG;
10176 remote_hostio_error (int errnum)
10178 int host_error = remote_fileio_errno_to_host (errnum);
10180 if (host_error == -1)
10181 error (_("Unknown remote I/O error %d"), errnum);
10183 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10187 remote_hostio_close_cleanup (void *opaque)
10189 int fd = *(int *) opaque;
10192 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10197 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10199 const char *filename = bfd_get_filename (abfd);
10200 int fd, remote_errno;
10203 gdb_assert (remote_filename_p (filename));
10205 fd = remote_hostio_open (find_target_at (process_stratum),
10206 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10209 errno = remote_fileio_errno_to_host (remote_errno);
10210 bfd_set_error (bfd_error_system_call);
10214 stream = xmalloc (sizeof (int));
10220 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10222 int fd = *(int *)stream;
10227 /* Ignore errors on close; these may happen if the remote
10228 connection was already torn down. */
10229 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10231 /* Zero means success. */
10236 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10237 file_ptr nbytes, file_ptr offset)
10239 int fd = *(int *)stream;
10241 file_ptr pos, bytes;
10244 while (nbytes > pos)
10246 bytes = remote_hostio_pread (find_target_at (process_stratum),
10247 fd, (gdb_byte *) buf + pos, nbytes - pos,
10248 offset + pos, &remote_errno);
10250 /* Success, but no bytes, means end-of-file. */
10254 errno = remote_fileio_errno_to_host (remote_errno);
10255 bfd_set_error (bfd_error_system_call);
10266 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10268 int fd = *(int *) stream;
10272 result = remote_hostio_fstat (find_target_at (process_stratum),
10273 fd, sb, &remote_errno);
10277 errno = remote_fileio_errno_to_host (remote_errno);
10278 bfd_set_error (bfd_error_system_call);
10285 remote_filename_p (const char *filename)
10287 return startswith (filename, REMOTE_SYSROOT_PREFIX);
10291 remote_bfd_open (const char *remote_file, const char *target)
10293 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10294 remote_bfd_iovec_open, NULL,
10295 remote_bfd_iovec_pread,
10296 remote_bfd_iovec_close,
10297 remote_bfd_iovec_stat);
10303 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10305 struct cleanup *back_to, *close_cleanup;
10306 int retcode, fd, remote_errno, bytes, io_size;
10309 int bytes_in_buffer;
10312 struct remote_state *rs = get_remote_state ();
10314 if (!rs->remote_desc)
10315 error (_("command can only be used with remote target"));
10317 file = gdb_fopen_cloexec (local_file, "rb");
10319 perror_with_name (local_file);
10320 back_to = make_cleanup_fclose (file);
10322 fd = remote_hostio_open (find_target_at (process_stratum),
10323 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10325 0700, &remote_errno);
10327 remote_hostio_error (remote_errno);
10329 /* Send up to this many bytes at once. They won't all fit in the
10330 remote packet limit, so we'll transfer slightly fewer. */
10331 io_size = get_remote_packet_size ();
10332 buffer = xmalloc (io_size);
10333 make_cleanup (xfree, buffer);
10335 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10337 bytes_in_buffer = 0;
10340 while (bytes_in_buffer || !saw_eof)
10344 bytes = fread (buffer + bytes_in_buffer, 1,
10345 io_size - bytes_in_buffer,
10350 error (_("Error reading %s."), local_file);
10353 /* EOF. Unless there is something still in the
10354 buffer from the last iteration, we are done. */
10356 if (bytes_in_buffer == 0)
10364 bytes += bytes_in_buffer;
10365 bytes_in_buffer = 0;
10367 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10369 offset, &remote_errno);
10372 remote_hostio_error (remote_errno);
10373 else if (retcode == 0)
10374 error (_("Remote write of %d bytes returned 0!"), bytes);
10375 else if (retcode < bytes)
10377 /* Short write. Save the rest of the read data for the next
10379 bytes_in_buffer = bytes - retcode;
10380 memmove (buffer, buffer + retcode, bytes_in_buffer);
10386 discard_cleanups (close_cleanup);
10387 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10388 remote_hostio_error (remote_errno);
10391 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10392 do_cleanups (back_to);
10396 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10398 struct cleanup *back_to, *close_cleanup;
10399 int fd, remote_errno, bytes, io_size;
10403 struct remote_state *rs = get_remote_state ();
10405 if (!rs->remote_desc)
10406 error (_("command can only be used with remote target"));
10408 fd = remote_hostio_open (find_target_at (process_stratum),
10409 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10411 remote_hostio_error (remote_errno);
10413 file = gdb_fopen_cloexec (local_file, "wb");
10415 perror_with_name (local_file);
10416 back_to = make_cleanup_fclose (file);
10418 /* Send up to this many bytes at once. They won't all fit in the
10419 remote packet limit, so we'll transfer slightly fewer. */
10420 io_size = get_remote_packet_size ();
10421 buffer = xmalloc (io_size);
10422 make_cleanup (xfree, buffer);
10424 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10429 bytes = remote_hostio_pread (find_target_at (process_stratum),
10430 fd, buffer, io_size, offset, &remote_errno);
10432 /* Success, but no bytes, means end-of-file. */
10435 remote_hostio_error (remote_errno);
10439 bytes = fwrite (buffer, 1, bytes, file);
10441 perror_with_name (local_file);
10444 discard_cleanups (close_cleanup);
10445 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10446 remote_hostio_error (remote_errno);
10449 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10450 do_cleanups (back_to);
10454 remote_file_delete (const char *remote_file, int from_tty)
10456 int retcode, remote_errno;
10457 struct remote_state *rs = get_remote_state ();
10459 if (!rs->remote_desc)
10460 error (_("command can only be used with remote target"));
10462 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10463 remote_file, &remote_errno);
10465 remote_hostio_error (remote_errno);
10468 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10472 remote_put_command (char *args, int from_tty)
10474 struct cleanup *back_to;
10478 error_no_arg (_("file to put"));
10480 argv = gdb_buildargv (args);
10481 back_to = make_cleanup_freeargv (argv);
10482 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10483 error (_("Invalid parameters to remote put"));
10485 remote_file_put (argv[0], argv[1], from_tty);
10487 do_cleanups (back_to);
10491 remote_get_command (char *args, int from_tty)
10493 struct cleanup *back_to;
10497 error_no_arg (_("file to get"));
10499 argv = gdb_buildargv (args);
10500 back_to = make_cleanup_freeargv (argv);
10501 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10502 error (_("Invalid parameters to remote get"));
10504 remote_file_get (argv[0], argv[1], from_tty);
10506 do_cleanups (back_to);
10510 remote_delete_command (char *args, int from_tty)
10512 struct cleanup *back_to;
10516 error_no_arg (_("file to delete"));
10518 argv = gdb_buildargv (args);
10519 back_to = make_cleanup_freeargv (argv);
10520 if (argv[0] == NULL || argv[1] != NULL)
10521 error (_("Invalid parameters to remote delete"));
10523 remote_file_delete (argv[0], from_tty);
10525 do_cleanups (back_to);
10529 remote_command (char *args, int from_tty)
10531 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
10535 remote_can_execute_reverse (struct target_ops *self)
10537 if (packet_support (PACKET_bs) == PACKET_ENABLE
10538 || packet_support (PACKET_bc) == PACKET_ENABLE)
10545 remote_supports_non_stop (struct target_ops *self)
10551 remote_supports_disable_randomization (struct target_ops *self)
10553 /* Only supported in extended mode. */
10558 remote_supports_multi_process (struct target_ops *self)
10560 struct remote_state *rs = get_remote_state ();
10562 /* Only extended-remote handles being attached to multiple
10563 processes, even though plain remote can use the multi-process
10564 thread id extensions, so that GDB knows the target process's
10566 return rs->extended && remote_multi_process_p (rs);
10570 remote_supports_cond_tracepoints (void)
10572 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
10576 remote_supports_cond_breakpoints (struct target_ops *self)
10578 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
10582 remote_supports_fast_tracepoints (void)
10584 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
10588 remote_supports_static_tracepoints (void)
10590 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
10594 remote_supports_install_in_trace (void)
10596 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
10600 remote_supports_enable_disable_tracepoint (struct target_ops *self)
10602 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10607 remote_supports_string_tracing (struct target_ops *self)
10609 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
10613 remote_can_run_breakpoint_commands (struct target_ops *self)
10615 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
10619 remote_trace_init (struct target_ops *self)
10622 remote_get_noisy_reply (&target_buf, &target_buf_size);
10623 if (strcmp (target_buf, "OK") != 0)
10624 error (_("Target does not support this command."));
10627 static void free_actions_list (char **actions_list);
10628 static void free_actions_list_cleanup_wrapper (void *);
10630 free_actions_list_cleanup_wrapper (void *al)
10632 free_actions_list (al);
10636 free_actions_list (char **actions_list)
10640 if (actions_list == 0)
10643 for (ndx = 0; actions_list[ndx]; ndx++)
10644 xfree (actions_list[ndx]);
10646 xfree (actions_list);
10649 /* Recursive routine to walk through command list including loops, and
10650 download packets for each command. */
10653 remote_download_command_source (int num, ULONGEST addr,
10654 struct command_line *cmds)
10656 struct remote_state *rs = get_remote_state ();
10657 struct command_line *cmd;
10659 for (cmd = cmds; cmd; cmd = cmd->next)
10661 QUIT; /* Allow user to bail out with ^C. */
10662 strcpy (rs->buf, "QTDPsrc:");
10663 encode_source_string (num, addr, "cmd", cmd->line,
10664 rs->buf + strlen (rs->buf),
10665 rs->buf_size - strlen (rs->buf));
10667 remote_get_noisy_reply (&target_buf, &target_buf_size);
10668 if (strcmp (target_buf, "OK"))
10669 warning (_("Target does not support source download."));
10671 if (cmd->control_type == while_control
10672 || cmd->control_type == while_stepping_control)
10674 remote_download_command_source (num, addr, *cmd->body_list);
10676 QUIT; /* Allow user to bail out with ^C. */
10677 strcpy (rs->buf, "QTDPsrc:");
10678 encode_source_string (num, addr, "cmd", "end",
10679 rs->buf + strlen (rs->buf),
10680 rs->buf_size - strlen (rs->buf));
10682 remote_get_noisy_reply (&target_buf, &target_buf_size);
10683 if (strcmp (target_buf, "OK"))
10684 warning (_("Target does not support source download."));
10690 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
10692 #define BUF_SIZE 2048
10696 char buf[BUF_SIZE];
10697 char **tdp_actions;
10698 char **stepping_actions;
10700 struct cleanup *old_chain = NULL;
10701 struct agent_expr *aexpr;
10702 struct cleanup *aexpr_chain = NULL;
10704 struct breakpoint *b = loc->owner;
10705 struct tracepoint *t = (struct tracepoint *) b;
10707 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10708 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10710 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10713 tpaddr = loc->address;
10714 sprintf_vma (addrbuf, tpaddr);
10715 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10716 addrbuf, /* address */
10717 (b->enable_state == bp_enabled ? 'E' : 'D'),
10718 t->step_count, t->pass_count);
10719 /* Fast tracepoints are mostly handled by the target, but we can
10720 tell the target how big of an instruction block should be moved
10722 if (b->type == bp_fast_tracepoint)
10724 /* Only test for support at download time; we may not know
10725 target capabilities at definition time. */
10726 if (remote_supports_fast_tracepoints ())
10730 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10731 tpaddr, &isize, NULL))
10732 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10735 /* If it passed validation at definition but fails now,
10736 something is very wrong. */
10737 internal_error (__FILE__, __LINE__,
10738 _("Fast tracepoint not "
10739 "valid during download"));
10742 /* Fast tracepoints are functionally identical to regular
10743 tracepoints, so don't take lack of support as a reason to
10744 give up on the trace run. */
10745 warning (_("Target does not support fast tracepoints, "
10746 "downloading %d as regular tracepoint"), b->number);
10748 else if (b->type == bp_static_tracepoint)
10750 /* Only test for support at download time; we may not know
10751 target capabilities at definition time. */
10752 if (remote_supports_static_tracepoints ())
10754 struct static_tracepoint_marker marker;
10756 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10757 strcat (buf, ":S");
10759 error (_("Static tracepoint not valid during download"));
10762 /* Fast tracepoints are functionally identical to regular
10763 tracepoints, so don't take lack of support as a reason
10764 to give up on the trace run. */
10765 error (_("Target does not support static tracepoints"));
10767 /* If the tracepoint has a conditional, make it into an agent
10768 expression and append to the definition. */
10771 /* Only test support at download time, we may not know target
10772 capabilities at definition time. */
10773 if (remote_supports_cond_tracepoints ())
10775 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10776 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10777 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10779 pkt = buf + strlen (buf);
10780 for (ndx = 0; ndx < aexpr->len; ++ndx)
10781 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10783 do_cleanups (aexpr_chain);
10786 warning (_("Target does not support conditional tracepoints, "
10787 "ignoring tp %d cond"), b->number);
10790 if (b->commands || *default_collect)
10793 remote_get_noisy_reply (&target_buf, &target_buf_size);
10794 if (strcmp (target_buf, "OK"))
10795 error (_("Target does not support tracepoints."));
10797 /* do_single_steps (t); */
10800 for (ndx = 0; tdp_actions[ndx]; ndx++)
10802 QUIT; /* Allow user to bail out with ^C. */
10803 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10804 b->number, addrbuf, /* address */
10806 ((tdp_actions[ndx + 1] || stepping_actions)
10809 remote_get_noisy_reply (&target_buf,
10811 if (strcmp (target_buf, "OK"))
10812 error (_("Error on target while setting tracepoints."));
10815 if (stepping_actions)
10817 for (ndx = 0; stepping_actions[ndx]; ndx++)
10819 QUIT; /* Allow user to bail out with ^C. */
10820 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10821 b->number, addrbuf, /* address */
10822 ((ndx == 0) ? "S" : ""),
10823 stepping_actions[ndx],
10824 (stepping_actions[ndx + 1] ? "-" : ""));
10826 remote_get_noisy_reply (&target_buf,
10828 if (strcmp (target_buf, "OK"))
10829 error (_("Error on target while setting tracepoints."));
10833 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
10835 if (b->addr_string)
10837 strcpy (buf, "QTDPsrc:");
10838 encode_source_string (b->number, loc->address,
10839 "at", b->addr_string, buf + strlen (buf),
10840 2048 - strlen (buf));
10843 remote_get_noisy_reply (&target_buf, &target_buf_size);
10844 if (strcmp (target_buf, "OK"))
10845 warning (_("Target does not support source download."));
10847 if (b->cond_string)
10849 strcpy (buf, "QTDPsrc:");
10850 encode_source_string (b->number, loc->address,
10851 "cond", b->cond_string, buf + strlen (buf),
10852 2048 - strlen (buf));
10854 remote_get_noisy_reply (&target_buf, &target_buf_size);
10855 if (strcmp (target_buf, "OK"))
10856 warning (_("Target does not support source download."));
10858 remote_download_command_source (b->number, loc->address,
10859 breakpoint_commands (b));
10862 do_cleanups (old_chain);
10866 remote_can_download_tracepoint (struct target_ops *self)
10868 struct remote_state *rs = get_remote_state ();
10869 struct trace_status *ts;
10872 /* Don't try to install tracepoints until we've relocated our
10873 symbols, and fetched and merged the target's tracepoint list with
10875 if (rs->starting_up)
10878 ts = current_trace_status ();
10879 status = remote_get_trace_status (self, ts);
10881 if (status == -1 || !ts->running_known || !ts->running)
10884 /* If we are in a tracing experiment, but remote stub doesn't support
10885 installing tracepoint in trace, we have to return. */
10886 if (!remote_supports_install_in_trace ())
10894 remote_download_trace_state_variable (struct target_ops *self,
10895 struct trace_state_variable *tsv)
10897 struct remote_state *rs = get_remote_state ();
10900 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10901 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10903 p = rs->buf + strlen (rs->buf);
10904 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10905 error (_("Trace state variable name too long for tsv definition packet"));
10906 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
10909 remote_get_noisy_reply (&target_buf, &target_buf_size);
10910 if (*target_buf == '\0')
10911 error (_("Target does not support this command."));
10912 if (strcmp (target_buf, "OK") != 0)
10913 error (_("Error on target while downloading trace state variable."));
10917 remote_enable_tracepoint (struct target_ops *self,
10918 struct bp_location *location)
10920 struct remote_state *rs = get_remote_state ();
10923 sprintf_vma (addr_buf, location->address);
10924 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10925 location->owner->number, addr_buf);
10927 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10928 if (*rs->buf == '\0')
10929 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10930 if (strcmp (rs->buf, "OK") != 0)
10931 error (_("Error on target while enabling tracepoint."));
10935 remote_disable_tracepoint (struct target_ops *self,
10936 struct bp_location *location)
10938 struct remote_state *rs = get_remote_state ();
10941 sprintf_vma (addr_buf, location->address);
10942 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10943 location->owner->number, addr_buf);
10945 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10946 if (*rs->buf == '\0')
10947 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10948 if (strcmp (rs->buf, "OK") != 0)
10949 error (_("Error on target while disabling tracepoint."));
10953 remote_trace_set_readonly_regions (struct target_ops *self)
10957 bfd_size_type size;
10963 return; /* No information to give. */
10965 strcpy (target_buf, "QTro");
10966 offset = strlen (target_buf);
10967 for (s = exec_bfd->sections; s; s = s->next)
10969 char tmp1[40], tmp2[40];
10972 if ((s->flags & SEC_LOAD) == 0 ||
10973 /* (s->flags & SEC_CODE) == 0 || */
10974 (s->flags & SEC_READONLY) == 0)
10978 vma = bfd_get_section_vma (abfd, s);
10979 size = bfd_get_section_size (s);
10980 sprintf_vma (tmp1, vma);
10981 sprintf_vma (tmp2, vma + size);
10982 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10983 if (offset + sec_length + 1 > target_buf_size)
10985 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
10987 Too many sections for read-only sections definition packet."));
10990 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10992 offset += sec_length;
10996 putpkt (target_buf);
10997 getpkt (&target_buf, &target_buf_size, 0);
11002 remote_trace_start (struct target_ops *self)
11004 putpkt ("QTStart");
11005 remote_get_noisy_reply (&target_buf, &target_buf_size);
11006 if (*target_buf == '\0')
11007 error (_("Target does not support this command."));
11008 if (strcmp (target_buf, "OK") != 0)
11009 error (_("Bogus reply from target: %s"), target_buf);
11013 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11015 /* Initialize it just to avoid a GCC false warning. */
11017 /* FIXME we need to get register block size some other way. */
11018 extern int trace_regblock_size;
11019 enum packet_result result;
11021 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11024 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11026 putpkt ("qTStatus");
11030 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11032 CATCH (ex, RETURN_MASK_ERROR)
11034 if (ex.error != TARGET_CLOSE_ERROR)
11036 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11039 throw_exception (ex);
11043 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11045 /* If the remote target doesn't do tracing, flag it. */
11046 if (result == PACKET_UNKNOWN)
11049 /* We're working with a live target. */
11050 ts->filename = NULL;
11053 error (_("Bogus trace status reply from target: %s"), target_buf);
11055 /* Function 'parse_trace_status' sets default value of each field of
11056 'ts' at first, so we don't have to do it here. */
11057 parse_trace_status (p, ts);
11059 return ts->running;
11063 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
11064 struct uploaded_tp *utp)
11066 struct remote_state *rs = get_remote_state ();
11068 struct bp_location *loc;
11069 struct tracepoint *tp = (struct tracepoint *) bp;
11070 size_t size = get_remote_packet_size ();
11074 tp->base.hit_count = 0;
11075 tp->traceframe_usage = 0;
11076 for (loc = tp->base.loc; loc; loc = loc->next)
11078 /* If the tracepoint was never downloaded, don't go asking for
11080 if (tp->number_on_target == 0)
11082 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11083 phex_nz (loc->address, 0));
11085 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11086 if (reply && *reply)
11089 parse_tracepoint_status (reply + 1, bp, utp);
11095 utp->hit_count = 0;
11096 utp->traceframe_usage = 0;
11097 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11098 phex_nz (utp->addr, 0));
11100 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11101 if (reply && *reply)
11104 parse_tracepoint_status (reply + 1, bp, utp);
11110 remote_trace_stop (struct target_ops *self)
11113 remote_get_noisy_reply (&target_buf, &target_buf_size);
11114 if (*target_buf == '\0')
11115 error (_("Target does not support this command."));
11116 if (strcmp (target_buf, "OK") != 0)
11117 error (_("Bogus reply from target: %s"), target_buf);
11121 remote_trace_find (struct target_ops *self,
11122 enum trace_find_type type, int num,
11123 CORE_ADDR addr1, CORE_ADDR addr2,
11126 struct remote_state *rs = get_remote_state ();
11127 char *endbuf = rs->buf + get_remote_packet_size ();
11129 int target_frameno = -1, target_tracept = -1;
11131 /* Lookups other than by absolute frame number depend on the current
11132 trace selected, so make sure it is correct on the remote end
11134 if (type != tfind_number)
11135 set_remote_traceframe ();
11138 strcpy (p, "QTFrame:");
11139 p = strchr (p, '\0');
11143 xsnprintf (p, endbuf - p, "%x", num);
11146 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11149 xsnprintf (p, endbuf - p, "tdp:%x", num);
11152 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11153 phex_nz (addr2, 0));
11155 case tfind_outside:
11156 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11157 phex_nz (addr2, 0));
11160 error (_("Unknown trace find type %d"), type);
11164 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11165 if (*reply == '\0')
11166 error (_("Target does not support this command."));
11168 while (reply && *reply)
11173 target_frameno = (int) strtol (p, &reply, 16);
11175 error (_("Unable to parse trace frame number"));
11176 /* Don't update our remote traceframe number cache on failure
11177 to select a remote traceframe. */
11178 if (target_frameno == -1)
11183 target_tracept = (int) strtol (p, &reply, 16);
11185 error (_("Unable to parse tracepoint number"));
11187 case 'O': /* "OK"? */
11188 if (reply[1] == 'K' && reply[2] == '\0')
11191 error (_("Bogus reply from target: %s"), reply);
11194 error (_("Bogus reply from target: %s"), reply);
11197 *tpp = target_tracept;
11199 rs->remote_traceframe_number = target_frameno;
11200 return target_frameno;
11204 remote_get_trace_state_variable_value (struct target_ops *self,
11205 int tsvnum, LONGEST *val)
11207 struct remote_state *rs = get_remote_state ();
11211 set_remote_traceframe ();
11213 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11215 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11216 if (reply && *reply)
11220 unpack_varlen_hex (reply + 1, &uval);
11221 *val = (LONGEST) uval;
11229 remote_save_trace_data (struct target_ops *self, const char *filename)
11231 struct remote_state *rs = get_remote_state ();
11235 strcpy (p, "QTSave:");
11237 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11238 error (_("Remote file name too long for trace save packet"));
11239 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11242 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11243 if (*reply == '\0')
11244 error (_("Target does not support this command."));
11245 if (strcmp (reply, "OK") != 0)
11246 error (_("Bogus reply from target: %s"), reply);
11250 /* This is basically a memory transfer, but needs to be its own packet
11251 because we don't know how the target actually organizes its trace
11252 memory, plus we want to be able to ask for as much as possible, but
11253 not be unhappy if we don't get as much as we ask for. */
11256 remote_get_raw_trace_data (struct target_ops *self,
11257 gdb_byte *buf, ULONGEST offset, LONGEST len)
11259 struct remote_state *rs = get_remote_state ();
11265 strcpy (p, "qTBuffer:");
11267 p += hexnumstr (p, offset);
11269 p += hexnumstr (p, len);
11273 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11274 if (reply && *reply)
11276 /* 'l' by itself means we're at the end of the buffer and
11277 there is nothing more to get. */
11281 /* Convert the reply into binary. Limit the number of bytes to
11282 convert according to our passed-in buffer size, rather than
11283 what was returned in the packet; if the target is
11284 unexpectedly generous and gives us a bigger reply than we
11285 asked for, we don't want to crash. */
11286 rslt = hex2bin (target_buf, buf, len);
11290 /* Something went wrong, flag as an error. */
11295 remote_set_disconnected_tracing (struct target_ops *self, int val)
11297 struct remote_state *rs = get_remote_state ();
11299 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11303 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11305 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11306 if (*reply == '\0')
11307 error (_("Target does not support this command."));
11308 if (strcmp (reply, "OK") != 0)
11309 error (_("Bogus reply from target: %s"), reply);
11312 warning (_("Target does not support disconnected tracing."));
11316 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11318 struct thread_info *info = find_thread_ptid (ptid);
11320 if (info && info->priv)
11321 return info->priv->core;
11326 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11328 struct remote_state *rs = get_remote_state ();
11331 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11333 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11334 if (*reply == '\0')
11335 error (_("Target does not support this command."));
11336 if (strcmp (reply, "OK") != 0)
11337 error (_("Bogus reply from target: %s"), reply);
11340 static struct traceframe_info *
11341 remote_traceframe_info (struct target_ops *self)
11345 text = target_read_stralloc (¤t_target,
11346 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11349 struct traceframe_info *info;
11350 struct cleanup *back_to = make_cleanup (xfree, text);
11352 info = parse_traceframe_info (text);
11353 do_cleanups (back_to);
11360 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11361 instruction on which a fast tracepoint may be placed. Returns -1
11362 if the packet is not supported, and 0 if the minimum instruction
11363 length is unknown. */
11366 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11368 struct remote_state *rs = get_remote_state ();
11371 /* If we're not debugging a process yet, the IPA can't be
11373 if (!target_has_execution)
11376 /* Make sure the remote is pointing at the right process. */
11377 set_general_process ();
11379 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11381 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11382 if (*reply == '\0')
11386 ULONGEST min_insn_len;
11388 unpack_varlen_hex (reply, &min_insn_len);
11390 return (int) min_insn_len;
11395 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11397 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11399 struct remote_state *rs = get_remote_state ();
11400 char *buf = rs->buf;
11401 char *endbuf = rs->buf + get_remote_packet_size ();
11402 enum packet_result result;
11404 gdb_assert (val >= 0 || val == -1);
11405 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11406 /* Send -1 as literal "-1" to avoid host size dependency. */
11410 buf += hexnumstr (buf, (ULONGEST) -val);
11413 buf += hexnumstr (buf, (ULONGEST) val);
11416 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11417 result = packet_ok (rs->buf,
11418 &remote_protocol_packets[PACKET_QTBuffer_size]);
11420 if (result != PACKET_OK)
11421 warning (_("Bogus reply from target: %s"), rs->buf);
11426 remote_set_trace_notes (struct target_ops *self,
11427 const char *user, const char *notes,
11428 const char *stop_notes)
11430 struct remote_state *rs = get_remote_state ();
11432 char *buf = rs->buf;
11433 char *endbuf = rs->buf + get_remote_packet_size ();
11436 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11439 buf += xsnprintf (buf, endbuf - buf, "user:");
11440 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11446 buf += xsnprintf (buf, endbuf - buf, "notes:");
11447 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11453 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11454 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11458 /* Ensure the buffer is terminated. */
11462 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11463 if (*reply == '\0')
11466 if (strcmp (reply, "OK") != 0)
11467 error (_("Bogus reply from target: %s"), reply);
11473 remote_use_agent (struct target_ops *self, int use)
11475 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11477 struct remote_state *rs = get_remote_state ();
11479 /* If the stub supports QAgent. */
11480 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11482 getpkt (&rs->buf, &rs->buf_size, 0);
11484 if (strcmp (rs->buf, "OK") == 0)
11495 remote_can_use_agent (struct target_ops *self)
11497 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11500 struct btrace_target_info
11502 /* The ptid of the traced thread. */
11505 /* The obtained branch trace configuration. */
11506 struct btrace_config conf;
11509 /* Reset our idea of our target's btrace configuration. */
11512 remote_btrace_reset (void)
11514 struct remote_state *rs = get_remote_state ();
11516 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11519 /* Check whether the target supports branch tracing. */
11522 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
11524 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
11526 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
11531 case BTRACE_FORMAT_NONE:
11534 case BTRACE_FORMAT_BTS:
11535 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11538 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
11541 /* Synchronize the configuration with the target. */
11544 btrace_sync_conf (const struct btrace_config *conf)
11546 struct packet_config *packet;
11547 struct remote_state *rs;
11548 char *buf, *pos, *endbuf;
11550 rs = get_remote_state ();
11552 endbuf = buf + get_remote_packet_size ();
11554 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11555 if (packet_config_support (packet) == PACKET_ENABLE
11556 && conf->bts.size != rs->btrace_config.bts.size)
11559 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11563 getpkt (&buf, &rs->buf_size, 0);
11565 if (packet_ok (buf, packet) == PACKET_ERROR)
11567 if (buf[0] == 'E' && buf[1] == '.')
11568 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11570 error (_("Failed to configure the BTS buffer size."));
11573 rs->btrace_config.bts.size = conf->bts.size;
11577 /* Read the current thread's btrace configuration from the target and
11578 store it into CONF. */
11581 btrace_read_config (struct btrace_config *conf)
11585 xml = target_read_stralloc (¤t_target,
11586 TARGET_OBJECT_BTRACE_CONF, "");
11589 struct cleanup *cleanup;
11591 cleanup = make_cleanup (xfree, xml);
11592 parse_xml_btrace_conf (conf, xml);
11593 do_cleanups (cleanup);
11597 /* Enable branch tracing. */
11599 static struct btrace_target_info *
11600 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11601 const struct btrace_config *conf)
11603 struct btrace_target_info *tinfo = NULL;
11604 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11605 struct remote_state *rs = get_remote_state ();
11606 char *buf = rs->buf;
11607 char *endbuf = rs->buf + get_remote_packet_size ();
11609 if (packet_config_support (packet) != PACKET_ENABLE)
11610 error (_("Target does not support branch tracing."));
11612 btrace_sync_conf (conf);
11614 set_general_thread (ptid);
11616 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11618 getpkt (&rs->buf, &rs->buf_size, 0);
11620 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11622 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11623 error (_("Could not enable branch tracing for %s: %s"),
11624 target_pid_to_str (ptid), rs->buf + 2);
11626 error (_("Could not enable branch tracing for %s."),
11627 target_pid_to_str (ptid));
11630 tinfo = xzalloc (sizeof (*tinfo));
11631 tinfo->ptid = ptid;
11633 /* If we fail to read the configuration, we lose some information, but the
11634 tracing itself is not impacted. */
11637 btrace_read_config (&tinfo->conf);
11639 CATCH (err, RETURN_MASK_ERROR)
11641 if (err.message != NULL)
11642 warning ("%s", err.message);
11649 /* Disable branch tracing. */
11652 remote_disable_btrace (struct target_ops *self,
11653 struct btrace_target_info *tinfo)
11655 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11656 struct remote_state *rs = get_remote_state ();
11657 char *buf = rs->buf;
11658 char *endbuf = rs->buf + get_remote_packet_size ();
11660 if (packet_config_support (packet) != PACKET_ENABLE)
11661 error (_("Target does not support branch tracing."));
11663 set_general_thread (tinfo->ptid);
11665 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11667 getpkt (&rs->buf, &rs->buf_size, 0);
11669 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11671 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11672 error (_("Could not disable branch tracing for %s: %s"),
11673 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11675 error (_("Could not disable branch tracing for %s."),
11676 target_pid_to_str (tinfo->ptid));
11682 /* Teardown branch tracing. */
11685 remote_teardown_btrace (struct target_ops *self,
11686 struct btrace_target_info *tinfo)
11688 /* We must not talk to the target during teardown. */
11692 /* Read the branch trace. */
11694 static enum btrace_error
11695 remote_read_btrace (struct target_ops *self,
11696 struct btrace_data *btrace,
11697 struct btrace_target_info *tinfo,
11698 enum btrace_read_type type)
11700 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11701 struct remote_state *rs = get_remote_state ();
11702 struct cleanup *cleanup;
11706 if (packet_config_support (packet) != PACKET_ENABLE)
11707 error (_("Target does not support branch tracing."));
11709 #if !defined(HAVE_LIBEXPAT)
11710 error (_("Cannot process branch tracing result. XML parsing not supported."));
11715 case BTRACE_READ_ALL:
11718 case BTRACE_READ_NEW:
11721 case BTRACE_READ_DELTA:
11725 internal_error (__FILE__, __LINE__,
11726 _("Bad branch tracing read type: %u."),
11727 (unsigned int) type);
11730 xml = target_read_stralloc (¤t_target,
11731 TARGET_OBJECT_BTRACE, annex);
11733 return BTRACE_ERR_UNKNOWN;
11735 cleanup = make_cleanup (xfree, xml);
11736 parse_xml_btrace (btrace, xml);
11737 do_cleanups (cleanup);
11739 return BTRACE_ERR_NONE;
11742 static const struct btrace_config *
11743 remote_btrace_conf (struct target_ops *self,
11744 const struct btrace_target_info *tinfo)
11746 return &tinfo->conf;
11750 remote_augmented_libraries_svr4_read (struct target_ops *self)
11752 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11756 /* Implementation of to_load. */
11759 remote_load (struct target_ops *self, const char *name, int from_tty)
11761 generic_load (name, from_tty);
11765 init_remote_ops (void)
11767 remote_ops.to_shortname = "remote";
11768 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11769 remote_ops.to_doc =
11770 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11771 Specify the serial device it is connected to\n\
11772 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11773 remote_ops.to_open = remote_open;
11774 remote_ops.to_close = remote_close;
11775 remote_ops.to_detach = remote_detach;
11776 remote_ops.to_disconnect = remote_disconnect;
11777 remote_ops.to_resume = remote_resume;
11778 remote_ops.to_wait = remote_wait;
11779 remote_ops.to_fetch_registers = remote_fetch_registers;
11780 remote_ops.to_store_registers = remote_store_registers;
11781 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11782 remote_ops.to_files_info = remote_files_info;
11783 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11784 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11785 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
11786 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
11787 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
11788 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
11789 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11790 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11791 remote_ops.to_watchpoint_addr_within_range =
11792 remote_watchpoint_addr_within_range;
11793 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11794 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11795 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11796 remote_ops.to_region_ok_for_hw_watchpoint
11797 = remote_region_ok_for_hw_watchpoint;
11798 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11799 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11800 remote_ops.to_kill = remote_kill;
11801 remote_ops.to_load = remote_load;
11802 remote_ops.to_mourn_inferior = remote_mourn;
11803 remote_ops.to_pass_signals = remote_pass_signals;
11804 remote_ops.to_program_signals = remote_program_signals;
11805 remote_ops.to_thread_alive = remote_thread_alive;
11806 remote_ops.to_update_thread_list = remote_update_thread_list;
11807 remote_ops.to_pid_to_str = remote_pid_to_str;
11808 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11809 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11810 remote_ops.to_stop = remote_stop;
11811 remote_ops.to_xfer_partial = remote_xfer_partial;
11812 remote_ops.to_rcmd = remote_rcmd;
11813 remote_ops.to_log_command = serial_log_command;
11814 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11815 remote_ops.to_stratum = process_stratum;
11816 remote_ops.to_has_all_memory = default_child_has_all_memory;
11817 remote_ops.to_has_memory = default_child_has_memory;
11818 remote_ops.to_has_stack = default_child_has_stack;
11819 remote_ops.to_has_registers = default_child_has_registers;
11820 remote_ops.to_has_execution = default_child_has_execution;
11821 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11822 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11823 remote_ops.to_magic = OPS_MAGIC;
11824 remote_ops.to_memory_map = remote_memory_map;
11825 remote_ops.to_flash_erase = remote_flash_erase;
11826 remote_ops.to_flash_done = remote_flash_done;
11827 remote_ops.to_read_description = remote_read_description;
11828 remote_ops.to_search_memory = remote_search_memory;
11829 remote_ops.to_can_async_p = remote_can_async_p;
11830 remote_ops.to_is_async_p = remote_is_async_p;
11831 remote_ops.to_async = remote_async;
11832 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11833 remote_ops.to_terminal_ours = remote_terminal_ours;
11834 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11835 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11836 remote_ops.to_supports_disable_randomization
11837 = remote_supports_disable_randomization;
11838 remote_ops.to_fileio_open = remote_hostio_open;
11839 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11840 remote_ops.to_fileio_pread = remote_hostio_pread;
11841 remote_ops.to_fileio_close = remote_hostio_close;
11842 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11843 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11844 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11845 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11846 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11847 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11848 remote_ops.to_trace_init = remote_trace_init;
11849 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11850 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11851 remote_ops.to_download_trace_state_variable
11852 = remote_download_trace_state_variable;
11853 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11854 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11855 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11856 remote_ops.to_trace_start = remote_trace_start;
11857 remote_ops.to_get_trace_status = remote_get_trace_status;
11858 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11859 remote_ops.to_trace_stop = remote_trace_stop;
11860 remote_ops.to_trace_find = remote_trace_find;
11861 remote_ops.to_get_trace_state_variable_value
11862 = remote_get_trace_state_variable_value;
11863 remote_ops.to_save_trace_data = remote_save_trace_data;
11864 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11865 remote_ops.to_upload_trace_state_variables
11866 = remote_upload_trace_state_variables;
11867 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11868 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11869 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11870 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11871 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11872 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11873 remote_ops.to_core_of_thread = remote_core_of_thread;
11874 remote_ops.to_verify_memory = remote_verify_memory;
11875 remote_ops.to_get_tib_address = remote_get_tib_address;
11876 remote_ops.to_set_permissions = remote_set_permissions;
11877 remote_ops.to_static_tracepoint_marker_at
11878 = remote_static_tracepoint_marker_at;
11879 remote_ops.to_static_tracepoint_markers_by_strid
11880 = remote_static_tracepoint_markers_by_strid;
11881 remote_ops.to_traceframe_info = remote_traceframe_info;
11882 remote_ops.to_use_agent = remote_use_agent;
11883 remote_ops.to_can_use_agent = remote_can_use_agent;
11884 remote_ops.to_supports_btrace = remote_supports_btrace;
11885 remote_ops.to_enable_btrace = remote_enable_btrace;
11886 remote_ops.to_disable_btrace = remote_disable_btrace;
11887 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11888 remote_ops.to_read_btrace = remote_read_btrace;
11889 remote_ops.to_btrace_conf = remote_btrace_conf;
11890 remote_ops.to_augmented_libraries_svr4_read =
11891 remote_augmented_libraries_svr4_read;
11894 /* Set up the extended remote vector by making a copy of the standard
11895 remote vector and adding to it. */
11898 init_extended_remote_ops (void)
11900 extended_remote_ops = remote_ops;
11902 extended_remote_ops.to_shortname = "extended-remote";
11903 extended_remote_ops.to_longname =
11904 "Extended remote serial target in gdb-specific protocol";
11905 extended_remote_ops.to_doc =
11906 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11907 Specify the serial device it is connected to (e.g. /dev/ttya).";
11908 extended_remote_ops.to_open = extended_remote_open;
11909 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11910 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11911 extended_remote_ops.to_detach = extended_remote_detach;
11912 extended_remote_ops.to_attach = extended_remote_attach;
11913 extended_remote_ops.to_post_attach = extended_remote_post_attach;
11914 extended_remote_ops.to_kill = extended_remote_kill;
11915 extended_remote_ops.to_supports_disable_randomization
11916 = extended_remote_supports_disable_randomization;
11920 remote_can_async_p (struct target_ops *ops)
11922 struct remote_state *rs = get_remote_state ();
11924 if (!target_async_permitted)
11925 /* We only enable async when the user specifically asks for it. */
11928 /* We're async whenever the serial device is. */
11929 return serial_can_async_p (rs->remote_desc);
11933 remote_is_async_p (struct target_ops *ops)
11935 struct remote_state *rs = get_remote_state ();
11937 if (!target_async_permitted)
11938 /* We only enable async when the user specifically asks for it. */
11941 /* We're async whenever the serial device is. */
11942 return serial_is_async_p (rs->remote_desc);
11945 /* Pass the SERIAL event on and up to the client. One day this code
11946 will be able to delay notifying the client of an event until the
11947 point where an entire packet has been received. */
11949 static serial_event_ftype remote_async_serial_handler;
11952 remote_async_serial_handler (struct serial *scb, void *context)
11954 struct remote_state *rs = context;
11956 /* Don't propogate error information up to the client. Instead let
11957 the client find out about the error by querying the target. */
11958 inferior_event_handler (INF_REG_EVENT, NULL);
11962 remote_async_inferior_event_handler (gdb_client_data data)
11964 inferior_event_handler (INF_REG_EVENT, NULL);
11968 remote_async (struct target_ops *ops, int enable)
11970 struct remote_state *rs = get_remote_state ();
11974 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11976 /* If there are pending events in the stop reply queue tell the
11977 event loop to process them. */
11978 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11979 mark_async_event_handler (remote_async_inferior_event_token);
11983 serial_async (rs->remote_desc, NULL, NULL);
11984 clear_async_event_handler (remote_async_inferior_event_token);
11989 set_remote_cmd (char *args, int from_tty)
11991 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
11995 show_remote_cmd (char *args, int from_tty)
11997 /* We can't just use cmd_show_list here, because we want to skip
11998 the redundant "show remote Z-packet" and the legacy aliases. */
11999 struct cleanup *showlist_chain;
12000 struct cmd_list_element *list = remote_show_cmdlist;
12001 struct ui_out *uiout = current_uiout;
12003 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12004 for (; list != NULL; list = list->next)
12005 if (strcmp (list->name, "Z-packet") == 0)
12007 else if (list->type == not_set_cmd)
12008 /* Alias commands are exactly like the original, except they
12009 don't have the normal type. */
12013 struct cleanup *option_chain
12014 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
12016 ui_out_field_string (uiout, "name", list->name);
12017 ui_out_text (uiout, ": ");
12018 if (list->type == show_cmd)
12019 do_show_command ((char *) NULL, from_tty, list);
12021 cmd_func (list, NULL, from_tty);
12022 /* Close the tuple. */
12023 do_cleanups (option_chain);
12026 /* Close the tuple. */
12027 do_cleanups (showlist_chain);
12031 /* Function to be called whenever a new objfile (shlib) is detected. */
12033 remote_new_objfile (struct objfile *objfile)
12035 struct remote_state *rs = get_remote_state ();
12037 if (rs->remote_desc != 0) /* Have a remote connection. */
12038 remote_check_symbols ();
12041 /* Pull all the tracepoints defined on the target and create local
12042 data structures representing them. We don't want to create real
12043 tracepoints yet, we don't want to mess up the user's existing
12047 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
12049 struct remote_state *rs = get_remote_state ();
12052 /* Ask for a first packet of tracepoint definition. */
12054 getpkt (&rs->buf, &rs->buf_size, 0);
12056 while (*p && *p != 'l')
12058 parse_tracepoint_definition (p, utpp);
12059 /* Ask for another packet of tracepoint definition. */
12061 getpkt (&rs->buf, &rs->buf_size, 0);
12068 remote_upload_trace_state_variables (struct target_ops *self,
12069 struct uploaded_tsv **utsvp)
12071 struct remote_state *rs = get_remote_state ();
12074 /* Ask for a first packet of variable definition. */
12076 getpkt (&rs->buf, &rs->buf_size, 0);
12078 while (*p && *p != 'l')
12080 parse_tsv_definition (p, utsvp);
12081 /* Ask for another packet of variable definition. */
12083 getpkt (&rs->buf, &rs->buf_size, 0);
12089 /* The "set/show range-stepping" show hook. */
12092 show_range_stepping (struct ui_file *file, int from_tty,
12093 struct cmd_list_element *c,
12096 fprintf_filtered (file,
12097 _("Debugger's willingness to use range stepping "
12098 "is %s.\n"), value);
12101 /* The "set/show range-stepping" set hook. */
12104 set_range_stepping (char *ignore_args, int from_tty,
12105 struct cmd_list_element *c)
12107 struct remote_state *rs = get_remote_state ();
12109 /* Whene enabling, check whether range stepping is actually
12110 supported by the target, and warn if not. */
12111 if (use_range_stepping)
12113 if (rs->remote_desc != NULL)
12115 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12116 remote_vcont_probe (rs);
12118 if (packet_support (PACKET_vCont) == PACKET_ENABLE
12119 && rs->supports_vCont.r)
12123 warning (_("Range stepping is not supported by the current target"));
12128 _initialize_remote (void)
12130 struct remote_state *rs;
12131 struct cmd_list_element *cmd;
12132 const char *cmd_name;
12134 /* architecture specific data */
12135 remote_gdbarch_data_handle =
12136 gdbarch_data_register_post_init (init_remote_state);
12137 remote_g_packet_data_handle =
12138 gdbarch_data_register_pre_init (remote_g_packet_data_init);
12140 /* Initialize the per-target state. At the moment there is only one
12141 of these, not one per target. Only one target is active at a
12143 remote_state = new_remote_state ();
12145 init_remote_ops ();
12146 add_target (&remote_ops);
12148 init_extended_remote_ops ();
12149 add_target (&extended_remote_ops);
12151 /* Hook into new objfile notification. */
12152 observer_attach_new_objfile (remote_new_objfile);
12153 /* We're no longer interested in notification events of an inferior
12155 observer_attach_inferior_exit (discard_pending_stop_replies);
12157 /* Set up signal handlers. */
12158 async_sigint_remote_token =
12159 create_async_signal_handler (async_remote_interrupt, NULL);
12160 async_sigint_remote_twice_token =
12161 create_async_signal_handler (async_remote_interrupt_twice, NULL);
12164 init_remote_threadtests ();
12167 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
12168 /* set/show remote ... */
12170 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12171 Remote protocol specific variables\n\
12172 Configure various remote-protocol specific variables such as\n\
12173 the packets being used"),
12174 &remote_set_cmdlist, "set remote ",
12175 0 /* allow-unknown */, &setlist);
12176 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12177 Remote protocol specific variables\n\
12178 Configure various remote-protocol specific variables such as\n\
12179 the packets being used"),
12180 &remote_show_cmdlist, "show remote ",
12181 0 /* allow-unknown */, &showlist);
12183 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12184 Compare section data on target to the exec file.\n\
12185 Argument is a single section name (default: all loaded sections).\n\
12186 To compare only read-only loaded sections, specify the -r option."),
12189 add_cmd ("packet", class_maintenance, packet_command, _("\
12190 Send an arbitrary packet to a remote target.\n\
12191 maintenance packet TEXT\n\
12192 If GDB is talking to an inferior via the GDB serial protocol, then\n\
12193 this command sends the string TEXT to the inferior, and displays the\n\
12194 response packet. GDB supplies the initial `$' character, and the\n\
12195 terminating `#' character and checksum."),
12198 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12199 Set whether to send break if interrupted."), _("\
12200 Show whether to send break if interrupted."), _("\
12201 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12202 set_remotebreak, show_remotebreak,
12203 &setlist, &showlist);
12204 cmd_name = "remotebreak";
12205 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12206 deprecate_cmd (cmd, "set remote interrupt-sequence");
12207 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12208 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12209 deprecate_cmd (cmd, "show remote interrupt-sequence");
12211 add_setshow_enum_cmd ("interrupt-sequence", class_support,
12212 interrupt_sequence_modes, &interrupt_sequence_mode,
12214 Set interrupt sequence to remote target."), _("\
12215 Show interrupt sequence to remote target."), _("\
12216 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12217 NULL, show_interrupt_sequence,
12218 &remote_set_cmdlist,
12219 &remote_show_cmdlist);
12221 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12222 &interrupt_on_connect, _("\
12223 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12224 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12225 If set, interrupt sequence is sent to remote target."),
12227 &remote_set_cmdlist, &remote_show_cmdlist);
12229 /* Install commands for configuring memory read/write packets. */
12231 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12232 Set the maximum number of bytes per memory write packet (deprecated)."),
12234 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12235 Show the maximum number of bytes per memory write packet (deprecated)."),
12237 add_cmd ("memory-write-packet-size", no_class,
12238 set_memory_write_packet_size, _("\
12239 Set the maximum number of bytes per memory-write packet.\n\
12240 Specify the number of bytes in a packet or 0 (zero) for the\n\
12241 default packet size. The actual limit is further reduced\n\
12242 dependent on the target. Specify ``fixed'' to disable the\n\
12243 further restriction and ``limit'' to enable that restriction."),
12244 &remote_set_cmdlist);
12245 add_cmd ("memory-read-packet-size", no_class,
12246 set_memory_read_packet_size, _("\
12247 Set the maximum number of bytes per memory-read packet.\n\
12248 Specify the number of bytes in a packet or 0 (zero) for the\n\
12249 default packet size. The actual limit is further reduced\n\
12250 dependent on the target. Specify ``fixed'' to disable the\n\
12251 further restriction and ``limit'' to enable that restriction."),
12252 &remote_set_cmdlist);
12253 add_cmd ("memory-write-packet-size", no_class,
12254 show_memory_write_packet_size,
12255 _("Show the maximum number of bytes per memory-write packet."),
12256 &remote_show_cmdlist);
12257 add_cmd ("memory-read-packet-size", no_class,
12258 show_memory_read_packet_size,
12259 _("Show the maximum number of bytes per memory-read packet."),
12260 &remote_show_cmdlist);
12262 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12263 &remote_hw_watchpoint_limit, _("\
12264 Set the maximum number of target hardware watchpoints."), _("\
12265 Show the maximum number of target hardware watchpoints."), _("\
12266 Specify a negative limit for unlimited."),
12267 NULL, NULL, /* FIXME: i18n: The maximum
12268 number of target hardware
12269 watchpoints is %s. */
12270 &remote_set_cmdlist, &remote_show_cmdlist);
12271 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12272 &remote_hw_watchpoint_length_limit, _("\
12273 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12274 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12275 Specify a negative limit for unlimited."),
12276 NULL, NULL, /* FIXME: i18n: The maximum
12277 length (in bytes) of a target
12278 hardware watchpoint is %s. */
12279 &remote_set_cmdlist, &remote_show_cmdlist);
12280 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12281 &remote_hw_breakpoint_limit, _("\
12282 Set the maximum number of target hardware breakpoints."), _("\
12283 Show the maximum number of target hardware breakpoints."), _("\
12284 Specify a negative limit for unlimited."),
12285 NULL, NULL, /* FIXME: i18n: The maximum
12286 number of target hardware
12287 breakpoints is %s. */
12288 &remote_set_cmdlist, &remote_show_cmdlist);
12290 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12291 &remote_address_size, _("\
12292 Set the maximum size of the address (in bits) in a memory packet."), _("\
12293 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12295 NULL, /* FIXME: i18n: */
12296 &setlist, &showlist);
12298 init_all_packet_configs ();
12300 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12301 "X", "binary-download", 1);
12303 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12304 "vCont", "verbose-resume", 0);
12306 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12307 "QPassSignals", "pass-signals", 0);
12309 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12310 "QProgramSignals", "program-signals", 0);
12312 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12313 "qSymbol", "symbol-lookup", 0);
12315 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12316 "P", "set-register", 1);
12318 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12319 "p", "fetch-register", 1);
12321 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12322 "Z0", "software-breakpoint", 0);
12324 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12325 "Z1", "hardware-breakpoint", 0);
12327 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12328 "Z2", "write-watchpoint", 0);
12330 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12331 "Z3", "read-watchpoint", 0);
12333 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12334 "Z4", "access-watchpoint", 0);
12336 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12337 "qXfer:auxv:read", "read-aux-vector", 0);
12339 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12340 "qXfer:features:read", "target-features", 0);
12342 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12343 "qXfer:libraries:read", "library-info", 0);
12345 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12346 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12348 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12349 "qXfer:memory-map:read", "memory-map", 0);
12351 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12352 "qXfer:spu:read", "read-spu-object", 0);
12354 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12355 "qXfer:spu:write", "write-spu-object", 0);
12357 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12358 "qXfer:osdata:read", "osdata", 0);
12360 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12361 "qXfer:threads:read", "threads", 0);
12363 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12364 "qXfer:siginfo:read", "read-siginfo-object", 0);
12366 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12367 "qXfer:siginfo:write", "write-siginfo-object", 0);
12369 add_packet_config_cmd
12370 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12371 "qXfer:traceframe-info:read", "traceframe-info", 0);
12373 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12374 "qXfer:uib:read", "unwind-info-block", 0);
12376 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12377 "qGetTLSAddr", "get-thread-local-storage-address",
12380 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12381 "qGetTIBAddr", "get-thread-information-block-address",
12384 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12385 "bc", "reverse-continue", 0);
12387 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12388 "bs", "reverse-step", 0);
12390 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12391 "qSupported", "supported-packets", 0);
12393 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12394 "qSearch:memory", "search-memory", 0);
12396 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12397 "qTStatus", "trace-status", 0);
12399 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12400 "vFile:open", "hostio-open", 0);
12402 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12403 "vFile:pread", "hostio-pread", 0);
12405 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12406 "vFile:pwrite", "hostio-pwrite", 0);
12408 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12409 "vFile:close", "hostio-close", 0);
12411 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12412 "vFile:unlink", "hostio-unlink", 0);
12414 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12415 "vFile:readlink", "hostio-readlink", 0);
12417 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12418 "vFile:fstat", "hostio-fstat", 0);
12420 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12421 "vAttach", "attach", 0);
12423 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12426 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12427 "QStartNoAckMode", "noack", 0);
12429 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12430 "vKill", "kill", 0);
12432 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12433 "qAttached", "query-attached", 0);
12435 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12436 "ConditionalTracepoints",
12437 "conditional-tracepoints", 0);
12439 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12440 "ConditionalBreakpoints",
12441 "conditional-breakpoints", 0);
12443 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12444 "BreakpointCommands",
12445 "breakpoint-commands", 0);
12447 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12448 "FastTracepoints", "fast-tracepoints", 0);
12450 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12451 "TracepointSource", "TracepointSource", 0);
12453 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12454 "QAllow", "allow", 0);
12456 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12457 "StaticTracepoints", "static-tracepoints", 0);
12459 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12460 "InstallInTrace", "install-in-trace", 0);
12462 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12463 "qXfer:statictrace:read", "read-sdata-object", 0);
12465 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12466 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12468 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12469 "QDisableRandomization", "disable-randomization", 0);
12471 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12472 "QAgent", "agent", 0);
12474 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12475 "QTBuffer:size", "trace-buffer-size", 0);
12477 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12478 "Qbtrace:off", "disable-btrace", 0);
12480 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12481 "Qbtrace:bts", "enable-btrace", 0);
12483 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12484 "qXfer:btrace", "read-btrace", 0);
12486 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12487 "qXfer:btrace-conf", "read-btrace-conf", 0);
12489 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12490 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12492 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12493 "swbreak-feature", "swbreak-feature", 0);
12495 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12496 "hwbreak-feature", "hwbreak-feature", 0);
12498 /* Assert that we've registered "set remote foo-packet" commands
12499 for all packet configs. */
12503 for (i = 0; i < PACKET_MAX; i++)
12505 /* Ideally all configs would have a command associated. Some
12506 still don't though. */
12511 case PACKET_QNonStop:
12512 case PACKET_multiprocess_feature:
12513 case PACKET_EnableDisableTracepoints_feature:
12514 case PACKET_tracenz_feature:
12515 case PACKET_DisconnectedTracing_feature:
12516 case PACKET_augmented_libraries_svr4_read_feature:
12518 /* Additions to this list need to be well justified:
12519 pre-existing packets are OK; new packets are not. */
12527 /* This catches both forgetting to add a config command, and
12528 forgetting to remove a packet from the exception list. */
12529 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12533 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12534 Z sub-packet has its own set and show commands, but users may
12535 have sets to this variable in their .gdbinit files (or in their
12537 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12538 &remote_Z_packet_detect, _("\
12539 Set use of remote protocol `Z' packets"), _("\
12540 Show use of remote protocol `Z' packets "), _("\
12541 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12543 set_remote_protocol_Z_packet_cmd,
12544 show_remote_protocol_Z_packet_cmd,
12545 /* FIXME: i18n: Use of remote protocol
12546 `Z' packets is %s. */
12547 &remote_set_cmdlist, &remote_show_cmdlist);
12549 add_prefix_cmd ("remote", class_files, remote_command, _("\
12550 Manipulate files on the remote system\n\
12551 Transfer files to and from the remote target system."),
12552 &remote_cmdlist, "remote ",
12553 0 /* allow-unknown */, &cmdlist);
12555 add_cmd ("put", class_files, remote_put_command,
12556 _("Copy a local file to the remote system."),
12559 add_cmd ("get", class_files, remote_get_command,
12560 _("Copy a remote file to the local system."),
12563 add_cmd ("delete", class_files, remote_delete_command,
12564 _("Delete a remote file."),
12567 remote_exec_file = xstrdup ("");
12568 add_setshow_string_noescape_cmd ("exec-file", class_files,
12569 &remote_exec_file, _("\
12570 Set the remote pathname for \"run\""), _("\
12571 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12572 &remote_set_cmdlist, &remote_show_cmdlist);
12574 add_setshow_boolean_cmd ("range-stepping", class_run,
12575 &use_range_stepping, _("\
12576 Enable or disable range stepping."), _("\
12577 Show whether target-assisted range stepping is enabled."), _("\
12578 If on, and the target supports it, when stepping a source line, GDB\n\
12579 tells the target to step the corresponding range of addresses itself instead\n\
12580 of issuing multiple single-steps. This speeds up source level\n\
12581 stepping. If off, GDB always issues single-steps, even if range\n\
12582 stepping is supported by the target. The default is on."),
12583 set_range_stepping,
12584 show_range_stepping,
12588 /* Eventually initialize fileio. See fileio.c */
12589 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12591 /* Take advantage of the fact that the TID field is not used, to tag
12592 special ptids with it set to != 0. */
12593 magic_null_ptid = ptid_build (42000, -1, 1);
12594 not_sent_ptid = ptid_build (42000, -2, 1);
12595 any_thread_ptid = ptid_build (42000, 0, 1);
12597 target_buf_size = 2048;
12598 target_buf = xmalloc (target_buf_size);