1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2013 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. */
23 #include "gdb_string.h"
29 #include "exceptions.h"
31 /*#include "terminal.h" */
34 #include "gdb-stabs.h"
35 #include "gdbthread.h"
37 #include "remote-notif.h"
40 #include "gdb_assert.h"
43 #include "cli/cli-decode.h"
44 #include "cli/cli-setshow.h"
45 #include "target-descriptions.h"
47 #include "filestuff.h"
52 #include "event-loop.h"
53 #include "event-top.h"
59 #include "gdbcore.h" /* for exec_bfd */
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
74 /* Temp hacks for tracepoint encoding migration. */
75 static char *target_buf;
76 static long target_buf_size;
78 /* The size to align memory write packets, when practical. The protocol
79 does not guarantee any alignment, and gdb will generate short
80 writes and unaligned writes, but even as a best-effort attempt this
81 can improve bulk transfers. For instance, if a write is misaligned
82 relative to the target's data bus, the stub may need to make an extra
83 round trip fetching data from the target. This doesn't make a
84 huge difference, but it's easy to do, so we try to be helpful.
86 The alignment chosen is arbitrary; usually data bus width is
87 important here, not the possibly larger cache line size. */
88 enum { REMOTE_ALIGN_WRITES = 16 };
90 /* Prototypes for local functions. */
91 static void cleanup_sigint_signal_handler (void *dummy);
92 static void initialize_sigint_signal_handler (void);
93 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
94 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
95 int forever, int *is_notif);
97 static void handle_remote_sigint (int);
98 static void handle_remote_sigint_twice (int);
99 static void async_remote_interrupt (gdb_client_data);
100 static void async_remote_interrupt_twice (gdb_client_data);
102 static void remote_files_info (struct target_ops *ignore);
104 static void remote_prepare_to_store (struct regcache *regcache);
106 static void remote_open (char *name, int from_tty);
108 static void extended_remote_open (char *name, int from_tty);
110 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
112 static void remote_close (void);
114 static void remote_mourn (struct target_ops *ops);
116 static void extended_remote_restart (void);
118 static void extended_remote_mourn (struct target_ops *);
120 static void remote_mourn_1 (struct target_ops *);
122 static void remote_send (char **buf, long *sizeof_buf_p);
124 static int readchar (int timeout);
126 static void remote_serial_write (const char *str, int len);
128 static void remote_kill (struct target_ops *ops);
130 static int tohex (int nib);
132 static int remote_can_async_p (void);
134 static int remote_is_async_p (void);
136 static void remote_async (void (*callback) (enum inferior_event_type event_type,
137 void *context), void *context);
139 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
141 static void remote_interrupt (int signo);
143 static void remote_interrupt_twice (int signo);
145 static void interrupt_query (void);
147 static void set_general_thread (struct ptid ptid);
148 static void set_continue_thread (struct ptid ptid);
150 static void get_offsets (void);
152 static void skip_frame (void);
154 static long read_frame (char **buf_p, long *sizeof_buf);
156 static int hexnumlen (ULONGEST num);
158 static void init_remote_ops (void);
160 static void init_extended_remote_ops (void);
162 static void remote_stop (ptid_t);
164 static int ishex (int ch, int *val);
166 static int stubhex (int ch);
168 static int hexnumstr (char *, ULONGEST);
170 static int hexnumnstr (char *, ULONGEST, int);
172 static CORE_ADDR remote_address_masked (CORE_ADDR);
174 static void print_packet (char *);
176 static void compare_sections_command (char *, int);
178 static void packet_command (char *, int);
180 static int stub_unpack_int (char *buff, int fieldlength);
182 static ptid_t remote_current_thread (ptid_t oldptid);
184 static void remote_find_new_threads (void);
186 static void record_currthread (ptid_t currthread);
188 static int fromhex (int a);
190 static int putpkt_binary (char *buf, int cnt);
192 static void check_binary_download (CORE_ADDR addr);
194 struct packet_config;
196 static void show_packet_config_cmd (struct packet_config *config);
198 static void update_packet_config (struct packet_config *config);
200 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
201 struct cmd_list_element *c);
203 static void show_remote_protocol_packet_cmd (struct ui_file *file,
205 struct cmd_list_element *c,
208 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
209 static ptid_t read_ptid (char *buf, char **obuf);
211 static void remote_set_permissions (void);
214 static int remote_get_trace_status (struct trace_status *ts);
216 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
218 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
220 static void remote_query_supported (void);
222 static void remote_check_symbols (void);
224 void _initialize_remote (void);
227 static void stop_reply_xfree (struct stop_reply *);
228 static void remote_parse_stop_reply (char *, struct stop_reply *);
229 static void push_stop_reply (struct stop_reply *);
230 static void discard_pending_stop_replies (struct inferior *);
231 static int peek_stop_reply (ptid_t ptid);
233 static void remote_async_inferior_event_handler (gdb_client_data);
235 static void remote_terminal_ours (void);
237 static int remote_read_description_p (struct target_ops *target);
239 static void remote_console_output (char *msg);
241 static int remote_supports_cond_breakpoints (void);
243 static int remote_can_run_breakpoint_commands (void);
247 static struct cmd_list_element *remote_cmdlist;
249 /* For "set remote" and "show remote". */
251 static struct cmd_list_element *remote_set_cmdlist;
252 static struct cmd_list_element *remote_show_cmdlist;
254 /* Stub vCont actions support.
256 Each field is a boolean flag indicating whether the stub reports
257 support for the corresponding action. */
259 struct vCont_action_support
268 /* Controls whether GDB is willing to use range stepping. */
270 static int use_range_stepping = 1;
272 /* Description of the remote protocol state for the currently
273 connected target. This is per-target state, and independent of the
274 selected architecture. */
278 /* A buffer to use for incoming packets, and its current size. The
279 buffer is grown dynamically for larger incoming packets.
280 Outgoing packets may also be constructed in this buffer.
281 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
282 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
287 /* True if we're going through initial connection setup (finding out
288 about the remote side's threads, relocating symbols, etc.). */
291 /* If we negotiated packet size explicitly (and thus can bypass
292 heuristics for the largest packet size that will not overflow
293 a buffer in the stub), this will be set to that packet size.
294 Otherwise zero, meaning to use the guessed size. */
295 long explicit_packet_size;
297 /* remote_wait is normally called when the target is running and
298 waits for a stop reply packet. But sometimes we need to call it
299 when the target is already stopped. We can send a "?" packet
300 and have remote_wait read the response. Or, if we already have
301 the response, we can stash it in BUF and tell remote_wait to
302 skip calling getpkt. This flag is set when BUF contains a
303 stop reply packet and the target is not waiting. */
304 int cached_wait_status;
306 /* True, if in no ack mode. That is, neither GDB nor the stub will
307 expect acks from each other. The connection is assumed to be
311 /* True if we're connected in extended remote mode. */
314 /* True if the stub reported support for multi-process
316 int multi_process_aware;
318 /* True if we resumed the target and we're waiting for the target to
319 stop. In the mean time, we can't start another command/query.
320 The remote server wouldn't be ready to process it, so we'd
321 timeout waiting for a reply that would never come and eventually
322 we'd close the connection. This can happen in asynchronous mode
323 because we allow GDB commands while the target is running. */
324 int waiting_for_stop_reply;
326 /* True if the stub reports support for non-stop mode. */
329 /* The status of the stub support for the various vCont actions. */
330 struct vCont_action_support supports_vCont;
332 /* True if the stub reports support for conditional tracepoints. */
333 int cond_tracepoints;
335 /* True if the stub reports support for target-side breakpoint
337 int cond_breakpoints;
339 /* True if the stub reports support for target-side breakpoint
341 int breakpoint_commands;
343 /* True if the stub reports support for fast tracepoints. */
344 int fast_tracepoints;
346 /* True if the stub reports support for static tracepoints. */
347 int static_tracepoints;
349 /* True if the stub reports support for installing tracepoint while
351 int install_in_trace;
353 /* True if the stub can continue running a trace while GDB is
355 int disconnected_tracing;
357 /* True if the stub reports support for enabling and disabling
358 tracepoints while a trace experiment is running. */
359 int enable_disable_tracepoints;
361 /* True if the stub can collect strings using tracenz bytecode. */
364 /* True if the stub supports qXfer:libraries-svr4:read with a
366 int augmented_libraries_svr4_read;
368 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
369 responded to that. */
373 /* Private data that we'll store in (struct thread_info)->private. */
374 struct private_thread_info
381 free_private_thread_info (struct private_thread_info *info)
387 /* Returns true if the multi-process extensions are in effect. */
389 remote_multi_process_p (struct remote_state *rs)
391 return rs->multi_process_aware;
394 /* This data could be associated with a target, but we do not always
395 have access to the current target when we need it, so for now it is
396 static. This will be fine for as long as only one target is in use
398 static struct remote_state remote_state;
400 static struct remote_state *
401 get_remote_state_raw (void)
403 return &remote_state;
406 /* Description of the remote protocol for a given architecture. */
410 long offset; /* Offset into G packet. */
411 long regnum; /* GDB's internal register number. */
412 LONGEST pnum; /* Remote protocol register number. */
413 int in_g_packet; /* Always part of G packet. */
414 /* long size in bytes; == register_size (target_gdbarch (), regnum);
416 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
420 struct remote_arch_state
422 /* Description of the remote protocol registers. */
423 long sizeof_g_packet;
425 /* Description of the remote protocol registers indexed by REGNUM
426 (making an array gdbarch_num_regs in size). */
427 struct packet_reg *regs;
429 /* This is the size (in chars) of the first response to the ``g''
430 packet. It is used as a heuristic when determining the maximum
431 size of memory-read and memory-write packets. A target will
432 typically only reserve a buffer large enough to hold the ``g''
433 packet. The size does not include packet overhead (headers and
435 long actual_register_packet_size;
437 /* This is the maximum size (in chars) of a non read/write packet.
438 It is also used as a cap on the size of read/write packets. */
439 long remote_packet_size;
442 long sizeof_pkt = 2000;
444 /* Utility: generate error from an incoming stub packet. */
446 trace_error (char *buf)
449 return; /* not an error msg */
452 case '1': /* malformed packet error */
453 if (*++buf == '0') /* general case: */
454 error (_("remote.c: error in outgoing packet."));
456 error (_("remote.c: error in outgoing packet at field #%ld."),
457 strtol (buf, NULL, 16));
459 error (_("Target returns error code '%s'."), buf);
463 /* Utility: wait for reply from stub, while accepting "O" packets. */
465 remote_get_noisy_reply (char **buf_p,
468 do /* Loop on reply from remote stub. */
472 QUIT; /* Allow user to bail out with ^C. */
473 getpkt (buf_p, sizeof_buf, 0);
477 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
480 CORE_ADDR from, to, org_to;
482 int adjusted_size = 0;
483 volatile struct gdb_exception ex;
485 p = buf + strlen ("qRelocInsn:");
486 pp = unpack_varlen_hex (p, &ul);
488 error (_("invalid qRelocInsn packet: %s"), buf);
492 unpack_varlen_hex (p, &ul);
497 TRY_CATCH (ex, RETURN_MASK_ALL)
499 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
503 adjusted_size = to - org_to;
505 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
508 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
510 /* Propagate memory errors silently back to the target.
511 The stub may have limited the range of addresses we
512 can write to, for example. */
517 /* Something unexpectedly bad happened. Be verbose so
518 we can tell what, and propagate the error back to the
519 stub, so it doesn't get stuck waiting for a
521 exception_fprintf (gdb_stderr, ex,
522 _("warning: relocating instruction: "));
526 else if (buf[0] == 'O' && buf[1] != 'K')
527 remote_console_output (buf + 1); /* 'O' message from stub */
529 return buf; /* Here's the actual reply. */
534 /* Handle for retreving the remote protocol data from gdbarch. */
535 static struct gdbarch_data *remote_gdbarch_data_handle;
537 static struct remote_arch_state *
538 get_remote_arch_state (void)
540 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
543 /* Fetch the global remote target state. */
545 static struct remote_state *
546 get_remote_state (void)
548 /* Make sure that the remote architecture state has been
549 initialized, because doing so might reallocate rs->buf. Any
550 function which calls getpkt also needs to be mindful of changes
551 to rs->buf, but this call limits the number of places which run
553 get_remote_arch_state ();
555 return get_remote_state_raw ();
559 compare_pnums (const void *lhs_, const void *rhs_)
561 const struct packet_reg * const *lhs = lhs_;
562 const struct packet_reg * const *rhs = rhs_;
564 if ((*lhs)->pnum < (*rhs)->pnum)
566 else if ((*lhs)->pnum == (*rhs)->pnum)
573 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
575 int regnum, num_remote_regs, offset;
576 struct packet_reg **remote_regs;
578 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
580 struct packet_reg *r = ®s[regnum];
582 if (register_size (gdbarch, regnum) == 0)
583 /* Do not try to fetch zero-sized (placeholder) registers. */
586 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
591 /* Define the g/G packet format as the contents of each register
592 with a remote protocol number, in order of ascending protocol
595 remote_regs = alloca (gdbarch_num_regs (gdbarch)
596 * sizeof (struct packet_reg *));
597 for (num_remote_regs = 0, regnum = 0;
598 regnum < gdbarch_num_regs (gdbarch);
600 if (regs[regnum].pnum != -1)
601 remote_regs[num_remote_regs++] = ®s[regnum];
603 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
606 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
608 remote_regs[regnum]->in_g_packet = 1;
609 remote_regs[regnum]->offset = offset;
610 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
616 /* Given the architecture described by GDBARCH, return the remote
617 protocol register's number and the register's offset in the g/G
618 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
619 If the target does not have a mapping for REGNUM, return false,
620 otherwise, return true. */
623 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
624 int *pnum, int *poffset)
627 struct packet_reg *regs;
628 struct cleanup *old_chain;
630 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
632 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
633 old_chain = make_cleanup (xfree, regs);
635 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
637 *pnum = regs[regnum].pnum;
638 *poffset = regs[regnum].offset;
640 do_cleanups (old_chain);
646 init_remote_state (struct gdbarch *gdbarch)
648 struct remote_state *rs = get_remote_state_raw ();
649 struct remote_arch_state *rsa;
651 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
653 /* Use the architecture to build a regnum<->pnum table, which will be
654 1:1 unless a feature set specifies otherwise. */
655 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
656 gdbarch_num_regs (gdbarch),
659 /* Record the maximum possible size of the g packet - it may turn out
661 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
663 /* Default maximum number of characters in a packet body. Many
664 remote stubs have a hardwired buffer size of 400 bytes
665 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
666 as the maximum packet-size to ensure that the packet and an extra
667 NUL character can always fit in the buffer. This stops GDB
668 trashing stubs that try to squeeze an extra NUL into what is
669 already a full buffer (As of 1999-12-04 that was most stubs). */
670 rsa->remote_packet_size = 400 - 1;
672 /* This one is filled in when a ``g'' packet is received. */
673 rsa->actual_register_packet_size = 0;
675 /* Should rsa->sizeof_g_packet needs more space than the
676 default, adjust the size accordingly. Remember that each byte is
677 encoded as two characters. 32 is the overhead for the packet
678 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
679 (``$NN:G...#NN'') is a better guess, the below has been padded a
681 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
682 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
684 /* Make sure that the packet buffer is plenty big enough for
685 this architecture. */
686 if (rs->buf_size < rsa->remote_packet_size)
688 rs->buf_size = 2 * rsa->remote_packet_size;
689 rs->buf = xrealloc (rs->buf, rs->buf_size);
695 /* Return the current allowed size of a remote packet. This is
696 inferred from the current architecture, and should be used to
697 limit the length of outgoing packets. */
699 get_remote_packet_size (void)
701 struct remote_state *rs = get_remote_state ();
702 struct remote_arch_state *rsa = get_remote_arch_state ();
704 if (rs->explicit_packet_size)
705 return rs->explicit_packet_size;
707 return rsa->remote_packet_size;
710 static struct packet_reg *
711 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
713 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
717 struct packet_reg *r = &rsa->regs[regnum];
719 gdb_assert (r->regnum == regnum);
724 static struct packet_reg *
725 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
729 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
731 struct packet_reg *r = &rsa->regs[i];
739 /* FIXME: graces/2002-08-08: These variables should eventually be
740 bound to an instance of the target object (as in gdbarch-tdep()),
741 when such a thing exists. */
743 /* This is set to the data address of the access causing the target
744 to stop for a watchpoint. */
745 static CORE_ADDR remote_watch_data_address;
747 /* This is non-zero if target stopped for a watchpoint. */
748 static int remote_stopped_by_watchpoint_p;
750 static struct target_ops remote_ops;
752 static struct target_ops extended_remote_ops;
754 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
755 ``forever'' still use the normal timeout mechanism. This is
756 currently used by the ASYNC code to guarentee that target reads
757 during the initial connect always time-out. Once getpkt has been
758 modified to return a timeout indication and, in turn
759 remote_wait()/wait_for_inferior() have gained a timeout parameter
761 static int wait_forever_enabled_p = 1;
763 /* Allow the user to specify what sequence to send to the remote
764 when he requests a program interruption: Although ^C is usually
765 what remote systems expect (this is the default, here), it is
766 sometimes preferable to send a break. On other systems such
767 as the Linux kernel, a break followed by g, which is Magic SysRq g
768 is required in order to interrupt the execution. */
769 const char interrupt_sequence_control_c[] = "Ctrl-C";
770 const char interrupt_sequence_break[] = "BREAK";
771 const char interrupt_sequence_break_g[] = "BREAK-g";
772 static const char *const interrupt_sequence_modes[] =
774 interrupt_sequence_control_c,
775 interrupt_sequence_break,
776 interrupt_sequence_break_g,
779 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
782 show_interrupt_sequence (struct ui_file *file, int from_tty,
783 struct cmd_list_element *c,
786 if (interrupt_sequence_mode == interrupt_sequence_control_c)
787 fprintf_filtered (file,
788 _("Send the ASCII ETX character (Ctrl-c) "
789 "to the remote target to interrupt the "
790 "execution of the program.\n"));
791 else if (interrupt_sequence_mode == interrupt_sequence_break)
792 fprintf_filtered (file,
793 _("send a break signal to the remote target "
794 "to interrupt the execution of the program.\n"));
795 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
796 fprintf_filtered (file,
797 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
798 "the remote target to interrupt the execution "
799 "of Linux kernel.\n"));
801 internal_error (__FILE__, __LINE__,
802 _("Invalid value for interrupt_sequence_mode: %s."),
803 interrupt_sequence_mode);
806 /* This boolean variable specifies whether interrupt_sequence is sent
807 to the remote target when gdb connects to it.
808 This is mostly needed when you debug the Linux kernel: The Linux kernel
809 expects BREAK g which is Magic SysRq g for connecting gdb. */
810 static int interrupt_on_connect = 0;
812 /* This variable is used to implement the "set/show remotebreak" commands.
813 Since these commands are now deprecated in favor of "set/show remote
814 interrupt-sequence", it no longer has any effect on the code. */
815 static int remote_break;
818 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
821 interrupt_sequence_mode = interrupt_sequence_break;
823 interrupt_sequence_mode = interrupt_sequence_control_c;
827 show_remotebreak (struct ui_file *file, int from_tty,
828 struct cmd_list_element *c,
833 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
834 remote_open knows that we don't have a file open when the program
836 static struct serial *remote_desc = NULL;
838 /* This variable sets the number of bits in an address that are to be
839 sent in a memory ("M" or "m") packet. Normally, after stripping
840 leading zeros, the entire address would be sent. This variable
841 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
842 initial implementation of remote.c restricted the address sent in
843 memory packets to ``host::sizeof long'' bytes - (typically 32
844 bits). Consequently, for 64 bit targets, the upper 32 bits of an
845 address was never sent. Since fixing this bug may cause a break in
846 some remote targets this variable is principly provided to
847 facilitate backward compatibility. */
849 static unsigned int remote_address_size;
851 /* Temporary to track who currently owns the terminal. See
852 remote_terminal_* for more details. */
854 static int remote_async_terminal_ours_p;
856 /* The executable file to use for "run" on the remote side. */
858 static char *remote_exec_file = "";
861 /* User configurable variables for the number of characters in a
862 memory read/write packet. MIN (rsa->remote_packet_size,
863 rsa->sizeof_g_packet) is the default. Some targets need smaller
864 values (fifo overruns, et.al.) and some users need larger values
865 (speed up transfers). The variables ``preferred_*'' (the user
866 request), ``current_*'' (what was actually set) and ``forced_*''
867 (Positive - a soft limit, negative - a hard limit). */
869 struct memory_packet_config
876 /* Compute the current size of a read/write packet. Since this makes
877 use of ``actual_register_packet_size'' the computation is dynamic. */
880 get_memory_packet_size (struct memory_packet_config *config)
882 struct remote_state *rs = get_remote_state ();
883 struct remote_arch_state *rsa = get_remote_arch_state ();
885 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
886 law?) that some hosts don't cope very well with large alloca()
887 calls. Eventually the alloca() code will be replaced by calls to
888 xmalloc() and make_cleanups() allowing this restriction to either
889 be lifted or removed. */
890 #ifndef MAX_REMOTE_PACKET_SIZE
891 #define MAX_REMOTE_PACKET_SIZE 16384
893 /* NOTE: 20 ensures we can write at least one byte. */
894 #ifndef MIN_REMOTE_PACKET_SIZE
895 #define MIN_REMOTE_PACKET_SIZE 20
900 if (config->size <= 0)
901 what_they_get = MAX_REMOTE_PACKET_SIZE;
903 what_they_get = config->size;
907 what_they_get = get_remote_packet_size ();
908 /* Limit the packet to the size specified by the user. */
910 && what_they_get > config->size)
911 what_they_get = config->size;
913 /* Limit it to the size of the targets ``g'' response unless we have
914 permission from the stub to use a larger packet size. */
915 if (rs->explicit_packet_size == 0
916 && rsa->actual_register_packet_size > 0
917 && what_they_get > rsa->actual_register_packet_size)
918 what_they_get = rsa->actual_register_packet_size;
920 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
921 what_they_get = MAX_REMOTE_PACKET_SIZE;
922 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
923 what_they_get = MIN_REMOTE_PACKET_SIZE;
925 /* Make sure there is room in the global buffer for this packet
926 (including its trailing NUL byte). */
927 if (rs->buf_size < what_they_get + 1)
929 rs->buf_size = 2 * what_they_get;
930 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
933 return what_they_get;
936 /* Update the size of a read/write packet. If they user wants
937 something really big then do a sanity check. */
940 set_memory_packet_size (char *args, struct memory_packet_config *config)
942 int fixed_p = config->fixed_p;
943 long size = config->size;
946 error (_("Argument required (integer, `fixed' or `limited')."));
947 else if (strcmp (args, "hard") == 0
948 || strcmp (args, "fixed") == 0)
950 else if (strcmp (args, "soft") == 0
951 || strcmp (args, "limit") == 0)
957 size = strtoul (args, &end, 0);
959 error (_("Invalid %s (bad syntax)."), config->name);
961 /* Instead of explicitly capping the size of a packet to
962 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
963 instead allowed to set the size to something arbitrarily
965 if (size > MAX_REMOTE_PACKET_SIZE)
966 error (_("Invalid %s (too large)."), config->name);
970 if (fixed_p && !config->fixed_p)
972 if (! query (_("The target may not be able to correctly handle a %s\n"
973 "of %ld bytes. Change the packet size? "),
975 error (_("Packet size not changed."));
977 /* Update the config. */
978 config->fixed_p = fixed_p;
983 show_memory_packet_size (struct memory_packet_config *config)
985 printf_filtered (_("The %s is %ld. "), config->name, config->size);
987 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
988 get_memory_packet_size (config));
990 printf_filtered (_("Packets are limited to %ld bytes.\n"),
991 get_memory_packet_size (config));
994 static struct memory_packet_config memory_write_packet_config =
996 "memory-write-packet-size",
1000 set_memory_write_packet_size (char *args, int from_tty)
1002 set_memory_packet_size (args, &memory_write_packet_config);
1006 show_memory_write_packet_size (char *args, int from_tty)
1008 show_memory_packet_size (&memory_write_packet_config);
1012 get_memory_write_packet_size (void)
1014 return get_memory_packet_size (&memory_write_packet_config);
1017 static struct memory_packet_config memory_read_packet_config =
1019 "memory-read-packet-size",
1023 set_memory_read_packet_size (char *args, int from_tty)
1025 set_memory_packet_size (args, &memory_read_packet_config);
1029 show_memory_read_packet_size (char *args, int from_tty)
1031 show_memory_packet_size (&memory_read_packet_config);
1035 get_memory_read_packet_size (void)
1037 long size = get_memory_packet_size (&memory_read_packet_config);
1039 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1040 extra buffer size argument before the memory read size can be
1041 increased beyond this. */
1042 if (size > get_remote_packet_size ())
1043 size = get_remote_packet_size ();
1048 /* Generic configuration support for packets the stub optionally
1049 supports. Allows the user to specify the use of the packet as well
1050 as allowing GDB to auto-detect support in the remote stub. */
1054 PACKET_SUPPORT_UNKNOWN = 0,
1059 struct packet_config
1063 enum auto_boolean detect;
1064 enum packet_support support;
1067 /* Analyze a packet's return value and update the packet config
1078 update_packet_config (struct packet_config *config)
1080 switch (config->detect)
1082 case AUTO_BOOLEAN_TRUE:
1083 config->support = PACKET_ENABLE;
1085 case AUTO_BOOLEAN_FALSE:
1086 config->support = PACKET_DISABLE;
1088 case AUTO_BOOLEAN_AUTO:
1089 config->support = PACKET_SUPPORT_UNKNOWN;
1095 show_packet_config_cmd (struct packet_config *config)
1097 char *support = "internal-error";
1099 switch (config->support)
1102 support = "enabled";
1104 case PACKET_DISABLE:
1105 support = "disabled";
1107 case PACKET_SUPPORT_UNKNOWN:
1108 support = "unknown";
1111 switch (config->detect)
1113 case AUTO_BOOLEAN_AUTO:
1114 printf_filtered (_("Support for the `%s' packet "
1115 "is auto-detected, currently %s.\n"),
1116 config->name, support);
1118 case AUTO_BOOLEAN_TRUE:
1119 case AUTO_BOOLEAN_FALSE:
1120 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1121 config->name, support);
1127 add_packet_config_cmd (struct packet_config *config, const char *name,
1128 const char *title, int legacy)
1134 config->name = name;
1135 config->title = title;
1136 config->detect = AUTO_BOOLEAN_AUTO;
1137 config->support = PACKET_SUPPORT_UNKNOWN;
1138 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1140 show_doc = xstrprintf ("Show current use of remote "
1141 "protocol `%s' (%s) packet",
1143 /* set/show TITLE-packet {auto,on,off} */
1144 cmd_name = xstrprintf ("%s-packet", title);
1145 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1146 &config->detect, set_doc,
1147 show_doc, NULL, /* help_doc */
1148 set_remote_protocol_packet_cmd,
1149 show_remote_protocol_packet_cmd,
1150 &remote_set_cmdlist, &remote_show_cmdlist);
1151 /* The command code copies the documentation strings. */
1154 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1159 legacy_name = xstrprintf ("%s-packet", name);
1160 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1161 &remote_set_cmdlist);
1162 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1163 &remote_show_cmdlist);
1167 static enum packet_result
1168 packet_check_result (const char *buf)
1172 /* The stub recognized the packet request. Check that the
1173 operation succeeded. */
1175 && isxdigit (buf[1]) && isxdigit (buf[2])
1177 /* "Enn" - definitly an error. */
1178 return PACKET_ERROR;
1180 /* Always treat "E." as an error. This will be used for
1181 more verbose error messages, such as E.memtypes. */
1182 if (buf[0] == 'E' && buf[1] == '.')
1183 return PACKET_ERROR;
1185 /* The packet may or may not be OK. Just assume it is. */
1189 /* The stub does not support the packet. */
1190 return PACKET_UNKNOWN;
1193 static enum packet_result
1194 packet_ok (const char *buf, struct packet_config *config)
1196 enum packet_result result;
1198 result = packet_check_result (buf);
1203 /* The stub recognized the packet request. */
1204 switch (config->support)
1206 case PACKET_SUPPORT_UNKNOWN:
1208 fprintf_unfiltered (gdb_stdlog,
1209 "Packet %s (%s) is supported\n",
1210 config->name, config->title);
1211 config->support = PACKET_ENABLE;
1213 case PACKET_DISABLE:
1214 internal_error (__FILE__, __LINE__,
1215 _("packet_ok: attempt to use a disabled packet"));
1221 case PACKET_UNKNOWN:
1222 /* The stub does not support the packet. */
1223 switch (config->support)
1226 if (config->detect == AUTO_BOOLEAN_AUTO)
1227 /* If the stub previously indicated that the packet was
1228 supported then there is a protocol error.. */
1229 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1230 config->name, config->title);
1232 /* The user set it wrong. */
1233 error (_("Enabled packet %s (%s) not recognized by stub"),
1234 config->name, config->title);
1236 case PACKET_SUPPORT_UNKNOWN:
1238 fprintf_unfiltered (gdb_stdlog,
1239 "Packet %s (%s) is NOT supported\n",
1240 config->name, config->title);
1241 config->support = PACKET_DISABLE;
1243 case PACKET_DISABLE:
1265 PACKET_vFile_pwrite,
1267 PACKET_vFile_unlink,
1268 PACKET_vFile_readlink,
1270 PACKET_qXfer_features,
1271 PACKET_qXfer_libraries,
1272 PACKET_qXfer_libraries_svr4,
1273 PACKET_qXfer_memory_map,
1274 PACKET_qXfer_spu_read,
1275 PACKET_qXfer_spu_write,
1276 PACKET_qXfer_osdata,
1277 PACKET_qXfer_threads,
1278 PACKET_qXfer_statictrace_read,
1279 PACKET_qXfer_traceframe_info,
1285 PACKET_QPassSignals,
1286 PACKET_QProgramSignals,
1287 PACKET_qSearch_memory,
1290 PACKET_QStartNoAckMode,
1292 PACKET_qXfer_siginfo_read,
1293 PACKET_qXfer_siginfo_write,
1295 PACKET_ConditionalTracepoints,
1296 PACKET_ConditionalBreakpoints,
1297 PACKET_BreakpointCommands,
1298 PACKET_FastTracepoints,
1299 PACKET_StaticTracepoints,
1300 PACKET_InstallInTrace,
1303 PACKET_TracepointSource,
1306 PACKET_QDisableRandomization,
1308 PACKET_QTBuffer_size,
1311 PACKET_qXfer_btrace,
1315 static struct packet_config remote_protocol_packets[PACKET_MAX];
1318 set_remote_protocol_packet_cmd (char *args, int from_tty,
1319 struct cmd_list_element *c)
1321 struct packet_config *packet;
1323 for (packet = remote_protocol_packets;
1324 packet < &remote_protocol_packets[PACKET_MAX];
1327 if (&packet->detect == c->var)
1329 update_packet_config (packet);
1333 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1338 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1339 struct cmd_list_element *c,
1342 struct packet_config *packet;
1344 for (packet = remote_protocol_packets;
1345 packet < &remote_protocol_packets[PACKET_MAX];
1348 if (&packet->detect == c->var)
1350 show_packet_config_cmd (packet);
1354 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1358 /* Should we try one of the 'Z' requests? */
1362 Z_PACKET_SOFTWARE_BP,
1363 Z_PACKET_HARDWARE_BP,
1370 /* For compatibility with older distributions. Provide a ``set remote
1371 Z-packet ...'' command that updates all the Z packet types. */
1373 static enum auto_boolean remote_Z_packet_detect;
1376 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1377 struct cmd_list_element *c)
1381 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1383 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1384 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1389 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1390 struct cmd_list_element *c,
1395 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1397 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1401 /* Should we try the 'ThreadInfo' query packet?
1403 This variable (NOT available to the user: auto-detect only!)
1404 determines whether GDB will use the new, simpler "ThreadInfo"
1405 query or the older, more complex syntax for thread queries.
1406 This is an auto-detect variable (set to true at each connect,
1407 and set to false when the target fails to recognize it). */
1409 static int use_threadinfo_query;
1410 static int use_threadextra_query;
1412 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1413 static struct async_signal_handler *sigint_remote_twice_token;
1414 static struct async_signal_handler *sigint_remote_token;
1417 /* Asynchronous signal handle registered as event loop source for
1418 when we have pending events ready to be passed to the core. */
1420 static struct async_event_handler *remote_async_inferior_event_token;
1424 static ptid_t magic_null_ptid;
1425 static ptid_t not_sent_ptid;
1426 static ptid_t any_thread_ptid;
1428 /* These are the threads which we last sent to the remote system. The
1429 TID member will be -1 for all or -2 for not sent yet. */
1431 static ptid_t general_thread;
1432 static ptid_t continue_thread;
1434 /* This is the traceframe which we last selected on the remote system.
1435 It will be -1 if no traceframe is selected. */
1436 static int remote_traceframe_number = -1;
1438 /* Find out if the stub attached to PID (and hence GDB should offer to
1439 detach instead of killing it when bailing out). */
1442 remote_query_attached (int pid)
1444 struct remote_state *rs = get_remote_state ();
1445 size_t size = get_remote_packet_size ();
1447 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1450 if (remote_multi_process_p (rs))
1451 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1453 xsnprintf (rs->buf, size, "qAttached");
1456 getpkt (&rs->buf, &rs->buf_size, 0);
1458 switch (packet_ok (rs->buf,
1459 &remote_protocol_packets[PACKET_qAttached]))
1462 if (strcmp (rs->buf, "1") == 0)
1466 warning (_("Remote failure reply: %s"), rs->buf);
1468 case PACKET_UNKNOWN:
1475 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1476 has been invented by GDB, instead of reported by the target. Since
1477 we can be connected to a remote system before before knowing about
1478 any inferior, mark the target with execution when we find the first
1479 inferior. If ATTACHED is 1, then we had just attached to this
1480 inferior. If it is 0, then we just created this inferior. If it
1481 is -1, then try querying the remote stub to find out if it had
1482 attached to the inferior or not. */
1484 static struct inferior *
1485 remote_add_inferior (int fake_pid_p, int pid, int attached)
1487 struct inferior *inf;
1489 /* Check whether this process we're learning about is to be
1490 considered attached, or if is to be considered to have been
1491 spawned by the stub. */
1493 attached = remote_query_attached (pid);
1495 if (gdbarch_has_global_solist (target_gdbarch ()))
1497 /* If the target shares code across all inferiors, then every
1498 attach adds a new inferior. */
1499 inf = add_inferior (pid);
1501 /* ... and every inferior is bound to the same program space.
1502 However, each inferior may still have its own address
1504 inf->aspace = maybe_new_address_space ();
1505 inf->pspace = current_program_space;
1509 /* In the traditional debugging scenario, there's a 1-1 match
1510 between program/address spaces. We simply bind the inferior
1511 to the program space's address space. */
1512 inf = current_inferior ();
1513 inferior_appeared (inf, pid);
1516 inf->attach_flag = attached;
1517 inf->fake_pid_p = fake_pid_p;
1522 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1523 according to RUNNING. */
1526 remote_add_thread (ptid_t ptid, int running)
1530 set_executing (ptid, running);
1531 set_running (ptid, running);
1534 /* Come here when we learn about a thread id from the remote target.
1535 It may be the first time we hear about such thread, so take the
1536 opportunity to add it to GDB's thread list. In case this is the
1537 first time we're noticing its corresponding inferior, add it to
1538 GDB's inferior list as well. */
1541 remote_notice_new_inferior (ptid_t currthread, int running)
1543 /* If this is a new thread, add it to GDB's thread list.
1544 If we leave it up to WFI to do this, bad things will happen. */
1546 if (in_thread_list (currthread) && is_exited (currthread))
1548 /* We're seeing an event on a thread id we knew had exited.
1549 This has to be a new thread reusing the old id. Add it. */
1550 remote_add_thread (currthread, running);
1554 if (!in_thread_list (currthread))
1556 struct inferior *inf = NULL;
1557 int pid = ptid_get_pid (currthread);
1559 if (ptid_is_pid (inferior_ptid)
1560 && pid == ptid_get_pid (inferior_ptid))
1562 /* inferior_ptid has no thread member yet. This can happen
1563 with the vAttach -> remote_wait,"TAAthread:" path if the
1564 stub doesn't support qC. This is the first stop reported
1565 after an attach, so this is the main thread. Update the
1566 ptid in the thread list. */
1567 if (in_thread_list (pid_to_ptid (pid)))
1568 thread_change_ptid (inferior_ptid, currthread);
1571 remote_add_thread (currthread, running);
1572 inferior_ptid = currthread;
1577 if (ptid_equal (magic_null_ptid, inferior_ptid))
1579 /* inferior_ptid is not set yet. This can happen with the
1580 vRun -> remote_wait,"TAAthread:" path if the stub
1581 doesn't support qC. This is the first stop reported
1582 after an attach, so this is the main thread. Update the
1583 ptid in the thread list. */
1584 thread_change_ptid (inferior_ptid, currthread);
1588 /* When connecting to a target remote, or to a target
1589 extended-remote which already was debugging an inferior, we
1590 may not know about it yet. Add it before adding its child
1591 thread, so notifications are emitted in a sensible order. */
1592 if (!in_inferior_list (ptid_get_pid (currthread)))
1594 struct remote_state *rs = get_remote_state ();
1595 int fake_pid_p = !remote_multi_process_p (rs);
1597 inf = remote_add_inferior (fake_pid_p,
1598 ptid_get_pid (currthread), -1);
1601 /* This is really a new thread. Add it. */
1602 remote_add_thread (currthread, running);
1604 /* If we found a new inferior, let the common code do whatever
1605 it needs to with it (e.g., read shared libraries, insert
1608 notice_new_inferior (currthread, running, 0);
1612 /* Return the private thread data, creating it if necessary. */
1614 static struct private_thread_info *
1615 demand_private_info (ptid_t ptid)
1617 struct thread_info *info = find_thread_ptid (ptid);
1623 info->private = xmalloc (sizeof (*(info->private)));
1624 info->private_dtor = free_private_thread_info;
1625 info->private->core = -1;
1626 info->private->extra = 0;
1629 return info->private;
1632 /* Call this function as a result of
1633 1) A halt indication (T packet) containing a thread id
1634 2) A direct query of currthread
1635 3) Successful execution of set thread */
1638 record_currthread (ptid_t currthread)
1640 general_thread = currthread;
1643 static char *last_pass_packet;
1645 /* If 'QPassSignals' is supported, tell the remote stub what signals
1646 it can simply pass through to the inferior without reporting. */
1649 remote_pass_signals (int numsigs, unsigned char *pass_signals)
1651 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1653 char *pass_packet, *p;
1656 gdb_assert (numsigs < 256);
1657 for (i = 0; i < numsigs; i++)
1659 if (pass_signals[i])
1662 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1663 strcpy (pass_packet, "QPassSignals:");
1664 p = pass_packet + strlen (pass_packet);
1665 for (i = 0; i < numsigs; i++)
1667 if (pass_signals[i])
1670 *p++ = tohex (i >> 4);
1671 *p++ = tohex (i & 15);
1680 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1682 struct remote_state *rs = get_remote_state ();
1683 char *buf = rs->buf;
1685 putpkt (pass_packet);
1686 getpkt (&rs->buf, &rs->buf_size, 0);
1687 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1688 if (last_pass_packet)
1689 xfree (last_pass_packet);
1690 last_pass_packet = pass_packet;
1693 xfree (pass_packet);
1697 /* The last QProgramSignals packet sent to the target. We bypass
1698 sending a new program signals list down to the target if the new
1699 packet is exactly the same as the last we sent. IOW, we only let
1700 the target know about program signals list changes. */
1702 static char *last_program_signals_packet;
1704 /* If 'QProgramSignals' is supported, tell the remote stub what
1705 signals it should pass through to the inferior when detaching. */
1708 remote_program_signals (int numsigs, unsigned char *signals)
1710 if (remote_protocol_packets[PACKET_QProgramSignals].support != PACKET_DISABLE)
1715 gdb_assert (numsigs < 256);
1716 for (i = 0; i < numsigs; i++)
1721 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1722 strcpy (packet, "QProgramSignals:");
1723 p = packet + strlen (packet);
1724 for (i = 0; i < numsigs; i++)
1726 if (signal_pass_state (i))
1729 *p++ = tohex (i >> 4);
1730 *p++ = tohex (i & 15);
1739 if (!last_program_signals_packet
1740 || strcmp (last_program_signals_packet, packet) != 0)
1742 struct remote_state *rs = get_remote_state ();
1743 char *buf = rs->buf;
1746 getpkt (&rs->buf, &rs->buf_size, 0);
1747 packet_ok (buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1748 xfree (last_program_signals_packet);
1749 last_program_signals_packet = packet;
1756 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1757 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1758 thread. If GEN is set, set the general thread, if not, then set
1759 the step/continue thread. */
1761 set_thread (struct ptid ptid, int gen)
1763 struct remote_state *rs = get_remote_state ();
1764 ptid_t state = gen ? general_thread : continue_thread;
1765 char *buf = rs->buf;
1766 char *endbuf = rs->buf + get_remote_packet_size ();
1768 if (ptid_equal (state, ptid))
1772 *buf++ = gen ? 'g' : 'c';
1773 if (ptid_equal (ptid, magic_null_ptid))
1774 xsnprintf (buf, endbuf - buf, "0");
1775 else if (ptid_equal (ptid, any_thread_ptid))
1776 xsnprintf (buf, endbuf - buf, "0");
1777 else if (ptid_equal (ptid, minus_one_ptid))
1778 xsnprintf (buf, endbuf - buf, "-1");
1780 write_ptid (buf, endbuf, ptid);
1782 getpkt (&rs->buf, &rs->buf_size, 0);
1784 general_thread = ptid;
1786 continue_thread = ptid;
1790 set_general_thread (struct ptid ptid)
1792 set_thread (ptid, 1);
1796 set_continue_thread (struct ptid ptid)
1798 set_thread (ptid, 0);
1801 /* Change the remote current process. Which thread within the process
1802 ends up selected isn't important, as long as it is the same process
1803 as what INFERIOR_PTID points to.
1805 This comes from that fact that there is no explicit notion of
1806 "selected process" in the protocol. The selected process for
1807 general operations is the process the selected general thread
1811 set_general_process (void)
1813 struct remote_state *rs = get_remote_state ();
1815 /* If the remote can't handle multiple processes, don't bother. */
1816 if (!rs->extended || !remote_multi_process_p (rs))
1819 /* We only need to change the remote current thread if it's pointing
1820 at some other process. */
1821 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1822 set_general_thread (inferior_ptid);
1826 /* Return nonzero if the thread PTID is still alive on the remote
1830 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1832 struct remote_state *rs = get_remote_state ();
1835 if (ptid_equal (ptid, magic_null_ptid))
1836 /* The main thread is always alive. */
1839 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1840 /* The main thread is always alive. This can happen after a
1841 vAttach, if the remote side doesn't support
1846 endp = rs->buf + get_remote_packet_size ();
1849 write_ptid (p, endp, ptid);
1852 getpkt (&rs->buf, &rs->buf_size, 0);
1853 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1856 /* About these extended threadlist and threadinfo packets. They are
1857 variable length packets but, the fields within them are often fixed
1858 length. They are redundent enough to send over UDP as is the
1859 remote protocol in general. There is a matching unit test module
1862 #define OPAQUETHREADBYTES 8
1864 /* a 64 bit opaque identifier */
1865 typedef unsigned char threadref[OPAQUETHREADBYTES];
1867 /* WARNING: This threadref data structure comes from the remote O.S.,
1868 libstub protocol encoding, and remote.c. It is not particularly
1871 /* Right now, the internal structure is int. We want it to be bigger.
1872 Plan to fix this. */
1874 typedef int gdb_threadref; /* Internal GDB thread reference. */
1876 /* gdb_ext_thread_info is an internal GDB data structure which is
1877 equivalent to the reply of the remote threadinfo packet. */
1879 struct gdb_ext_thread_info
1881 threadref threadid; /* External form of thread reference. */
1882 int active; /* Has state interesting to GDB?
1884 char display[256]; /* Brief state display, name,
1885 blocked/suspended. */
1886 char shortname[32]; /* To be used to name threads. */
1887 char more_display[256]; /* Long info, statistics, queue depth,
1891 /* The volume of remote transfers can be limited by submitting
1892 a mask containing bits specifying the desired information.
1893 Use a union of these values as the 'selection' parameter to
1894 get_thread_info. FIXME: Make these TAG names more thread specific. */
1896 #define TAG_THREADID 1
1897 #define TAG_EXISTS 2
1898 #define TAG_DISPLAY 4
1899 #define TAG_THREADNAME 8
1900 #define TAG_MOREDISPLAY 16
1902 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1904 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1906 static char *unpack_nibble (char *buf, int *val);
1908 static char *pack_nibble (char *buf, int nibble);
1910 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1912 static char *unpack_byte (char *buf, int *value);
1914 static char *pack_int (char *buf, int value);
1916 static char *unpack_int (char *buf, int *value);
1918 static char *unpack_string (char *src, char *dest, int length);
1920 static char *pack_threadid (char *pkt, threadref *id);
1922 static char *unpack_threadid (char *inbuf, threadref *id);
1924 void int_to_threadref (threadref *id, int value);
1926 static int threadref_to_int (threadref *ref);
1928 static void copy_threadref (threadref *dest, threadref *src);
1930 static int threadmatch (threadref *dest, threadref *src);
1932 static char *pack_threadinfo_request (char *pkt, int mode,
1935 static int remote_unpack_thread_info_response (char *pkt,
1936 threadref *expectedref,
1937 struct gdb_ext_thread_info
1941 static int remote_get_threadinfo (threadref *threadid,
1942 int fieldset, /*TAG mask */
1943 struct gdb_ext_thread_info *info);
1945 static char *pack_threadlist_request (char *pkt, int startflag,
1947 threadref *nextthread);
1949 static int parse_threadlist_response (char *pkt,
1951 threadref *original_echo,
1952 threadref *resultlist,
1955 static int remote_get_threadlist (int startflag,
1956 threadref *nextthread,
1960 threadref *threadlist);
1962 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1964 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1965 void *context, int looplimit);
1967 static int remote_newthread_step (threadref *ref, void *context);
1970 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1971 buffer we're allowed to write to. Returns
1972 BUF+CHARACTERS_WRITTEN. */
1975 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1978 struct remote_state *rs = get_remote_state ();
1980 if (remote_multi_process_p (rs))
1982 pid = ptid_get_pid (ptid);
1984 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1986 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1988 tid = ptid_get_tid (ptid);
1990 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1992 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1997 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1998 passed the last parsed char. Returns null_ptid on error. */
2001 read_ptid (char *buf, char **obuf)
2005 ULONGEST pid = 0, tid = 0;
2009 /* Multi-process ptid. */
2010 pp = unpack_varlen_hex (p + 1, &pid);
2012 error (_("invalid remote ptid: %s"), p);
2015 pp = unpack_varlen_hex (p + 1, &tid);
2018 return ptid_build (pid, 0, tid);
2021 /* No multi-process. Just a tid. */
2022 pp = unpack_varlen_hex (p, &tid);
2024 /* Since the stub is not sending a process id, then default to
2025 what's in inferior_ptid, unless it's null at this point. If so,
2026 then since there's no way to know the pid of the reported
2027 threads, use the magic number. */
2028 if (ptid_equal (inferior_ptid, null_ptid))
2029 pid = ptid_get_pid (magic_null_ptid);
2031 pid = ptid_get_pid (inferior_ptid);
2035 return ptid_build (pid, 0, tid);
2038 /* Encode 64 bits in 16 chars of hex. */
2040 static const char hexchars[] = "0123456789abcdef";
2043 ishex (int ch, int *val)
2045 if ((ch >= 'a') && (ch <= 'f'))
2047 *val = ch - 'a' + 10;
2050 if ((ch >= 'A') && (ch <= 'F'))
2052 *val = ch - 'A' + 10;
2055 if ((ch >= '0') && (ch <= '9'))
2066 if (ch >= 'a' && ch <= 'f')
2067 return ch - 'a' + 10;
2068 if (ch >= '0' && ch <= '9')
2070 if (ch >= 'A' && ch <= 'F')
2071 return ch - 'A' + 10;
2076 stub_unpack_int (char *buff, int fieldlength)
2083 nibble = stubhex (*buff++);
2087 retval = retval << 4;
2093 unpack_varlen_hex (char *buff, /* packet to parse */
2097 ULONGEST retval = 0;
2099 while (ishex (*buff, &nibble))
2102 retval = retval << 4;
2103 retval |= nibble & 0x0f;
2110 unpack_nibble (char *buf, int *val)
2112 *val = fromhex (*buf++);
2117 pack_nibble (char *buf, int nibble)
2119 *buf++ = hexchars[(nibble & 0x0f)];
2124 pack_hex_byte (char *pkt, int byte)
2126 *pkt++ = hexchars[(byte >> 4) & 0xf];
2127 *pkt++ = hexchars[(byte & 0xf)];
2132 unpack_byte (char *buf, int *value)
2134 *value = stub_unpack_int (buf, 2);
2139 pack_int (char *buf, int value)
2141 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2142 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2143 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2144 buf = pack_hex_byte (buf, (value & 0xff));
2149 unpack_int (char *buf, int *value)
2151 *value = stub_unpack_int (buf, 8);
2155 #if 0 /* Currently unused, uncomment when needed. */
2156 static char *pack_string (char *pkt, char *string);
2159 pack_string (char *pkt, char *string)
2164 len = strlen (string);
2166 len = 200; /* Bigger than most GDB packets, junk??? */
2167 pkt = pack_hex_byte (pkt, len);
2171 if ((ch == '\0') || (ch == '#'))
2172 ch = '*'; /* Protect encapsulation. */
2177 #endif /* 0 (unused) */
2180 unpack_string (char *src, char *dest, int length)
2189 pack_threadid (char *pkt, threadref *id)
2192 unsigned char *altid;
2194 altid = (unsigned char *) id;
2195 limit = pkt + BUF_THREAD_ID_SIZE;
2197 pkt = pack_hex_byte (pkt, *altid++);
2203 unpack_threadid (char *inbuf, threadref *id)
2206 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2209 altref = (char *) id;
2211 while (inbuf < limit)
2213 x = stubhex (*inbuf++);
2214 y = stubhex (*inbuf++);
2215 *altref++ = (x << 4) | y;
2220 /* Externally, threadrefs are 64 bits but internally, they are still
2221 ints. This is due to a mismatch of specifications. We would like
2222 to use 64bit thread references internally. This is an adapter
2226 int_to_threadref (threadref *id, int value)
2228 unsigned char *scan;
2230 scan = (unsigned char *) id;
2236 *scan++ = (value >> 24) & 0xff;
2237 *scan++ = (value >> 16) & 0xff;
2238 *scan++ = (value >> 8) & 0xff;
2239 *scan++ = (value & 0xff);
2243 threadref_to_int (threadref *ref)
2246 unsigned char *scan;
2252 value = (value << 8) | ((*scan++) & 0xff);
2257 copy_threadref (threadref *dest, threadref *src)
2260 unsigned char *csrc, *cdest;
2262 csrc = (unsigned char *) src;
2263 cdest = (unsigned char *) dest;
2270 threadmatch (threadref *dest, threadref *src)
2272 /* Things are broken right now, so just assume we got a match. */
2274 unsigned char *srcp, *destp;
2276 srcp = (char *) src;
2277 destp = (char *) dest;
2281 result &= (*srcp++ == *destp++) ? 1 : 0;
2288 threadid:1, # always request threadid
2295 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2298 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2300 *pkt++ = 'q'; /* Info Query */
2301 *pkt++ = 'P'; /* process or thread info */
2302 pkt = pack_int (pkt, mode); /* mode */
2303 pkt = pack_threadid (pkt, id); /* threadid */
2304 *pkt = '\0'; /* terminate */
2308 /* These values tag the fields in a thread info response packet. */
2309 /* Tagging the fields allows us to request specific fields and to
2310 add more fields as time goes by. */
2312 #define TAG_THREADID 1 /* Echo the thread identifier. */
2313 #define TAG_EXISTS 2 /* Is this process defined enough to
2314 fetch registers and its stack? */
2315 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2316 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2317 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2321 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2322 struct gdb_ext_thread_info *info)
2324 struct remote_state *rs = get_remote_state ();
2328 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2331 /* info->threadid = 0; FIXME: implement zero_threadref. */
2333 info->display[0] = '\0';
2334 info->shortname[0] = '\0';
2335 info->more_display[0] = '\0';
2337 /* Assume the characters indicating the packet type have been
2339 pkt = unpack_int (pkt, &mask); /* arg mask */
2340 pkt = unpack_threadid (pkt, &ref);
2343 warning (_("Incomplete response to threadinfo request."));
2344 if (!threadmatch (&ref, expectedref))
2345 { /* This is an answer to a different request. */
2346 warning (_("ERROR RMT Thread info mismatch."));
2349 copy_threadref (&info->threadid, &ref);
2351 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2353 /* Packets are terminated with nulls. */
2354 while ((pkt < limit) && mask && *pkt)
2356 pkt = unpack_int (pkt, &tag); /* tag */
2357 pkt = unpack_byte (pkt, &length); /* length */
2358 if (!(tag & mask)) /* Tags out of synch with mask. */
2360 warning (_("ERROR RMT: threadinfo tag mismatch."));
2364 if (tag == TAG_THREADID)
2368 warning (_("ERROR RMT: length of threadid is not 16."));
2372 pkt = unpack_threadid (pkt, &ref);
2373 mask = mask & ~TAG_THREADID;
2376 if (tag == TAG_EXISTS)
2378 info->active = stub_unpack_int (pkt, length);
2380 mask = mask & ~(TAG_EXISTS);
2383 warning (_("ERROR RMT: 'exists' length too long."));
2389 if (tag == TAG_THREADNAME)
2391 pkt = unpack_string (pkt, &info->shortname[0], length);
2392 mask = mask & ~TAG_THREADNAME;
2395 if (tag == TAG_DISPLAY)
2397 pkt = unpack_string (pkt, &info->display[0], length);
2398 mask = mask & ~TAG_DISPLAY;
2401 if (tag == TAG_MOREDISPLAY)
2403 pkt = unpack_string (pkt, &info->more_display[0], length);
2404 mask = mask & ~TAG_MOREDISPLAY;
2407 warning (_("ERROR RMT: unknown thread info tag."));
2408 break; /* Not a tag we know about. */
2414 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2415 struct gdb_ext_thread_info *info)
2417 struct remote_state *rs = get_remote_state ();
2420 pack_threadinfo_request (rs->buf, fieldset, threadid);
2422 getpkt (&rs->buf, &rs->buf_size, 0);
2424 if (rs->buf[0] == '\0')
2427 result = remote_unpack_thread_info_response (rs->buf + 2,
2432 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2435 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2436 threadref *nextthread)
2438 *pkt++ = 'q'; /* info query packet */
2439 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2440 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2441 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2442 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2447 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2450 parse_threadlist_response (char *pkt, int result_limit,
2451 threadref *original_echo, threadref *resultlist,
2454 struct remote_state *rs = get_remote_state ();
2456 int count, resultcount, done;
2459 /* Assume the 'q' and 'M chars have been stripped. */
2460 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2461 /* done parse past here */
2462 pkt = unpack_byte (pkt, &count); /* count field */
2463 pkt = unpack_nibble (pkt, &done);
2464 /* The first threadid is the argument threadid. */
2465 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2466 while ((count-- > 0) && (pkt < limit))
2468 pkt = unpack_threadid (pkt, resultlist++);
2469 if (resultcount++ >= result_limit)
2478 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2479 int *done, int *result_count, threadref *threadlist)
2481 struct remote_state *rs = get_remote_state ();
2482 static threadref echo_nextthread;
2485 /* Trancate result limit to be smaller than the packet size. */
2486 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2487 >= get_remote_packet_size ())
2488 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2490 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2492 getpkt (&rs->buf, &rs->buf_size, 0);
2494 if (*rs->buf == '\0')
2498 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2501 if (!threadmatch (&echo_nextthread, nextthread))
2503 /* FIXME: This is a good reason to drop the packet. */
2504 /* Possably, there is a duplicate response. */
2506 retransmit immediatly - race conditions
2507 retransmit after timeout - yes
2509 wait for packet, then exit
2511 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2512 return 0; /* I choose simply exiting. */
2514 if (*result_count <= 0)
2518 warning (_("RMT ERROR : failed to get remote thread list."));
2521 return result; /* break; */
2523 if (*result_count > result_limit)
2526 warning (_("RMT ERROR: threadlist response longer than requested."));
2532 /* This is the interface between remote and threads, remotes upper
2535 /* remote_find_new_threads retrieves the thread list and for each
2536 thread in the list, looks up the thread in GDB's internal list,
2537 adding the thread if it does not already exist. This involves
2538 getting partial thread lists from the remote target so, polling the
2539 quit_flag is required. */
2542 /* About this many threadisds fit in a packet. */
2544 #define MAXTHREADLISTRESULTS 32
2547 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2550 int done, i, result_count;
2554 static threadref nextthread;
2555 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2560 if (loopcount++ > looplimit)
2563 warning (_("Remote fetch threadlist -infinite loop-."));
2566 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2567 &done, &result_count, resultthreadlist))
2572 /* Clear for later iterations. */
2574 /* Setup to resume next batch of thread references, set nextthread. */
2575 if (result_count >= 1)
2576 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2578 while (result_count--)
2579 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2586 remote_newthread_step (threadref *ref, void *context)
2588 int pid = ptid_get_pid (inferior_ptid);
2589 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2591 if (!in_thread_list (ptid))
2593 return 1; /* continue iterator */
2596 #define CRAZY_MAX_THREADS 1000
2599 remote_current_thread (ptid_t oldpid)
2601 struct remote_state *rs = get_remote_state ();
2604 getpkt (&rs->buf, &rs->buf_size, 0);
2605 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2606 return read_ptid (&rs->buf[2], NULL);
2611 /* Find new threads for info threads command.
2612 * Original version, using John Metzler's thread protocol.
2616 remote_find_new_threads (void)
2618 remote_threadlist_iterator (remote_newthread_step, 0,
2622 #if defined(HAVE_LIBEXPAT)
2624 typedef struct thread_item
2630 DEF_VEC_O(thread_item_t);
2632 struct threads_parsing_context
2634 VEC (thread_item_t) *items;
2638 start_thread (struct gdb_xml_parser *parser,
2639 const struct gdb_xml_element *element,
2640 void *user_data, VEC(gdb_xml_value_s) *attributes)
2642 struct threads_parsing_context *data = user_data;
2644 struct thread_item item;
2646 struct gdb_xml_value *attr;
2648 id = xml_find_attribute (attributes, "id")->value;
2649 item.ptid = read_ptid (id, NULL);
2651 attr = xml_find_attribute (attributes, "core");
2653 item.core = *(ULONGEST *) attr->value;
2659 VEC_safe_push (thread_item_t, data->items, &item);
2663 end_thread (struct gdb_xml_parser *parser,
2664 const struct gdb_xml_element *element,
2665 void *user_data, const char *body_text)
2667 struct threads_parsing_context *data = user_data;
2669 if (body_text && *body_text)
2670 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2673 const struct gdb_xml_attribute thread_attributes[] = {
2674 { "id", GDB_XML_AF_NONE, NULL, NULL },
2675 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2676 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2679 const struct gdb_xml_element thread_children[] = {
2680 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2683 const struct gdb_xml_element threads_children[] = {
2684 { "thread", thread_attributes, thread_children,
2685 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2686 start_thread, end_thread },
2687 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2690 const struct gdb_xml_element threads_elements[] = {
2691 { "threads", NULL, threads_children,
2692 GDB_XML_EF_NONE, NULL, NULL },
2693 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2696 /* Discard the contents of the constructed thread info context. */
2699 clear_threads_parsing_context (void *p)
2701 struct threads_parsing_context *context = p;
2703 struct thread_item *item;
2705 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2706 xfree (item->extra);
2708 VEC_free (thread_item_t, context->items);
2714 * Find all threads for info threads command.
2715 * Uses new thread protocol contributed by Cisco.
2716 * Falls back and attempts to use the older method (above)
2717 * if the target doesn't respond to the new method.
2721 remote_threads_info (struct target_ops *ops)
2723 struct remote_state *rs = get_remote_state ();
2727 if (remote_desc == 0) /* paranoia */
2728 error (_("Command can only be used when connected to the remote target."));
2730 #if defined(HAVE_LIBEXPAT)
2731 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2733 char *xml = target_read_stralloc (¤t_target,
2734 TARGET_OBJECT_THREADS, NULL);
2736 struct cleanup *back_to = make_cleanup (xfree, xml);
2740 struct threads_parsing_context context;
2742 context.items = NULL;
2743 make_cleanup (clear_threads_parsing_context, &context);
2745 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2746 threads_elements, xml, &context) == 0)
2749 struct thread_item *item;
2752 VEC_iterate (thread_item_t, context.items, i, item);
2755 if (!ptid_equal (item->ptid, null_ptid))
2757 struct private_thread_info *info;
2758 /* In non-stop mode, we assume new found threads
2759 are running until proven otherwise with a
2760 stop reply. In all-stop, we can only get
2761 here if all threads are stopped. */
2762 int running = non_stop ? 1 : 0;
2764 remote_notice_new_inferior (item->ptid, running);
2766 info = demand_private_info (item->ptid);
2767 info->core = item->core;
2768 info->extra = item->extra;
2775 do_cleanups (back_to);
2780 if (use_threadinfo_query)
2782 putpkt ("qfThreadInfo");
2783 getpkt (&rs->buf, &rs->buf_size, 0);
2785 if (bufp[0] != '\0') /* q packet recognized */
2787 struct cleanup *old_chain;
2790 /* remote_notice_new_inferior (in the loop below) may make
2791 new RSP calls, which clobber rs->buf. Work with a
2793 bufp = saved_reply = xstrdup (rs->buf);
2794 old_chain = make_cleanup (free_current_contents, &saved_reply);
2796 while (*bufp++ == 'm') /* reply contains one or more TID */
2800 new_thread = read_ptid (bufp, &bufp);
2801 if (!ptid_equal (new_thread, null_ptid))
2803 /* In non-stop mode, we assume new found threads
2804 are running until proven otherwise with a
2805 stop reply. In all-stop, we can only get
2806 here if all threads are stopped. */
2807 int running = non_stop ? 1 : 0;
2809 remote_notice_new_inferior (new_thread, running);
2812 while (*bufp++ == ','); /* comma-separated list */
2813 free_current_contents (&saved_reply);
2814 putpkt ("qsThreadInfo");
2815 getpkt (&rs->buf, &rs->buf_size, 0);
2816 bufp = saved_reply = xstrdup (rs->buf);
2818 do_cleanups (old_chain);
2823 /* Only qfThreadInfo is supported in non-stop mode. */
2827 /* Else fall back to old method based on jmetzler protocol. */
2828 use_threadinfo_query = 0;
2829 remote_find_new_threads ();
2834 * Collect a descriptive string about the given thread.
2835 * The target may say anything it wants to about the thread
2836 * (typically info about its blocked / runnable state, name, etc.).
2837 * This string will appear in the info threads display.
2839 * Optional: targets are not required to implement this function.
2843 remote_threads_extra_info (struct thread_info *tp)
2845 struct remote_state *rs = get_remote_state ();
2849 struct gdb_ext_thread_info threadinfo;
2850 static char display_buf[100]; /* arbitrary... */
2851 int n = 0; /* position in display_buf */
2853 if (remote_desc == 0) /* paranoia */
2854 internal_error (__FILE__, __LINE__,
2855 _("remote_threads_extra_info"));
2857 if (ptid_equal (tp->ptid, magic_null_ptid)
2858 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2859 /* This is the main thread which was added by GDB. The remote
2860 server doesn't know about it. */
2863 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2865 struct thread_info *info = find_thread_ptid (tp->ptid);
2867 if (info && info->private)
2868 return info->private->extra;
2873 if (use_threadextra_query)
2876 char *endb = rs->buf + get_remote_packet_size ();
2878 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2880 write_ptid (b, endb, tp->ptid);
2883 getpkt (&rs->buf, &rs->buf_size, 0);
2884 if (rs->buf[0] != 0)
2886 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2887 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2888 display_buf [result] = '\0';
2893 /* If the above query fails, fall back to the old method. */
2894 use_threadextra_query = 0;
2895 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2896 | TAG_MOREDISPLAY | TAG_DISPLAY;
2897 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2898 if (remote_get_threadinfo (&id, set, &threadinfo))
2899 if (threadinfo.active)
2901 if (*threadinfo.shortname)
2902 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2903 " Name: %s,", threadinfo.shortname);
2904 if (*threadinfo.display)
2905 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2906 " State: %s,", threadinfo.display);
2907 if (*threadinfo.more_display)
2908 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2909 " Priority: %s", threadinfo.more_display);
2913 /* For purely cosmetic reasons, clear up trailing commas. */
2914 if (',' == display_buf[n-1])
2915 display_buf[n-1] = ' ';
2924 remote_static_tracepoint_marker_at (CORE_ADDR addr,
2925 struct static_tracepoint_marker *marker)
2927 struct remote_state *rs = get_remote_state ();
2930 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2932 p += hexnumstr (p, addr);
2934 getpkt (&rs->buf, &rs->buf_size, 0);
2938 error (_("Remote failure reply: %s"), p);
2942 parse_static_tracepoint_marker_definition (p, &p, marker);
2949 static VEC(static_tracepoint_marker_p) *
2950 remote_static_tracepoint_markers_by_strid (const char *strid)
2952 struct remote_state *rs = get_remote_state ();
2953 VEC(static_tracepoint_marker_p) *markers = NULL;
2954 struct static_tracepoint_marker *marker = NULL;
2955 struct cleanup *old_chain;
2958 /* Ask for a first packet of static tracepoint marker
2961 getpkt (&rs->buf, &rs->buf_size, 0);
2964 error (_("Remote failure reply: %s"), p);
2966 old_chain = make_cleanup (free_current_marker, &marker);
2971 marker = XCNEW (struct static_tracepoint_marker);
2975 parse_static_tracepoint_marker_definition (p, &p, marker);
2977 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2979 VEC_safe_push (static_tracepoint_marker_p,
2985 release_static_tracepoint_marker (marker);
2986 memset (marker, 0, sizeof (*marker));
2989 while (*p++ == ','); /* comma-separated list */
2990 /* Ask for another packet of static tracepoint definition. */
2992 getpkt (&rs->buf, &rs->buf_size, 0);
2996 do_cleanups (old_chain);
3001 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3004 remote_get_ada_task_ptid (long lwp, long thread)
3006 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
3010 /* Restart the remote side; this is an extended protocol operation. */
3013 extended_remote_restart (void)
3015 struct remote_state *rs = get_remote_state ();
3017 /* Send the restart command; for reasons I don't understand the
3018 remote side really expects a number after the "R". */
3019 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3022 remote_fileio_reset ();
3025 /* Clean up connection to a remote debugger. */
3030 if (remote_desc == NULL)
3031 return; /* already closed */
3033 /* Make sure we leave stdin registered in the event loop, and we
3034 don't leave the async SIGINT signal handler installed. */
3035 remote_terminal_ours ();
3037 serial_close (remote_desc);
3040 /* We don't have a connection to the remote stub anymore. Get rid
3041 of all the inferiors and their threads we were controlling.
3042 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3043 will be unable to find the thread corresponding to (pid, 0, 0). */
3044 inferior_ptid = null_ptid;
3045 discard_all_inferiors ();
3047 /* Stop replies may from inferiors which are still unknown to GDB.
3048 We are closing the remote target, so we should discard
3049 everything, including the stop replies from GDB-unknown
3051 discard_pending_stop_replies (NULL);
3053 if (remote_async_inferior_event_token)
3054 delete_async_event_handler (&remote_async_inferior_event_token);
3056 remote_notif_unregister_async_event_handler ();
3058 trace_reset_local_state ();
3061 /* Query the remote side for the text, data and bss offsets. */
3066 struct remote_state *rs = get_remote_state ();
3069 int lose, num_segments = 0, do_sections, do_segments;
3070 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3071 struct section_offsets *offs;
3072 struct symfile_segment_data *data;
3074 if (symfile_objfile == NULL)
3077 putpkt ("qOffsets");
3078 getpkt (&rs->buf, &rs->buf_size, 0);
3081 if (buf[0] == '\000')
3082 return; /* Return silently. Stub doesn't support
3086 warning (_("Remote failure reply: %s"), buf);
3090 /* Pick up each field in turn. This used to be done with scanf, but
3091 scanf will make trouble if CORE_ADDR size doesn't match
3092 conversion directives correctly. The following code will work
3093 with any size of CORE_ADDR. */
3094 text_addr = data_addr = bss_addr = 0;
3098 if (strncmp (ptr, "Text=", 5) == 0)
3101 /* Don't use strtol, could lose on big values. */
3102 while (*ptr && *ptr != ';')
3103 text_addr = (text_addr << 4) + fromhex (*ptr++);
3105 if (strncmp (ptr, ";Data=", 6) == 0)
3108 while (*ptr && *ptr != ';')
3109 data_addr = (data_addr << 4) + fromhex (*ptr++);
3114 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3117 while (*ptr && *ptr != ';')
3118 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3120 if (bss_addr != data_addr)
3121 warning (_("Target reported unsupported offsets: %s"), buf);
3126 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3129 /* Don't use strtol, could lose on big values. */
3130 while (*ptr && *ptr != ';')
3131 text_addr = (text_addr << 4) + fromhex (*ptr++);
3134 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3137 while (*ptr && *ptr != ';')
3138 data_addr = (data_addr << 4) + fromhex (*ptr++);
3146 error (_("Malformed response to offset query, %s"), buf);
3147 else if (*ptr != '\0')
3148 warning (_("Target reported unsupported offsets: %s"), buf);
3150 offs = ((struct section_offsets *)
3151 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3152 memcpy (offs, symfile_objfile->section_offsets,
3153 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3155 data = get_symfile_segment_data (symfile_objfile->obfd);
3156 do_segments = (data != NULL);
3157 do_sections = num_segments == 0;
3159 if (num_segments > 0)
3161 segments[0] = text_addr;
3162 segments[1] = data_addr;
3164 /* If we have two segments, we can still try to relocate everything
3165 by assuming that the .text and .data offsets apply to the whole
3166 text and data segments. Convert the offsets given in the packet
3167 to base addresses for symfile_map_offsets_to_segments. */
3168 else if (data && data->num_segments == 2)
3170 segments[0] = data->segment_bases[0] + text_addr;
3171 segments[1] = data->segment_bases[1] + data_addr;
3174 /* If the object file has only one segment, assume that it is text
3175 rather than data; main programs with no writable data are rare,
3176 but programs with no code are useless. Of course the code might
3177 have ended up in the data segment... to detect that we would need
3178 the permissions here. */
3179 else if (data && data->num_segments == 1)
3181 segments[0] = data->segment_bases[0] + text_addr;
3184 /* There's no way to relocate by segment. */
3190 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3191 offs, num_segments, segments);
3193 if (ret == 0 && !do_sections)
3194 error (_("Can not handle qOffsets TextSeg "
3195 "response with this symbol file"));
3202 free_symfile_segment_data (data);
3206 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3208 /* This is a temporary kludge to force data and bss to use the
3209 same offsets because that's what nlmconv does now. The real
3210 solution requires changes to the stub and remote.c that I
3211 don't have time to do right now. */
3213 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3214 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3217 objfile_relocate (symfile_objfile, offs);
3220 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3221 threads we know are stopped already. This is used during the
3222 initial remote connection in non-stop mode --- threads that are
3223 reported as already being stopped are left stopped. */
3226 set_stop_requested_callback (struct thread_info *thread, void *data)
3228 /* If we have a stop reply for this thread, it must be stopped. */
3229 if (peek_stop_reply (thread->ptid))
3230 set_stop_requested (thread->ptid, 1);
3235 /* Send interrupt_sequence to remote target. */
3237 send_interrupt_sequence (void)
3239 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3240 remote_serial_write ("\x03", 1);
3241 else if (interrupt_sequence_mode == interrupt_sequence_break)
3242 serial_send_break (remote_desc);
3243 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3245 serial_send_break (remote_desc);
3246 remote_serial_write ("g", 1);
3249 internal_error (__FILE__, __LINE__,
3250 _("Invalid value for interrupt_sequence_mode: %s."),
3251 interrupt_sequence_mode);
3255 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3256 and extract the PTID. Returns NULL_PTID if not found. */
3259 stop_reply_extract_thread (char *stop_reply)
3261 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3265 /* Txx r:val ; r:val (...) */
3268 /* Look for "register" named "thread". */
3273 p1 = strchr (p, ':');
3277 if (strncmp (p, "thread", p1 - p) == 0)
3278 return read_ptid (++p1, &p);
3280 p1 = strchr (p, ';');
3292 /* Query the remote target for which is the current thread/process,
3293 add it to our tables, and update INFERIOR_PTID. The caller is
3294 responsible for setting the state such that the remote end is ready
3295 to return the current thread.
3297 This function is called after handling the '?' or 'vRun' packets,
3298 whose response is a stop reply from which we can also try
3299 extracting the thread. If the target doesn't support the explicit
3300 qC query, we infer the current thread from that stop reply, passed
3301 in in WAIT_STATUS, which may be NULL. */
3304 add_current_inferior_and_thread (char *wait_status)
3306 struct remote_state *rs = get_remote_state ();
3308 ptid_t ptid = null_ptid;
3310 inferior_ptid = null_ptid;
3312 /* Now, if we have thread information, update inferior_ptid. First
3313 if we have a stop reply handy, maybe it's a T stop reply with a
3314 "thread" register we can extract the current thread from. If
3315 not, ask the remote which is the current thread, with qC. The
3316 former method avoids a roundtrip. Note we don't use
3317 remote_parse_stop_reply as that makes use of the target
3318 architecture, which we haven't yet fully determined at this
3320 if (wait_status != NULL)
3321 ptid = stop_reply_extract_thread (wait_status);
3322 if (ptid_equal (ptid, null_ptid))
3323 ptid = remote_current_thread (inferior_ptid);
3325 if (!ptid_equal (ptid, null_ptid))
3327 if (!remote_multi_process_p (rs))
3330 inferior_ptid = ptid;
3334 /* Without this, some commands which require an active target
3335 (such as kill) won't work. This variable serves (at least)
3336 double duty as both the pid of the target process (if it has
3337 such), and as a flag indicating that a target is active. */
3338 inferior_ptid = magic_null_ptid;
3342 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3344 /* Add the main thread. */
3345 add_thread_silent (inferior_ptid);
3349 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3351 struct remote_state *rs = get_remote_state ();
3352 struct packet_config *noack_config;
3353 char *wait_status = NULL;
3355 immediate_quit++; /* Allow user to interrupt it. */
3358 if (interrupt_on_connect)
3359 send_interrupt_sequence ();
3361 /* Ack any packet which the remote side has already sent. */
3362 serial_write (remote_desc, "+", 1);
3364 /* Signal other parts that we're going through the initial setup,
3365 and so things may not be stable yet. */
3366 rs->starting_up = 1;
3368 /* The first packet we send to the target is the optional "supported
3369 packets" request. If the target can answer this, it will tell us
3370 which later probes to skip. */
3371 remote_query_supported ();
3373 /* If the stub wants to get a QAllow, compose one and send it. */
3374 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3375 remote_set_permissions ();
3377 /* Next, we possibly activate noack mode.
3379 If the QStartNoAckMode packet configuration is set to AUTO,
3380 enable noack mode if the stub reported a wish for it with
3383 If set to TRUE, then enable noack mode even if the stub didn't
3384 report it in qSupported. If the stub doesn't reply OK, the
3385 session ends with an error.
3387 If FALSE, then don't activate noack mode, regardless of what the
3388 stub claimed should be the default with qSupported. */
3390 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3392 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3393 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3394 && noack_config->support == PACKET_ENABLE))
3396 putpkt ("QStartNoAckMode");
3397 getpkt (&rs->buf, &rs->buf_size, 0);
3398 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3404 /* Tell the remote that we are using the extended protocol. */
3406 getpkt (&rs->buf, &rs->buf_size, 0);
3409 /* Let the target know which signals it is allowed to pass down to
3411 update_signals_program_target ();
3413 /* Next, if the target can specify a description, read it. We do
3414 this before anything involving memory or registers. */
3415 target_find_description ();
3417 /* Next, now that we know something about the target, update the
3418 address spaces in the program spaces. */
3419 update_address_spaces ();
3421 /* On OSs where the list of libraries is global to all
3422 processes, we fetch them early. */
3423 if (gdbarch_has_global_solist (target_gdbarch ()))
3424 solib_add (NULL, from_tty, target, auto_solib_add);
3428 if (!rs->non_stop_aware)
3429 error (_("Non-stop mode requested, but remote "
3430 "does not support non-stop"));
3432 putpkt ("QNonStop:1");
3433 getpkt (&rs->buf, &rs->buf_size, 0);
3435 if (strcmp (rs->buf, "OK") != 0)
3436 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3438 /* Find about threads and processes the stub is already
3439 controlling. We default to adding them in the running state.
3440 The '?' query below will then tell us about which threads are
3442 remote_threads_info (target);
3444 else if (rs->non_stop_aware)
3446 /* Don't assume that the stub can operate in all-stop mode.
3447 Request it explicitly. */
3448 putpkt ("QNonStop:0");
3449 getpkt (&rs->buf, &rs->buf_size, 0);
3451 if (strcmp (rs->buf, "OK") != 0)
3452 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3455 /* Upload TSVs regardless of whether the target is running or not. The
3456 remote stub, such as GDBserver, may have some predefined or builtin
3457 TSVs, even if the target is not running. */
3458 if (remote_get_trace_status (current_trace_status ()) != -1)
3460 struct uploaded_tsv *uploaded_tsvs = NULL;
3462 remote_upload_trace_state_variables (&uploaded_tsvs);
3463 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3466 /* Check whether the target is running now. */
3468 getpkt (&rs->buf, &rs->buf_size, 0);
3474 struct inferior *inf;
3476 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3479 error (_("The target is not running (try extended-remote?)"));
3481 /* We're connected, but not running. Drop out before we
3482 call start_remote. */
3483 rs->starting_up = 0;
3488 /* Save the reply for later. */
3489 wait_status = alloca (strlen (rs->buf) + 1);
3490 strcpy (wait_status, rs->buf);
3493 /* Let the stub know that we want it to return the thread. */
3494 set_continue_thread (minus_one_ptid);
3496 add_current_inferior_and_thread (wait_status);
3498 /* init_wait_for_inferior should be called before get_offsets in order
3499 to manage `inserted' flag in bp loc in a correct state.
3500 breakpoint_init_inferior, called from init_wait_for_inferior, set
3501 `inserted' flag to 0, while before breakpoint_re_set, called from
3502 start_remote, set `inserted' flag to 1. In the initialization of
3503 inferior, breakpoint_init_inferior should be called first, and then
3504 breakpoint_re_set can be called. If this order is broken, state of
3505 `inserted' flag is wrong, and cause some problems on breakpoint
3507 init_wait_for_inferior ();
3509 get_offsets (); /* Get text, data & bss offsets. */
3511 /* If we could not find a description using qXfer, and we know
3512 how to do it some other way, try again. This is not
3513 supported for non-stop; it could be, but it is tricky if
3514 there are no stopped threads when we connect. */
3515 if (remote_read_description_p (target)
3516 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3518 target_clear_description ();
3519 target_find_description ();
3522 /* Use the previously fetched status. */
3523 gdb_assert (wait_status != NULL);
3524 strcpy (rs->buf, wait_status);
3525 rs->cached_wait_status = 1;
3528 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3532 /* Clear WFI global state. Do this before finding about new
3533 threads and inferiors, and setting the current inferior.
3534 Otherwise we would clear the proceed status of the current
3535 inferior when we want its stop_soon state to be preserved
3536 (see notice_new_inferior). */
3537 init_wait_for_inferior ();
3539 /* In non-stop, we will either get an "OK", meaning that there
3540 are no stopped threads at this time; or, a regular stop
3541 reply. In the latter case, there may be more than one thread
3542 stopped --- we pull them all out using the vStopped
3544 if (strcmp (rs->buf, "OK") != 0)
3546 struct notif_client *notif = ¬if_client_stop;
3548 /* remote_notif_get_pending_replies acks this one, and gets
3550 notif_client_stop.pending_event
3551 = remote_notif_parse (notif, rs->buf);
3552 remote_notif_get_pending_events (notif);
3554 /* Make sure that threads that were stopped remain
3556 iterate_over_threads (set_stop_requested_callback, NULL);
3559 if (target_can_async_p ())
3560 target_async (inferior_event_handler, 0);
3562 if (thread_count () == 0)
3565 error (_("The target is not running (try extended-remote?)"));
3567 /* We're connected, but not running. Drop out before we
3568 call start_remote. */
3569 rs->starting_up = 0;
3573 /* Let the stub know that we want it to return the thread. */
3575 /* Force the stub to choose a thread. */
3576 set_general_thread (null_ptid);
3579 inferior_ptid = remote_current_thread (minus_one_ptid);
3580 if (ptid_equal (inferior_ptid, minus_one_ptid))
3581 error (_("remote didn't report the current thread in non-stop mode"));
3583 get_offsets (); /* Get text, data & bss offsets. */
3585 /* In non-stop mode, any cached wait status will be stored in
3586 the stop reply queue. */
3587 gdb_assert (wait_status == NULL);
3589 /* Report all signals during attach/startup. */
3590 remote_pass_signals (0, NULL);
3593 /* If we connected to a live target, do some additional setup. */
3594 if (target_has_execution)
3596 if (exec_bfd) /* No use without an exec file. */
3597 remote_check_symbols ();
3600 /* Possibly the target has been engaged in a trace run started
3601 previously; find out where things are at. */
3602 if (remote_get_trace_status (current_trace_status ()) != -1)
3604 struct uploaded_tp *uploaded_tps = NULL;
3606 if (current_trace_status ()->running)
3607 printf_filtered (_("Trace is already running on the target.\n"));
3609 remote_upload_tracepoints (&uploaded_tps);
3611 merge_uploaded_tracepoints (&uploaded_tps);
3614 /* The thread and inferior lists are now synchronized with the
3615 target, our symbols have been relocated, and we're merged the
3616 target's tracepoints with ours. We're done with basic start
3618 rs->starting_up = 0;
3620 /* If breakpoints are global, insert them now. */
3621 if (gdbarch_has_global_breakpoints (target_gdbarch ())
3622 && breakpoints_always_inserted_mode ())
3623 insert_breakpoints ();
3626 /* Open a connection to a remote debugger.
3627 NAME is the filename used for communication. */
3630 remote_open (char *name, int from_tty)
3632 remote_open_1 (name, from_tty, &remote_ops, 0);
3635 /* Open a connection to a remote debugger using the extended
3636 remote gdb protocol. NAME is the filename used for communication. */
3639 extended_remote_open (char *name, int from_tty)
3641 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3644 /* Generic code for opening a connection to a remote target. */
3647 init_all_packet_configs (void)
3651 for (i = 0; i < PACKET_MAX; i++)
3652 update_packet_config (&remote_protocol_packets[i]);
3655 /* Symbol look-up. */
3658 remote_check_symbols (void)
3660 struct remote_state *rs = get_remote_state ();
3661 char *msg, *reply, *tmp;
3662 struct minimal_symbol *sym;
3665 /* The remote side has no concept of inferiors that aren't running
3666 yet, it only knows about running processes. If we're connected
3667 but our current inferior is not running, we should not invite the
3668 remote target to request symbol lookups related to its
3669 (unrelated) current process. */
3670 if (!target_has_execution)
3673 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3676 /* Make sure the remote is pointing at the right process. Note
3677 there's no way to select "no process". */
3678 set_general_process ();
3680 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3681 because we need both at the same time. */
3682 msg = alloca (get_remote_packet_size ());
3684 /* Invite target to request symbol lookups. */
3686 putpkt ("qSymbol::");
3687 getpkt (&rs->buf, &rs->buf_size, 0);
3688 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3691 while (strncmp (reply, "qSymbol:", 8) == 0)
3694 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3696 sym = lookup_minimal_symbol (msg, NULL, NULL);
3698 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3701 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3702 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3704 /* If this is a function address, return the start of code
3705 instead of any data function descriptor. */
3706 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3710 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3711 phex_nz (sym_addr, addr_size), &reply[8]);
3715 getpkt (&rs->buf, &rs->buf_size, 0);
3720 static struct serial *
3721 remote_serial_open (char *name)
3723 static int udp_warning = 0;
3725 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3726 of in ser-tcp.c, because it is the remote protocol assuming that the
3727 serial connection is reliable and not the serial connection promising
3729 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3731 warning (_("The remote protocol may be unreliable over UDP.\n"
3732 "Some events may be lost, rendering further debugging "
3737 return serial_open (name);
3740 /* Inform the target of our permission settings. The permission flags
3741 work without this, but if the target knows the settings, it can do
3742 a couple things. First, it can add its own check, to catch cases
3743 that somehow manage to get by the permissions checks in target
3744 methods. Second, if the target is wired to disallow particular
3745 settings (for instance, a system in the field that is not set up to
3746 be able to stop at a breakpoint), it can object to any unavailable
3750 remote_set_permissions (void)
3752 struct remote_state *rs = get_remote_state ();
3754 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3755 "WriteReg:%x;WriteMem:%x;"
3756 "InsertBreak:%x;InsertTrace:%x;"
3757 "InsertFastTrace:%x;Stop:%x",
3758 may_write_registers, may_write_memory,
3759 may_insert_breakpoints, may_insert_tracepoints,
3760 may_insert_fast_tracepoints, may_stop);
3762 getpkt (&rs->buf, &rs->buf_size, 0);
3764 /* If the target didn't like the packet, warn the user. Do not try
3765 to undo the user's settings, that would just be maddening. */
3766 if (strcmp (rs->buf, "OK") != 0)
3767 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3770 /* This type describes each known response to the qSupported
3772 struct protocol_feature
3774 /* The name of this protocol feature. */
3777 /* The default for this protocol feature. */
3778 enum packet_support default_support;
3780 /* The function to call when this feature is reported, or after
3781 qSupported processing if the feature is not supported.
3782 The first argument points to this structure. The second
3783 argument indicates whether the packet requested support be
3784 enabled, disabled, or probed (or the default, if this function
3785 is being called at the end of processing and this feature was
3786 not reported). The third argument may be NULL; if not NULL, it
3787 is a NUL-terminated string taken from the packet following
3788 this feature's name and an equals sign. */
3789 void (*func) (const struct protocol_feature *, enum packet_support,
3792 /* The corresponding packet for this feature. Only used if
3793 FUNC is remote_supported_packet. */
3798 remote_supported_packet (const struct protocol_feature *feature,
3799 enum packet_support support,
3800 const char *argument)
3804 warning (_("Remote qSupported response supplied an unexpected value for"
3805 " \"%s\"."), feature->name);
3809 if (remote_protocol_packets[feature->packet].support
3810 == PACKET_SUPPORT_UNKNOWN)
3811 remote_protocol_packets[feature->packet].support = support;
3815 remote_packet_size (const struct protocol_feature *feature,
3816 enum packet_support support, const char *value)
3818 struct remote_state *rs = get_remote_state ();
3823 if (support != PACKET_ENABLE)
3826 if (value == NULL || *value == '\0')
3828 warning (_("Remote target reported \"%s\" without a size."),
3834 packet_size = strtol (value, &value_end, 16);
3835 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3837 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3838 feature->name, value);
3842 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3844 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3845 packet_size, MAX_REMOTE_PACKET_SIZE);
3846 packet_size = MAX_REMOTE_PACKET_SIZE;
3849 /* Record the new maximum packet size. */
3850 rs->explicit_packet_size = packet_size;
3854 remote_multi_process_feature (const struct protocol_feature *feature,
3855 enum packet_support support, const char *value)
3857 struct remote_state *rs = get_remote_state ();
3859 rs->multi_process_aware = (support == PACKET_ENABLE);
3863 remote_non_stop_feature (const struct protocol_feature *feature,
3864 enum packet_support support, const char *value)
3866 struct remote_state *rs = get_remote_state ();
3868 rs->non_stop_aware = (support == PACKET_ENABLE);
3872 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3873 enum packet_support support,
3876 struct remote_state *rs = get_remote_state ();
3878 rs->cond_tracepoints = (support == PACKET_ENABLE);
3882 remote_cond_breakpoint_feature (const struct protocol_feature *feature,
3883 enum packet_support support,
3886 struct remote_state *rs = get_remote_state ();
3888 rs->cond_breakpoints = (support == PACKET_ENABLE);
3892 remote_breakpoint_commands_feature (const struct protocol_feature *feature,
3893 enum packet_support support,
3896 struct remote_state *rs = get_remote_state ();
3898 rs->breakpoint_commands = (support == PACKET_ENABLE);
3902 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3903 enum packet_support support,
3906 struct remote_state *rs = get_remote_state ();
3908 rs->fast_tracepoints = (support == PACKET_ENABLE);
3912 remote_static_tracepoint_feature (const struct protocol_feature *feature,
3913 enum packet_support support,
3916 struct remote_state *rs = get_remote_state ();
3918 rs->static_tracepoints = (support == PACKET_ENABLE);
3922 remote_install_in_trace_feature (const struct protocol_feature *feature,
3923 enum packet_support support,
3926 struct remote_state *rs = get_remote_state ();
3928 rs->install_in_trace = (support == PACKET_ENABLE);
3932 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3933 enum packet_support support,
3936 struct remote_state *rs = get_remote_state ();
3938 rs->disconnected_tracing = (support == PACKET_ENABLE);
3942 remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3943 enum packet_support support,
3946 struct remote_state *rs = get_remote_state ();
3948 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3952 remote_string_tracing_feature (const struct protocol_feature *feature,
3953 enum packet_support support,
3956 struct remote_state *rs = get_remote_state ();
3958 rs->string_tracing = (support == PACKET_ENABLE);
3962 remote_augmented_libraries_svr4_read_feature
3963 (const struct protocol_feature *feature,
3964 enum packet_support support, const char *value)
3966 struct remote_state *rs = get_remote_state ();
3968 rs->augmented_libraries_svr4_read = (support == PACKET_ENABLE);
3971 static struct protocol_feature remote_protocol_features[] = {
3972 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3973 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3974 PACKET_qXfer_auxv },
3975 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3976 PACKET_qXfer_features },
3977 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3978 PACKET_qXfer_libraries },
3979 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3980 PACKET_qXfer_libraries_svr4 },
3981 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3982 remote_augmented_libraries_svr4_read_feature, -1 },
3983 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3984 PACKET_qXfer_memory_map },
3985 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3986 PACKET_qXfer_spu_read },
3987 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3988 PACKET_qXfer_spu_write },
3989 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3990 PACKET_qXfer_osdata },
3991 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3992 PACKET_qXfer_threads },
3993 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3994 PACKET_qXfer_traceframe_info },
3995 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3996 PACKET_QPassSignals },
3997 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3998 PACKET_QProgramSignals },
3999 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4000 PACKET_QStartNoAckMode },
4001 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
4002 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
4003 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4004 PACKET_qXfer_siginfo_read },
4005 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4006 PACKET_qXfer_siginfo_write },
4007 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
4008 PACKET_ConditionalTracepoints },
4009 { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
4010 PACKET_ConditionalBreakpoints },
4011 { "BreakpointCommands", PACKET_DISABLE, remote_breakpoint_commands_feature,
4012 PACKET_BreakpointCommands },
4013 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
4014 PACKET_FastTracepoints },
4015 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
4016 PACKET_StaticTracepoints },
4017 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
4018 PACKET_InstallInTrace},
4019 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
4021 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4023 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4025 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4026 PACKET_TracepointSource },
4027 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4029 { "EnableDisableTracepoints", PACKET_DISABLE,
4030 remote_enable_disable_tracepoint_feature, -1 },
4031 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4032 PACKET_qXfer_fdpic },
4033 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4035 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4036 PACKET_QDisableRandomization },
4037 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4038 { "QTBuffer:size", PACKET_DISABLE,
4039 remote_supported_packet, PACKET_QTBuffer_size},
4040 { "tracenz", PACKET_DISABLE,
4041 remote_string_tracing_feature, -1 },
4042 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4043 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4044 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4045 PACKET_qXfer_btrace }
4048 static char *remote_support_xml;
4050 /* Register string appended to "xmlRegisters=" in qSupported query. */
4053 register_remote_support_xml (const char *xml)
4055 #if defined(HAVE_LIBEXPAT)
4056 if (remote_support_xml == NULL)
4057 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4060 char *copy = xstrdup (remote_support_xml + 13);
4061 char *p = strtok (copy, ",");
4065 if (strcmp (p, xml) == 0)
4072 while ((p = strtok (NULL, ",")) != NULL);
4075 remote_support_xml = reconcat (remote_support_xml,
4076 remote_support_xml, ",", xml,
4083 remote_query_supported_append (char *msg, const char *append)
4086 return reconcat (msg, msg, ";", append, (char *) NULL);
4088 return xstrdup (append);
4092 remote_query_supported (void)
4094 struct remote_state *rs = get_remote_state ();
4097 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4099 /* The packet support flags are handled differently for this packet
4100 than for most others. We treat an error, a disabled packet, and
4101 an empty response identically: any features which must be reported
4102 to be used will be automatically disabled. An empty buffer
4103 accomplishes this, since that is also the representation for a list
4104 containing no features. */
4107 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
4110 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4112 q = remote_query_supported_append (q, "multiprocess+");
4114 if (remote_support_xml)
4115 q = remote_query_supported_append (q, remote_support_xml);
4117 q = remote_query_supported_append (q, "qRelocInsn+");
4119 q = reconcat (q, "qSupported:", q, (char *) NULL);
4122 do_cleanups (old_chain);
4124 getpkt (&rs->buf, &rs->buf_size, 0);
4126 /* If an error occured, warn, but do not return - just reset the
4127 buffer to empty and go on to disable features. */
4128 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4131 warning (_("Remote failure reply: %s"), rs->buf);
4136 memset (seen, 0, sizeof (seen));
4141 enum packet_support is_supported;
4142 char *p, *end, *name_end, *value;
4144 /* First separate out this item from the rest of the packet. If
4145 there's another item after this, we overwrite the separator
4146 (terminated strings are much easier to work with). */
4148 end = strchr (p, ';');
4151 end = p + strlen (p);
4161 warning (_("empty item in \"qSupported\" response"));
4166 name_end = strchr (p, '=');
4169 /* This is a name=value entry. */
4170 is_supported = PACKET_ENABLE;
4171 value = name_end + 1;
4180 is_supported = PACKET_ENABLE;
4184 is_supported = PACKET_DISABLE;
4188 is_supported = PACKET_SUPPORT_UNKNOWN;
4192 warning (_("unrecognized item \"%s\" "
4193 "in \"qSupported\" response"), p);
4199 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4200 if (strcmp (remote_protocol_features[i].name, p) == 0)
4202 const struct protocol_feature *feature;
4205 feature = &remote_protocol_features[i];
4206 feature->func (feature, is_supported, value);
4211 /* If we increased the packet size, make sure to increase the global
4212 buffer size also. We delay this until after parsing the entire
4213 qSupported packet, because this is the same buffer we were
4215 if (rs->buf_size < rs->explicit_packet_size)
4217 rs->buf_size = rs->explicit_packet_size;
4218 rs->buf = xrealloc (rs->buf, rs->buf_size);
4221 /* Handle the defaults for unmentioned features. */
4222 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4225 const struct protocol_feature *feature;
4227 feature = &remote_protocol_features[i];
4228 feature->func (feature, feature->default_support, NULL);
4232 /* Remove any of the remote.c targets from target stack. Upper targets depend
4233 on it so remove them first. */
4236 remote_unpush_target (void)
4238 pop_all_targets_above (process_stratum - 1);
4242 remote_open_1 (char *name, int from_tty,
4243 struct target_ops *target, int extended_p)
4245 struct remote_state *rs = get_remote_state ();
4248 error (_("To open a remote debug connection, you need to specify what\n"
4249 "serial device is attached to the remote system\n"
4250 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4252 /* See FIXME above. */
4253 if (!target_async_permitted)
4254 wait_forever_enabled_p = 1;
4256 /* If we're connected to a running target, target_preopen will kill it.
4257 Ask this question first, before target_preopen has a chance to kill
4259 if (remote_desc != NULL && !have_inferiors ())
4262 && !query (_("Already connected to a remote target. Disconnect? ")))
4263 error (_("Still connected."));
4266 /* Here the possibly existing remote target gets unpushed. */
4267 target_preopen (from_tty);
4269 /* Make sure we send the passed signals list the next time we resume. */
4270 xfree (last_pass_packet);
4271 last_pass_packet = NULL;
4273 /* Make sure we send the program signals list the next time we
4275 xfree (last_program_signals_packet);
4276 last_program_signals_packet = NULL;
4278 remote_fileio_reset ();
4279 reopen_exec_file ();
4282 remote_desc = remote_serial_open (name);
4284 perror_with_name (name);
4286 if (baud_rate != -1)
4288 if (serial_setbaudrate (remote_desc, baud_rate))
4290 /* The requested speed could not be set. Error out to
4291 top level after closing remote_desc. Take care to
4292 set remote_desc to NULL to avoid closing remote_desc
4294 serial_close (remote_desc);
4296 perror_with_name (name);
4300 serial_raw (remote_desc);
4302 /* If there is something sitting in the buffer we might take it as a
4303 response to a command, which would be bad. */
4304 serial_flush_input (remote_desc);
4308 puts_filtered ("Remote debugging using ");
4309 puts_filtered (name);
4310 puts_filtered ("\n");
4312 push_target (target); /* Switch to using remote target now. */
4314 /* Register extra event sources in the event loop. */
4315 remote_async_inferior_event_token
4316 = create_async_event_handler (remote_async_inferior_event_handler,
4318 remote_notif_register_async_event_handler ();
4320 /* Reset the target state; these things will be queried either by
4321 remote_query_supported or as they are needed. */
4322 init_all_packet_configs ();
4323 rs->cached_wait_status = 0;
4324 rs->explicit_packet_size = 0;
4326 rs->multi_process_aware = 0;
4327 rs->extended = extended_p;
4328 rs->non_stop_aware = 0;
4329 rs->waiting_for_stop_reply = 0;
4330 rs->ctrlc_pending_p = 0;
4332 general_thread = not_sent_ptid;
4333 continue_thread = not_sent_ptid;
4334 remote_traceframe_number = -1;
4336 /* Probe for ability to use "ThreadInfo" query, as required. */
4337 use_threadinfo_query = 1;
4338 use_threadextra_query = 1;
4340 if (target_async_permitted)
4342 /* With this target we start out by owning the terminal. */
4343 remote_async_terminal_ours_p = 1;
4345 /* FIXME: cagney/1999-09-23: During the initial connection it is
4346 assumed that the target is already ready and able to respond to
4347 requests. Unfortunately remote_start_remote() eventually calls
4348 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4349 around this. Eventually a mechanism that allows
4350 wait_for_inferior() to expect/get timeouts will be
4352 wait_forever_enabled_p = 0;
4355 /* First delete any symbols previously loaded from shared libraries. */
4356 no_shared_libraries (NULL, 0);
4359 init_thread_list ();
4361 /* Start the remote connection. If error() or QUIT, discard this
4362 target (we'd otherwise be in an inconsistent state) and then
4363 propogate the error on up the exception chain. This ensures that
4364 the caller doesn't stumble along blindly assuming that the
4365 function succeeded. The CLI doesn't have this problem but other
4366 UI's, such as MI do.
4368 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4369 this function should return an error indication letting the
4370 caller restore the previous state. Unfortunately the command
4371 ``target remote'' is directly wired to this function making that
4372 impossible. On a positive note, the CLI side of this problem has
4373 been fixed - the function set_cmd_context() makes it possible for
4374 all the ``target ....'' commands to share a common callback
4375 function. See cli-dump.c. */
4377 volatile struct gdb_exception ex;
4379 TRY_CATCH (ex, RETURN_MASK_ALL)
4381 remote_start_remote (from_tty, target, extended_p);
4385 /* Pop the partially set up target - unless something else did
4386 already before throwing the exception. */
4387 if (remote_desc != NULL)
4388 remote_unpush_target ();
4389 if (target_async_permitted)
4390 wait_forever_enabled_p = 1;
4391 throw_exception (ex);
4395 if (target_async_permitted)
4396 wait_forever_enabled_p = 1;
4399 /* This takes a program previously attached to and detaches it. After
4400 this is done, GDB can be used to debug some other program. We
4401 better not have left any breakpoints in the target program or it'll
4402 die when it hits one. */
4405 remote_detach_1 (char *args, int from_tty, int extended)
4407 int pid = ptid_get_pid (inferior_ptid);
4408 struct remote_state *rs = get_remote_state ();
4411 error (_("Argument given to \"detach\" when remotely debugging."));
4413 if (!target_has_execution)
4414 error (_("No process to detach from."));
4418 char *exec_file = get_exec_file (0);
4419 if (exec_file == NULL)
4421 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4422 target_pid_to_str (pid_to_ptid (pid)));
4423 gdb_flush (gdb_stdout);
4426 /* Tell the remote target to detach. */
4427 if (remote_multi_process_p (rs))
4428 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4430 strcpy (rs->buf, "D");
4433 getpkt (&rs->buf, &rs->buf_size, 0);
4435 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4437 else if (rs->buf[0] == '\0')
4438 error (_("Remote doesn't know how to detach"));
4440 error (_("Can't detach process."));
4442 if (from_tty && !extended)
4443 puts_filtered (_("Ending remote debugging.\n"));
4445 target_mourn_inferior ();
4449 remote_detach (struct target_ops *ops, char *args, int from_tty)
4451 remote_detach_1 (args, from_tty, 0);
4455 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
4457 remote_detach_1 (args, from_tty, 1);
4460 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4463 remote_disconnect (struct target_ops *target, char *args, int from_tty)
4466 error (_("Argument given to \"disconnect\" when remotely debugging."));
4468 /* Make sure we unpush even the extended remote targets; mourn
4469 won't do it. So call remote_mourn_1 directly instead of
4470 target_mourn_inferior. */
4471 remote_mourn_1 (target);
4474 puts_filtered ("Ending remote debugging.\n");
4477 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4478 be chatty about it. */
4481 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4483 struct remote_state *rs = get_remote_state ();
4485 char *wait_status = NULL;
4487 pid = parse_pid_to_attach (args);
4489 /* Remote PID can be freely equal to getpid, do not check it here the same
4490 way as in other targets. */
4492 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4493 error (_("This target does not support attaching to a process"));
4497 char *exec_file = get_exec_file (0);
4500 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4501 target_pid_to_str (pid_to_ptid (pid)));
4503 printf_unfiltered (_("Attaching to %s\n"),
4504 target_pid_to_str (pid_to_ptid (pid)));
4506 gdb_flush (gdb_stdout);
4509 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4511 getpkt (&rs->buf, &rs->buf_size, 0);
4513 if (packet_ok (rs->buf,
4514 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
4518 /* Save the reply for later. */
4519 wait_status = alloca (strlen (rs->buf) + 1);
4520 strcpy (wait_status, rs->buf);
4522 else if (strcmp (rs->buf, "OK") != 0)
4523 error (_("Attaching to %s failed with: %s"),
4524 target_pid_to_str (pid_to_ptid (pid)),
4527 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4528 error (_("This target does not support attaching to a process"));
4530 error (_("Attaching to %s failed"),
4531 target_pid_to_str (pid_to_ptid (pid)));
4533 set_current_inferior (remote_add_inferior (0, pid, 1));
4535 inferior_ptid = pid_to_ptid (pid);
4539 struct thread_info *thread;
4541 /* Get list of threads. */
4542 remote_threads_info (target);
4544 thread = first_thread_of_process (pid);
4546 inferior_ptid = thread->ptid;
4548 inferior_ptid = pid_to_ptid (pid);
4550 /* Invalidate our notion of the remote current thread. */
4551 record_currthread (minus_one_ptid);
4555 /* Now, if we have thread information, update inferior_ptid. */
4556 inferior_ptid = remote_current_thread (inferior_ptid);
4558 /* Add the main thread to the thread list. */
4559 add_thread_silent (inferior_ptid);
4562 /* Next, if the target can specify a description, read it. We do
4563 this before anything involving memory or registers. */
4564 target_find_description ();
4568 /* Use the previously fetched status. */
4569 gdb_assert (wait_status != NULL);
4571 if (target_can_async_p ())
4573 struct notif_event *reply
4574 = remote_notif_parse (¬if_client_stop, wait_status);
4576 push_stop_reply ((struct stop_reply *) reply);
4578 target_async (inferior_event_handler, 0);
4582 gdb_assert (wait_status != NULL);
4583 strcpy (rs->buf, wait_status);
4584 rs->cached_wait_status = 1;
4588 gdb_assert (wait_status == NULL);
4592 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4594 extended_remote_attach_1 (ops, args, from_tty);
4597 /* Convert hex digit A to a number. */
4602 if (a >= '0' && a <= '9')
4604 else if (a >= 'a' && a <= 'f')
4605 return a - 'a' + 10;
4606 else if (a >= 'A' && a <= 'F')
4607 return a - 'A' + 10;
4609 error (_("Reply contains invalid hex digit %d"), a);
4613 hex2bin (const char *hex, gdb_byte *bin, int count)
4617 for (i = 0; i < count; i++)
4619 if (hex[0] == 0 || hex[1] == 0)
4621 /* Hex string is short, or of uneven length.
4622 Return the count that has been converted so far. */
4625 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4631 /* Convert number NIB to a hex digit. */
4639 return 'a' + nib - 10;
4643 bin2hex (const gdb_byte *bin, char *hex, int count)
4647 /* May use a length, or a nul-terminated string as input. */
4649 count = strlen ((char *) bin);
4651 for (i = 0; i < count; i++)
4653 *hex++ = tohex ((*bin >> 4) & 0xf);
4654 *hex++ = tohex (*bin++ & 0xf);
4660 /* Check for the availability of vCont. This function should also check
4664 remote_vcont_probe (struct remote_state *rs)
4668 strcpy (rs->buf, "vCont?");
4670 getpkt (&rs->buf, &rs->buf_size, 0);
4673 /* Make sure that the features we assume are supported. */
4674 if (strncmp (buf, "vCont", 5) == 0)
4677 int support_s, support_S, support_c, support_C;
4683 rs->supports_vCont.t = 0;
4684 rs->supports_vCont.r = 0;
4685 while (p && *p == ';')
4688 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4690 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4692 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4694 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4696 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4697 rs->supports_vCont.t = 1;
4698 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4699 rs->supports_vCont.r = 1;
4701 p = strchr (p, ';');
4704 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4705 BUF will make packet_ok disable the packet. */
4706 if (!support_s || !support_S || !support_c || !support_C)
4710 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4713 /* Helper function for building "vCont" resumptions. Write a
4714 resumption to P. ENDP points to one-passed-the-end of the buffer
4715 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4716 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4717 resumed thread should be single-stepped and/or signalled. If PTID
4718 equals minus_one_ptid, then all threads are resumed; if PTID
4719 represents a process, then all threads of the process are resumed;
4720 the thread to be stepped and/or signalled is given in the global
4724 append_resumption (char *p, char *endp,
4725 ptid_t ptid, int step, enum gdb_signal siggnal)
4727 struct remote_state *rs = get_remote_state ();
4729 if (step && siggnal != GDB_SIGNAL_0)
4730 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4732 /* GDB is willing to range step. */
4733 && use_range_stepping
4734 /* Target supports range stepping. */
4735 && rs->supports_vCont.r
4736 /* We don't currently support range stepping multiple
4737 threads with a wildcard (though the protocol allows it,
4738 so stubs shouldn't make an active effort to forbid
4740 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4742 struct thread_info *tp;
4744 if (ptid_equal (ptid, minus_one_ptid))
4746 /* If we don't know about the target thread's tid, then
4747 we're resuming magic_null_ptid (see caller). */
4748 tp = find_thread_ptid (magic_null_ptid);
4751 tp = find_thread_ptid (ptid);
4752 gdb_assert (tp != NULL);
4754 if (tp->control.may_range_step)
4756 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4758 p += xsnprintf (p, endp - p, ";r%s,%s",
4759 phex_nz (tp->control.step_range_start,
4761 phex_nz (tp->control.step_range_end,
4765 p += xsnprintf (p, endp - p, ";s");
4768 p += xsnprintf (p, endp - p, ";s");
4769 else if (siggnal != GDB_SIGNAL_0)
4770 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4772 p += xsnprintf (p, endp - p, ";c");
4774 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4778 /* All (-1) threads of process. */
4779 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4781 p += xsnprintf (p, endp - p, ":");
4782 p = write_ptid (p, endp, nptid);
4784 else if (!ptid_equal (ptid, minus_one_ptid))
4786 p += xsnprintf (p, endp - p, ":");
4787 p = write_ptid (p, endp, ptid);
4793 /* Append a vCont continue-with-signal action for threads that have a
4794 non-zero stop signal. */
4797 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4799 struct thread_info *thread;
4801 ALL_THREADS (thread)
4802 if (ptid_match (thread->ptid, ptid)
4803 && !ptid_equal (inferior_ptid, thread->ptid)
4804 && thread->suspend.stop_signal != GDB_SIGNAL_0
4805 && signal_pass_state (thread->suspend.stop_signal))
4807 p = append_resumption (p, endp, thread->ptid,
4808 0, thread->suspend.stop_signal);
4809 thread->suspend.stop_signal = GDB_SIGNAL_0;
4815 /* Resume the remote inferior by using a "vCont" packet. The thread
4816 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4817 resumed thread should be single-stepped and/or signalled. If PTID
4818 equals minus_one_ptid, then all threads are resumed; the thread to
4819 be stepped and/or signalled is given in the global INFERIOR_PTID.
4820 This function returns non-zero iff it resumes the inferior.
4822 This function issues a strict subset of all possible vCont commands at the
4826 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4828 struct remote_state *rs = get_remote_state ();
4832 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4833 remote_vcont_probe (rs);
4835 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4839 endp = rs->buf + get_remote_packet_size ();
4841 /* If we could generate a wider range of packets, we'd have to worry
4842 about overflowing BUF. Should there be a generic
4843 "multi-part-packet" packet? */
4845 p += xsnprintf (p, endp - p, "vCont");
4847 if (ptid_equal (ptid, magic_null_ptid))
4849 /* MAGIC_NULL_PTID means that we don't have any active threads,
4850 so we don't have any TID numbers the inferior will
4851 understand. Make sure to only send forms that do not specify
4853 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4855 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4857 /* Resume all threads (of all processes, or of a single
4858 process), with preference for INFERIOR_PTID. This assumes
4859 inferior_ptid belongs to the set of all threads we are about
4861 if (step || siggnal != GDB_SIGNAL_0)
4863 /* Step inferior_ptid, with or without signal. */
4864 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4867 /* Also pass down any pending signaled resumption for other
4868 threads not the current. */
4869 p = append_pending_thread_resumptions (p, endp, ptid);
4871 /* And continue others without a signal. */
4872 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4876 /* Scheduler locking; resume only PTID. */
4877 append_resumption (p, endp, ptid, step, siggnal);
4880 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4885 /* In non-stop, the stub replies to vCont with "OK". The stop
4886 reply will be reported asynchronously by means of a `%Stop'
4888 getpkt (&rs->buf, &rs->buf_size, 0);
4889 if (strcmp (rs->buf, "OK") != 0)
4890 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4896 /* Tell the remote machine to resume. */
4898 static enum gdb_signal last_sent_signal = GDB_SIGNAL_0;
4900 static int last_sent_step;
4903 remote_resume (struct target_ops *ops,
4904 ptid_t ptid, int step, enum gdb_signal siggnal)
4906 struct remote_state *rs = get_remote_state ();
4909 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4910 (explained in remote-notif.c:handle_notification) so
4911 remote_notif_process is not called. We need find a place where
4912 it is safe to start a 'vNotif' sequence. It is good to do it
4913 before resuming inferior, because inferior was stopped and no RSP
4914 traffic at that moment. */
4916 remote_notif_process (¬if_client_stop);
4918 last_sent_signal = siggnal;
4919 last_sent_step = step;
4921 /* The vCont packet doesn't need to specify threads via Hc. */
4922 /* No reverse support (yet) for vCont. */
4923 if (execution_direction != EXEC_REVERSE)
4924 if (remote_vcont_resume (ptid, step, siggnal))
4927 /* All other supported resume packets do use Hc, so set the continue
4929 if (ptid_equal (ptid, minus_one_ptid))
4930 set_continue_thread (any_thread_ptid);
4932 set_continue_thread (ptid);
4935 if (execution_direction == EXEC_REVERSE)
4937 /* We don't pass signals to the target in reverse exec mode. */
4938 if (info_verbose && siggnal != GDB_SIGNAL_0)
4939 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4943 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4944 error (_("Remote reverse-step not supported."));
4946 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4947 error (_("Remote reverse-continue not supported."));
4949 strcpy (buf, step ? "bs" : "bc");
4951 else if (siggnal != GDB_SIGNAL_0)
4953 buf[0] = step ? 'S' : 'C';
4954 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4955 buf[2] = tohex (((int) siggnal) & 0xf);
4959 strcpy (buf, step ? "s" : "c");
4964 /* We are about to start executing the inferior, let's register it
4965 with the event loop. NOTE: this is the one place where all the
4966 execution commands end up. We could alternatively do this in each
4967 of the execution commands in infcmd.c. */
4968 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4969 into infcmd.c in order to allow inferior function calls to work
4970 NOT asynchronously. */
4971 if (target_can_async_p ())
4972 target_async (inferior_event_handler, 0);
4974 /* We've just told the target to resume. The remote server will
4975 wait for the inferior to stop, and then send a stop reply. In
4976 the mean time, we can't start another command/query ourselves
4977 because the stub wouldn't be ready to process it. This applies
4978 only to the base all-stop protocol, however. In non-stop (which
4979 only supports vCont), the stub replies with an "OK", and is
4980 immediate able to process further serial input. */
4982 rs->waiting_for_stop_reply = 1;
4986 /* Set up the signal handler for SIGINT, while the target is
4987 executing, ovewriting the 'regular' SIGINT signal handler. */
4989 initialize_sigint_signal_handler (void)
4991 signal (SIGINT, handle_remote_sigint);
4994 /* Signal handler for SIGINT, while the target is executing. */
4996 handle_remote_sigint (int sig)
4998 signal (sig, handle_remote_sigint_twice);
4999 mark_async_signal_handler (sigint_remote_token);
5002 /* Signal handler for SIGINT, installed after SIGINT has already been
5003 sent once. It will take effect the second time that the user sends
5006 handle_remote_sigint_twice (int sig)
5008 signal (sig, handle_remote_sigint);
5009 mark_async_signal_handler (sigint_remote_twice_token);
5012 /* Perform the real interruption of the target execution, in response
5015 async_remote_interrupt (gdb_client_data arg)
5018 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5020 target_stop (inferior_ptid);
5023 /* Perform interrupt, if the first attempt did not succeed. Just give
5024 up on the target alltogether. */
5026 async_remote_interrupt_twice (gdb_client_data arg)
5029 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5034 /* Reinstall the usual SIGINT handlers, after the target has
5037 cleanup_sigint_signal_handler (void *dummy)
5039 signal (SIGINT, handle_sigint);
5042 /* Send ^C to target to halt it. Target will respond, and send us a
5044 static void (*ofunc) (int);
5046 /* The command line interface's stop routine. This function is installed
5047 as a signal handler for SIGINT. The first time a user requests a
5048 stop, we call remote_stop to send a break or ^C. If there is no
5049 response from the target (it didn't stop when the user requested it),
5050 we ask the user if he'd like to detach from the target. */
5052 remote_interrupt (int signo)
5054 /* If this doesn't work, try more severe steps. */
5055 signal (signo, remote_interrupt_twice);
5057 gdb_call_async_signal_handler (sigint_remote_token, 1);
5060 /* The user typed ^C twice. */
5063 remote_interrupt_twice (int signo)
5065 signal (signo, ofunc);
5066 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
5067 signal (signo, remote_interrupt);
5070 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5071 thread, all threads of a remote process, or all threads of all
5075 remote_stop_ns (ptid_t ptid)
5077 struct remote_state *rs = get_remote_state ();
5079 char *endp = rs->buf + get_remote_packet_size ();
5081 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
5082 remote_vcont_probe (rs);
5084 if (!rs->supports_vCont.t)
5085 error (_("Remote server does not support stopping threads"));
5087 if (ptid_equal (ptid, minus_one_ptid)
5088 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5089 p += xsnprintf (p, endp - p, "vCont;t");
5094 p += xsnprintf (p, endp - p, "vCont;t:");
5096 if (ptid_is_pid (ptid))
5097 /* All (-1) threads of process. */
5098 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
5101 /* Small optimization: if we already have a stop reply for
5102 this thread, no use in telling the stub we want this
5104 if (peek_stop_reply (ptid))
5110 write_ptid (p, endp, nptid);
5113 /* In non-stop, we get an immediate OK reply. The stop reply will
5114 come in asynchronously by notification. */
5116 getpkt (&rs->buf, &rs->buf_size, 0);
5117 if (strcmp (rs->buf, "OK") != 0)
5118 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5121 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5122 remote target. It is undefined which thread of which process
5123 reports the stop. */
5126 remote_stop_as (ptid_t ptid)
5128 struct remote_state *rs = get_remote_state ();
5130 rs->ctrlc_pending_p = 1;
5132 /* If the inferior is stopped already, but the core didn't know
5133 about it yet, just ignore the request. The cached wait status
5134 will be collected in remote_wait. */
5135 if (rs->cached_wait_status)
5138 /* Send interrupt_sequence to remote target. */
5139 send_interrupt_sequence ();
5142 /* This is the generic stop called via the target vector. When a target
5143 interrupt is requested, either by the command line or the GUI, we
5144 will eventually end up here. */
5147 remote_stop (ptid_t ptid)
5150 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5153 remote_stop_ns (ptid);
5155 remote_stop_as (ptid);
5158 /* Ask the user what to do when an interrupt is received. */
5161 interrupt_query (void)
5163 target_terminal_ours ();
5165 if (target_can_async_p ())
5167 signal (SIGINT, handle_sigint);
5172 if (query (_("Interrupted while waiting for the program.\n\
5173 Give up (and stop debugging it)? ")))
5175 remote_unpush_target ();
5180 target_terminal_inferior ();
5183 /* Enable/disable target terminal ownership. Most targets can use
5184 terminal groups to control terminal ownership. Remote targets are
5185 different in that explicit transfer of ownership to/from GDB/target
5189 remote_terminal_inferior (void)
5191 if (!target_async_permitted)
5192 /* Nothing to do. */
5195 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5196 idempotent. The event-loop GDB talking to an asynchronous target
5197 with a synchronous command calls this function from both
5198 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5199 transfer the terminal to the target when it shouldn't this guard
5201 if (!remote_async_terminal_ours_p)
5203 delete_file_handler (input_fd);
5204 remote_async_terminal_ours_p = 0;
5205 initialize_sigint_signal_handler ();
5206 /* NOTE: At this point we could also register our selves as the
5207 recipient of all input. Any characters typed could then be
5208 passed on down to the target. */
5212 remote_terminal_ours (void)
5214 if (!target_async_permitted)
5215 /* Nothing to do. */
5218 /* See FIXME in remote_terminal_inferior. */
5219 if (remote_async_terminal_ours_p)
5221 cleanup_sigint_signal_handler (NULL);
5222 add_file_handler (input_fd, stdin_event_handler, 0);
5223 remote_async_terminal_ours_p = 1;
5227 remote_console_output (char *msg)
5231 for (p = msg; p[0] && p[1]; p += 2)
5234 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5238 fputs_unfiltered (tb, gdb_stdtarg);
5240 gdb_flush (gdb_stdtarg);
5243 typedef struct cached_reg
5246 gdb_byte data[MAX_REGISTER_SIZE];
5249 DEF_VEC_O(cached_reg_t);
5251 typedef struct stop_reply
5253 struct notif_event base;
5255 /* The identifier of the thread about this event */
5258 struct target_waitstatus ws;
5260 /* Expedited registers. This makes remote debugging a bit more
5261 efficient for those targets that provide critical registers as
5262 part of their normal status mechanism (as another roundtrip to
5263 fetch them is avoided). */
5264 VEC(cached_reg_t) *regcache;
5266 int stopped_by_watchpoint_p;
5267 CORE_ADDR watch_data_address;
5275 DECLARE_QUEUE_P (stop_reply_p);
5276 DEFINE_QUEUE_P (stop_reply_p);
5277 /* The list of already fetched and acknowledged stop events. This
5278 queue is used for notification Stop, and other notifications
5279 don't need queue for their events, because the notification events
5280 of Stop can't be consumed immediately, so that events should be
5281 queued first, and be consumed by remote_wait_{ns,as} one per
5282 time. Other notifications can consume their events immediately,
5283 so queue is not needed for them. */
5284 static QUEUE (stop_reply_p) *stop_reply_queue;
5287 stop_reply_xfree (struct stop_reply *r)
5291 VEC_free (cached_reg_t, r->regcache);
5297 remote_notif_stop_parse (struct notif_client *self, char *buf,
5298 struct notif_event *event)
5300 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5304 remote_notif_stop_ack (struct notif_client *self, char *buf,
5305 struct notif_event *event)
5307 struct stop_reply *stop_reply = (struct stop_reply *) event;
5310 putpkt ((char *) self->ack_command);
5312 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5313 /* We got an unknown stop reply. */
5314 error (_("Unknown stop reply"));
5316 push_stop_reply (stop_reply);
5320 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5322 /* We can't get pending events in remote_notif_process for
5323 notification stop, and we have to do this in remote_wait_ns
5324 instead. If we fetch all queued events from stub, remote stub
5325 may exit and we have no chance to process them back in
5327 mark_async_event_handler (remote_async_inferior_event_token);
5332 stop_reply_dtr (struct notif_event *event)
5334 struct stop_reply *r = (struct stop_reply *) event;
5336 VEC_free (cached_reg_t, r->regcache);
5339 static struct notif_event *
5340 remote_notif_stop_alloc_reply (void)
5342 struct notif_event *r
5343 = (struct notif_event *) XMALLOC (struct stop_reply);
5345 r->dtr = stop_reply_dtr;
5350 /* A client of notification Stop. */
5352 struct notif_client notif_client_stop =
5356 remote_notif_stop_parse,
5357 remote_notif_stop_ack,
5358 remote_notif_stop_can_get_pending_events,
5359 remote_notif_stop_alloc_reply,
5363 /* A parameter to pass data in and out. */
5365 struct queue_iter_param
5368 struct stop_reply *output;
5371 /* Remove all queue elements meet the condition it checks. */
5374 remote_notif_remove_all (QUEUE (stop_reply_p) *q,
5375 QUEUE_ITER (stop_reply_p) *iter,
5379 struct queue_iter_param *param = data;
5380 struct inferior *inf = param->input;
5382 if (inf == NULL || ptid_get_pid (event->ptid) == inf->pid)
5384 stop_reply_xfree (event);
5385 QUEUE_remove_elem (stop_reply_p, q, iter);
5391 /* Discard all pending stop replies of inferior INF. If INF is NULL,
5392 discard everything. */
5395 discard_pending_stop_replies (struct inferior *inf)
5398 struct queue_iter_param param;
5399 struct stop_reply *reply
5400 = (struct stop_reply *) notif_client_stop.pending_event;
5402 /* Discard the in-flight notification. */
5405 || ptid_get_pid (reply->ptid) == inf->pid))
5407 stop_reply_xfree (reply);
5408 notif_client_stop.pending_event = NULL;
5412 param.output = NULL;
5413 /* Discard the stop replies we have already pulled with
5415 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5416 remote_notif_remove_all, ¶m);
5419 /* A parameter to pass data in and out. */
5422 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5423 QUEUE_ITER (stop_reply_p) *iter,
5427 struct queue_iter_param *param = data;
5428 ptid_t *ptid = param->input;
5430 if (ptid_match (event->ptid, *ptid))
5432 param->output = event;
5433 QUEUE_remove_elem (stop_reply_p, q, iter);
5440 /* Remove the first reply in 'stop_reply_queue' which matches
5443 static struct stop_reply *
5444 remote_notif_remove_queued_reply (ptid_t ptid)
5446 struct queue_iter_param param;
5448 param.input = &ptid;
5449 param.output = NULL;
5451 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5452 remote_notif_remove_once_on_match, ¶m);
5454 fprintf_unfiltered (gdb_stdlog,
5455 "notif: discard queued event: 'Stop' in %s\n",
5456 target_pid_to_str (ptid));
5458 return param.output;
5461 /* Look for a queued stop reply belonging to PTID. If one is found,
5462 remove it from the queue, and return it. Returns NULL if none is
5463 found. If there are still queued events left to process, tell the
5464 event loop to get back to target_wait soon. */
5466 static struct stop_reply *
5467 queued_stop_reply (ptid_t ptid)
5469 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5471 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5472 /* There's still at least an event left. */
5473 mark_async_event_handler (remote_async_inferior_event_token);
5478 /* Push a fully parsed stop reply in the stop reply queue. Since we
5479 know that we now have at least one queued event left to pass to the
5480 core side, tell the event loop to get back to target_wait soon. */
5483 push_stop_reply (struct stop_reply *new_event)
5485 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5488 fprintf_unfiltered (gdb_stdlog,
5489 "notif: push 'Stop' %s to queue %d\n",
5490 target_pid_to_str (new_event->ptid),
5491 QUEUE_length (stop_reply_p,
5494 mark_async_event_handler (remote_async_inferior_event_token);
5498 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5499 QUEUE_ITER (stop_reply_p) *iter,
5500 struct stop_reply *event,
5503 ptid_t *ptid = data;
5505 return !(ptid_equal (*ptid, event->ptid)
5506 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5509 /* Returns true if we have a stop reply for PTID. */
5512 peek_stop_reply (ptid_t ptid)
5514 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5515 stop_reply_match_ptid_and_ws, &ptid);
5518 /* Parse the stop reply in BUF. Either the function succeeds, and the
5519 result is stored in EVENT, or throws an error. */
5522 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5524 struct remote_arch_state *rsa = get_remote_arch_state ();
5528 event->ptid = null_ptid;
5529 event->ws.kind = TARGET_WAITKIND_IGNORE;
5530 event->ws.value.integer = 0;
5531 event->solibs_changed = 0;
5532 event->replay_event = 0;
5533 event->stopped_by_watchpoint_p = 0;
5534 event->regcache = NULL;
5539 case 'T': /* Status with PC, SP, FP, ... */
5540 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5541 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5543 n... = register number
5544 r... = register contents
5547 p = &buf[3]; /* after Txx */
5555 /* If the packet contains a register number, save it in
5556 pnum and set p1 to point to the character following it.
5557 Otherwise p1 points to p. */
5559 /* If this packet is an awatch packet, don't parse the 'a'
5560 as a register number. */
5562 if (strncmp (p, "awatch", strlen("awatch")) != 0
5563 && strncmp (p, "core", strlen ("core") != 0))
5565 /* Read the ``P'' register number. */
5566 pnum = strtol (p, &p_temp, 16);
5572 if (p1 == p) /* No register number present here. */
5574 p1 = strchr (p, ':');
5576 error (_("Malformed packet(a) (missing colon): %s\n\
5579 if (strncmp (p, "thread", p1 - p) == 0)
5580 event->ptid = read_ptid (++p1, &p);
5581 else if ((strncmp (p, "watch", p1 - p) == 0)
5582 || (strncmp (p, "rwatch", p1 - p) == 0)
5583 || (strncmp (p, "awatch", p1 - p) == 0))
5585 event->stopped_by_watchpoint_p = 1;
5586 p = unpack_varlen_hex (++p1, &addr);
5587 event->watch_data_address = (CORE_ADDR) addr;
5589 else if (strncmp (p, "library", p1 - p) == 0)
5593 while (*p_temp && *p_temp != ';')
5596 event->solibs_changed = 1;
5599 else if (strncmp (p, "replaylog", p1 - p) == 0)
5601 /* NO_HISTORY event.
5602 p1 will indicate "begin" or "end", but
5603 it makes no difference for now, so ignore it. */
5604 event->replay_event = 1;
5605 p_temp = strchr (p1 + 1, ';');
5609 else if (strncmp (p, "core", p1 - p) == 0)
5613 p = unpack_varlen_hex (++p1, &c);
5618 /* Silently skip unknown optional info. */
5619 p_temp = strchr (p1 + 1, ';');
5626 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5627 cached_reg_t cached_reg;
5632 error (_("Malformed packet(b) (missing colon): %s\n\
5638 error (_("Remote sent bad register number %s: %s\n\
5640 hex_string (pnum), p, buf);
5642 cached_reg.num = reg->regnum;
5644 fieldsize = hex2bin (p, cached_reg.data,
5645 register_size (target_gdbarch (),
5648 if (fieldsize < register_size (target_gdbarch (),
5650 warning (_("Remote reply is too short: %s"), buf);
5652 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5656 error (_("Remote register badly formatted: %s\nhere: %s"),
5661 case 'S': /* Old style status, just signal only. */
5662 if (event->solibs_changed)
5663 event->ws.kind = TARGET_WAITKIND_LOADED;
5664 else if (event->replay_event)
5665 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5668 event->ws.kind = TARGET_WAITKIND_STOPPED;
5669 event->ws.value.sig = (enum gdb_signal)
5670 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5673 case 'W': /* Target exited. */
5680 /* GDB used to accept only 2 hex chars here. Stubs should
5681 only send more if they detect GDB supports multi-process
5683 p = unpack_varlen_hex (&buf[1], &value);
5687 /* The remote process exited. */
5688 event->ws.kind = TARGET_WAITKIND_EXITED;
5689 event->ws.value.integer = value;
5693 /* The remote process exited with a signal. */
5694 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5695 event->ws.value.sig = (enum gdb_signal) value;
5698 /* If no process is specified, assume inferior_ptid. */
5699 pid = ptid_get_pid (inferior_ptid);
5708 else if (strncmp (p,
5709 "process:", sizeof ("process:") - 1) == 0)
5713 p += sizeof ("process:") - 1;
5714 unpack_varlen_hex (p, &upid);
5718 error (_("unknown stop reply packet: %s"), buf);
5721 error (_("unknown stop reply packet: %s"), buf);
5722 event->ptid = pid_to_ptid (pid);
5727 if (non_stop && ptid_equal (event->ptid, null_ptid))
5728 error (_("No process or thread specified in stop reply: %s"), buf);
5731 /* When the stub wants to tell GDB about a new notification reply, it
5732 sends a notification (%Stop, for example). Those can come it at
5733 any time, hence, we have to make sure that any pending
5734 putpkt/getpkt sequence we're making is finished, before querying
5735 the stub for more events with the corresponding ack command
5736 (vStopped, for example). E.g., if we started a vStopped sequence
5737 immediately upon receiving the notification, something like this
5745 1.6) <-- (registers reply to step #1.3)
5747 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5750 To solve this, whenever we parse a %Stop notification successfully,
5751 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5752 doing whatever we were doing:
5758 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5759 2.5) <-- (registers reply to step #2.3)
5761 Eventualy after step #2.5, we return to the event loop, which
5762 notices there's an event on the
5763 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5764 associated callback --- the function below. At this point, we're
5765 always safe to start a vStopped sequence. :
5768 2.7) <-- T05 thread:2
5774 remote_notif_get_pending_events (struct notif_client *nc)
5776 struct remote_state *rs = get_remote_state ();
5778 if (nc->pending_event)
5781 fprintf_unfiltered (gdb_stdlog,
5782 "notif: process: '%s' ack pending event\n",
5786 nc->ack (nc, rs->buf, nc->pending_event);
5787 nc->pending_event = NULL;
5791 getpkt (&rs->buf, &rs->buf_size, 0);
5792 if (strcmp (rs->buf, "OK") == 0)
5795 remote_notif_ack (nc, rs->buf);
5801 fprintf_unfiltered (gdb_stdlog,
5802 "notif: process: '%s' no pending reply\n",
5807 /* Called when it is decided that STOP_REPLY holds the info of the
5808 event that is to be returned to the core. This function always
5809 destroys STOP_REPLY. */
5812 process_stop_reply (struct stop_reply *stop_reply,
5813 struct target_waitstatus *status)
5817 *status = stop_reply->ws;
5818 ptid = stop_reply->ptid;
5820 /* If no thread/process was reported by the stub, assume the current
5822 if (ptid_equal (ptid, null_ptid))
5823 ptid = inferior_ptid;
5825 if (status->kind != TARGET_WAITKIND_EXITED
5826 && status->kind != TARGET_WAITKIND_SIGNALLED)
5828 /* Expedited registers. */
5829 if (stop_reply->regcache)
5831 struct regcache *regcache
5832 = get_thread_arch_regcache (ptid, target_gdbarch ());
5837 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5839 regcache_raw_supply (regcache, reg->num, reg->data);
5840 VEC_free (cached_reg_t, stop_reply->regcache);
5843 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5844 remote_watch_data_address = stop_reply->watch_data_address;
5846 remote_notice_new_inferior (ptid, 0);
5847 demand_private_info (ptid)->core = stop_reply->core;
5850 stop_reply_xfree (stop_reply);
5854 /* The non-stop mode version of target_wait. */
5857 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5859 struct remote_state *rs = get_remote_state ();
5860 struct stop_reply *stop_reply;
5864 /* If in non-stop mode, get out of getpkt even if a
5865 notification is received. */
5867 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5868 0 /* forever */, &is_notif);
5871 if (ret != -1 && !is_notif)
5874 case 'E': /* Error of some sort. */
5875 /* We're out of sync with the target now. Did it continue
5876 or not? We can't tell which thread it was in non-stop,
5877 so just ignore this. */
5878 warning (_("Remote failure reply: %s"), rs->buf);
5880 case 'O': /* Console output. */
5881 remote_console_output (rs->buf + 1);
5884 warning (_("Invalid remote reply: %s"), rs->buf);
5888 /* Acknowledge a pending stop reply that may have arrived in the
5890 if (notif_client_stop.pending_event != NULL)
5891 remote_notif_get_pending_events (¬if_client_stop);
5893 /* If indeed we noticed a stop reply, we're done. */
5894 stop_reply = queued_stop_reply (ptid);
5895 if (stop_reply != NULL)
5896 return process_stop_reply (stop_reply, status);
5898 /* Still no event. If we're just polling for an event, then
5899 return to the event loop. */
5900 if (options & TARGET_WNOHANG)
5902 status->kind = TARGET_WAITKIND_IGNORE;
5903 return minus_one_ptid;
5906 /* Otherwise do a blocking wait. */
5907 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5908 1 /* forever */, &is_notif);
5912 /* Wait until the remote machine stops, then return, storing status in
5913 STATUS just as `wait' would. */
5916 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5918 struct remote_state *rs = get_remote_state ();
5919 ptid_t event_ptid = null_ptid;
5921 struct stop_reply *stop_reply;
5925 status->kind = TARGET_WAITKIND_IGNORE;
5926 status->value.integer = 0;
5928 stop_reply = queued_stop_reply (ptid);
5929 if (stop_reply != NULL)
5930 return process_stop_reply (stop_reply, status);
5932 if (rs->cached_wait_status)
5933 /* Use the cached wait status, but only once. */
5934 rs->cached_wait_status = 0;
5940 if (!target_is_async_p ())
5942 ofunc = signal (SIGINT, remote_interrupt);
5943 /* If the user hit C-c before this packet, or between packets,
5944 pretend that it was hit right here. */
5945 if (check_quit_flag ())
5948 remote_interrupt (SIGINT);
5952 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5953 _never_ wait for ever -> test on target_is_async_p().
5954 However, before we do that we need to ensure that the caller
5955 knows how to take the target into/out of async mode. */
5956 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5957 wait_forever_enabled_p, &is_notif);
5959 if (!target_is_async_p ())
5960 signal (SIGINT, ofunc);
5962 /* GDB gets a notification. Return to core as this event is
5964 if (ret != -1 && is_notif)
5965 return minus_one_ptid;
5970 remote_stopped_by_watchpoint_p = 0;
5972 /* We got something. */
5973 rs->waiting_for_stop_reply = 0;
5975 /* Assume that the target has acknowledged Ctrl-C unless we receive
5976 an 'F' or 'O' packet. */
5977 if (buf[0] != 'F' && buf[0] != 'O')
5978 rs->ctrlc_pending_p = 0;
5982 case 'E': /* Error of some sort. */
5983 /* We're out of sync with the target now. Did it continue or
5984 not? Not is more likely, so report a stop. */
5985 warning (_("Remote failure reply: %s"), buf);
5986 status->kind = TARGET_WAITKIND_STOPPED;
5987 status->value.sig = GDB_SIGNAL_0;
5989 case 'F': /* File-I/O request. */
5990 remote_fileio_request (buf, rs->ctrlc_pending_p);
5991 rs->ctrlc_pending_p = 0;
5993 case 'T': case 'S': case 'X': case 'W':
5995 struct stop_reply *stop_reply
5996 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
5999 event_ptid = process_stop_reply (stop_reply, status);
6002 case 'O': /* Console output. */
6003 remote_console_output (buf + 1);
6005 /* The target didn't really stop; keep waiting. */
6006 rs->waiting_for_stop_reply = 1;
6010 if (last_sent_signal != GDB_SIGNAL_0)
6012 /* Zero length reply means that we tried 'S' or 'C' and the
6013 remote system doesn't support it. */
6014 target_terminal_ours_for_output ();
6016 ("Can't send signals to this remote system. %s not sent.\n",
6017 gdb_signal_to_name (last_sent_signal));
6018 last_sent_signal = GDB_SIGNAL_0;
6019 target_terminal_inferior ();
6021 strcpy ((char *) buf, last_sent_step ? "s" : "c");
6022 putpkt ((char *) buf);
6024 /* We just told the target to resume, so a stop reply is in
6026 rs->waiting_for_stop_reply = 1;
6029 /* else fallthrough */
6031 warning (_("Invalid remote reply: %s"), buf);
6033 rs->waiting_for_stop_reply = 1;
6037 if (status->kind == TARGET_WAITKIND_IGNORE)
6039 /* Nothing interesting happened. If we're doing a non-blocking
6040 poll, we're done. Otherwise, go back to waiting. */
6041 if (options & TARGET_WNOHANG)
6042 return minus_one_ptid;
6046 else if (status->kind != TARGET_WAITKIND_EXITED
6047 && status->kind != TARGET_WAITKIND_SIGNALLED)
6049 if (!ptid_equal (event_ptid, null_ptid))
6050 record_currthread (event_ptid);
6052 event_ptid = inferior_ptid;
6055 /* A process exit. Invalidate our notion of current thread. */
6056 record_currthread (minus_one_ptid);
6061 /* Wait until the remote machine stops, then return, storing status in
6062 STATUS just as `wait' would. */
6065 remote_wait (struct target_ops *ops,
6066 ptid_t ptid, struct target_waitstatus *status, int options)
6071 event_ptid = remote_wait_ns (ptid, status, options);
6073 event_ptid = remote_wait_as (ptid, status, options);
6075 if (target_can_async_p ())
6077 /* If there are are events left in the queue tell the event loop
6079 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6080 mark_async_event_handler (remote_async_inferior_event_token);
6086 /* Fetch a single register using a 'p' packet. */
6089 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6091 struct remote_state *rs = get_remote_state ();
6093 char regp[MAX_REGISTER_SIZE];
6096 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
6099 if (reg->pnum == -1)
6104 p += hexnumstr (p, reg->pnum);
6107 getpkt (&rs->buf, &rs->buf_size, 0);
6111 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6115 case PACKET_UNKNOWN:
6118 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6119 gdbarch_register_name (get_regcache_arch (regcache),
6124 /* If this register is unfetchable, tell the regcache. */
6127 regcache_raw_supply (regcache, reg->regnum, NULL);
6131 /* Otherwise, parse and supply the value. */
6137 error (_("fetch_register_using_p: early buf termination"));
6139 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6142 regcache_raw_supply (regcache, reg->regnum, regp);
6146 /* Fetch the registers included in the target's 'g' packet. */
6149 send_g_packet (void)
6151 struct remote_state *rs = get_remote_state ();
6154 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6155 remote_send (&rs->buf, &rs->buf_size);
6157 /* We can get out of synch in various cases. If the first character
6158 in the buffer is not a hex character, assume that has happened
6159 and try to fetch another packet to read. */
6160 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6161 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6162 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6163 && rs->buf[0] != 'x') /* New: unavailable register value. */
6166 fprintf_unfiltered (gdb_stdlog,
6167 "Bad register packet; fetching a new packet\n");
6168 getpkt (&rs->buf, &rs->buf_size, 0);
6171 buf_len = strlen (rs->buf);
6173 /* Sanity check the received packet. */
6174 if (buf_len % 2 != 0)
6175 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6181 process_g_packet (struct regcache *regcache)
6183 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6184 struct remote_state *rs = get_remote_state ();
6185 struct remote_arch_state *rsa = get_remote_arch_state ();
6190 buf_len = strlen (rs->buf);
6192 /* Further sanity checks, with knowledge of the architecture. */
6193 if (buf_len > 2 * rsa->sizeof_g_packet)
6194 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6196 /* Save the size of the packet sent to us by the target. It is used
6197 as a heuristic when determining the max size of packets that the
6198 target can safely receive. */
6199 if (rsa->actual_register_packet_size == 0)
6200 rsa->actual_register_packet_size = buf_len;
6202 /* If this is smaller than we guessed the 'g' packet would be,
6203 update our records. A 'g' reply that doesn't include a register's
6204 value implies either that the register is not available, or that
6205 the 'p' packet must be used. */
6206 if (buf_len < 2 * rsa->sizeof_g_packet)
6208 rsa->sizeof_g_packet = buf_len / 2;
6210 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6212 if (rsa->regs[i].pnum == -1)
6215 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6216 rsa->regs[i].in_g_packet = 0;
6218 rsa->regs[i].in_g_packet = 1;
6222 regs = alloca (rsa->sizeof_g_packet);
6224 /* Unimplemented registers read as all bits zero. */
6225 memset (regs, 0, rsa->sizeof_g_packet);
6227 /* Reply describes registers byte by byte, each byte encoded as two
6228 hex characters. Suck them all up, then supply them to the
6229 register cacheing/storage mechanism. */
6232 for (i = 0; i < rsa->sizeof_g_packet; i++)
6234 if (p[0] == 0 || p[1] == 0)
6235 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6236 internal_error (__FILE__, __LINE__,
6237 _("unexpected end of 'g' packet reply"));
6239 if (p[0] == 'x' && p[1] == 'x')
6240 regs[i] = 0; /* 'x' */
6242 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6246 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6248 struct packet_reg *r = &rsa->regs[i];
6252 if (r->offset * 2 >= strlen (rs->buf))
6253 /* This shouldn't happen - we adjusted in_g_packet above. */
6254 internal_error (__FILE__, __LINE__,
6255 _("unexpected end of 'g' packet reply"));
6256 else if (rs->buf[r->offset * 2] == 'x')
6258 gdb_assert (r->offset * 2 < strlen (rs->buf));
6259 /* The register isn't available, mark it as such (at
6260 the same time setting the value to zero). */
6261 regcache_raw_supply (regcache, r->regnum, NULL);
6264 regcache_raw_supply (regcache, r->regnum,
6271 fetch_registers_using_g (struct regcache *regcache)
6274 process_g_packet (regcache);
6277 /* Make the remote selected traceframe match GDB's selected
6281 set_remote_traceframe (void)
6285 if (remote_traceframe_number == get_traceframe_number ())
6288 /* Avoid recursion, remote_trace_find calls us again. */
6289 remote_traceframe_number = get_traceframe_number ();
6291 newnum = target_trace_find (tfind_number,
6292 get_traceframe_number (), 0, 0, NULL);
6294 /* Should not happen. If it does, all bets are off. */
6295 if (newnum != get_traceframe_number ())
6296 warning (_("could not set remote traceframe"));
6300 remote_fetch_registers (struct target_ops *ops,
6301 struct regcache *regcache, int regnum)
6303 struct remote_arch_state *rsa = get_remote_arch_state ();
6306 set_remote_traceframe ();
6307 set_general_thread (inferior_ptid);
6311 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6313 gdb_assert (reg != NULL);
6315 /* If this register might be in the 'g' packet, try that first -
6316 we are likely to read more than one register. If this is the
6317 first 'g' packet, we might be overly optimistic about its
6318 contents, so fall back to 'p'. */
6319 if (reg->in_g_packet)
6321 fetch_registers_using_g (regcache);
6322 if (reg->in_g_packet)
6326 if (fetch_register_using_p (regcache, reg))
6329 /* This register is not available. */
6330 regcache_raw_supply (regcache, reg->regnum, NULL);
6335 fetch_registers_using_g (regcache);
6337 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6338 if (!rsa->regs[i].in_g_packet)
6339 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6341 /* This register is not available. */
6342 regcache_raw_supply (regcache, i, NULL);
6346 /* Prepare to store registers. Since we may send them all (using a
6347 'G' request), we have to read out the ones we don't want to change
6351 remote_prepare_to_store (struct regcache *regcache)
6353 struct remote_arch_state *rsa = get_remote_arch_state ();
6355 gdb_byte buf[MAX_REGISTER_SIZE];
6357 /* Make sure the entire registers array is valid. */
6358 switch (remote_protocol_packets[PACKET_P].support)
6360 case PACKET_DISABLE:
6361 case PACKET_SUPPORT_UNKNOWN:
6362 /* Make sure all the necessary registers are cached. */
6363 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6364 if (rsa->regs[i].in_g_packet)
6365 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6372 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6373 packet was not recognized. */
6376 store_register_using_P (const struct regcache *regcache,
6377 struct packet_reg *reg)
6379 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6380 struct remote_state *rs = get_remote_state ();
6381 /* Try storing a single register. */
6382 char *buf = rs->buf;
6383 gdb_byte regp[MAX_REGISTER_SIZE];
6386 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
6389 if (reg->pnum == -1)
6392 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6393 p = buf + strlen (buf);
6394 regcache_raw_collect (regcache, reg->regnum, regp);
6395 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6397 getpkt (&rs->buf, &rs->buf_size, 0);
6399 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6404 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6405 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6406 case PACKET_UNKNOWN:
6409 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6413 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6414 contents of the register cache buffer. FIXME: ignores errors. */
6417 store_registers_using_G (const struct regcache *regcache)
6419 struct remote_state *rs = get_remote_state ();
6420 struct remote_arch_state *rsa = get_remote_arch_state ();
6424 /* Extract all the registers in the regcache copying them into a
6429 regs = alloca (rsa->sizeof_g_packet);
6430 memset (regs, 0, rsa->sizeof_g_packet);
6431 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6433 struct packet_reg *r = &rsa->regs[i];
6436 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6440 /* Command describes registers byte by byte,
6441 each byte encoded as two hex characters. */
6444 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6446 bin2hex (regs, p, rsa->sizeof_g_packet);
6448 getpkt (&rs->buf, &rs->buf_size, 0);
6449 if (packet_check_result (rs->buf) == PACKET_ERROR)
6450 error (_("Could not write registers; remote failure reply '%s'"),
6454 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6455 of the register cache buffer. FIXME: ignores errors. */
6458 remote_store_registers (struct target_ops *ops,
6459 struct regcache *regcache, int regnum)
6461 struct remote_arch_state *rsa = get_remote_arch_state ();
6464 set_remote_traceframe ();
6465 set_general_thread (inferior_ptid);
6469 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6471 gdb_assert (reg != NULL);
6473 /* Always prefer to store registers using the 'P' packet if
6474 possible; we often change only a small number of registers.
6475 Sometimes we change a larger number; we'd need help from a
6476 higher layer to know to use 'G'. */
6477 if (store_register_using_P (regcache, reg))
6480 /* For now, don't complain if we have no way to write the
6481 register. GDB loses track of unavailable registers too
6482 easily. Some day, this may be an error. We don't have
6483 any way to read the register, either... */
6484 if (!reg->in_g_packet)
6487 store_registers_using_G (regcache);
6491 store_registers_using_G (regcache);
6493 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6494 if (!rsa->regs[i].in_g_packet)
6495 if (!store_register_using_P (regcache, &rsa->regs[i]))
6496 /* See above for why we do not issue an error here. */
6501 /* Return the number of hex digits in num. */
6504 hexnumlen (ULONGEST num)
6508 for (i = 0; num != 0; i++)
6514 /* Set BUF to the minimum number of hex digits representing NUM. */
6517 hexnumstr (char *buf, ULONGEST num)
6519 int len = hexnumlen (num);
6521 return hexnumnstr (buf, num, len);
6525 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6528 hexnumnstr (char *buf, ULONGEST num, int width)
6534 for (i = width - 1; i >= 0; i--)
6536 buf[i] = "0123456789abcdef"[(num & 0xf)];
6543 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6546 remote_address_masked (CORE_ADDR addr)
6548 unsigned int address_size = remote_address_size;
6550 /* If "remoteaddresssize" was not set, default to target address size. */
6552 address_size = gdbarch_addr_bit (target_gdbarch ());
6554 if (address_size > 0
6555 && address_size < (sizeof (ULONGEST) * 8))
6557 /* Only create a mask when that mask can safely be constructed
6558 in a ULONGEST variable. */
6561 mask = (mask << address_size) - 1;
6567 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
6568 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6569 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6570 (which may be more than *OUT_LEN due to escape characters). The
6571 total number of bytes in the output buffer will be at most
6575 remote_escape_output (const gdb_byte *buffer, int len,
6576 gdb_byte *out_buf, int *out_len,
6579 int input_index, output_index;
6582 for (input_index = 0; input_index < len; input_index++)
6584 gdb_byte b = buffer[input_index];
6586 if (b == '$' || b == '#' || b == '}')
6588 /* These must be escaped. */
6589 if (output_index + 2 > out_maxlen)
6591 out_buf[output_index++] = '}';
6592 out_buf[output_index++] = b ^ 0x20;
6596 if (output_index + 1 > out_maxlen)
6598 out_buf[output_index++] = b;
6602 *out_len = input_index;
6603 return output_index;
6606 /* Convert BUFFER, escaped data LEN bytes long, into binary data
6607 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6608 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6610 This function reverses remote_escape_output. It allows more
6611 escaped characters than that function does, in particular because
6612 '*' must be escaped to avoid the run-length encoding processing
6613 in reading packets. */
6616 remote_unescape_input (const gdb_byte *buffer, int len,
6617 gdb_byte *out_buf, int out_maxlen)
6619 int input_index, output_index;
6624 for (input_index = 0; input_index < len; input_index++)
6626 gdb_byte b = buffer[input_index];
6628 if (output_index + 1 > out_maxlen)
6630 warning (_("Received too much data from remote target;"
6631 " ignoring overflow."));
6632 return output_index;
6637 out_buf[output_index++] = b ^ 0x20;
6643 out_buf[output_index++] = b;
6647 error (_("Unmatched escape character in target response."));
6649 return output_index;
6652 /* Determine whether the remote target supports binary downloading.
6653 This is accomplished by sending a no-op memory write of zero length
6654 to the target at the specified address. It does not suffice to send
6655 the whole packet, since many stubs strip the eighth bit and
6656 subsequently compute a wrong checksum, which causes real havoc with
6659 NOTE: This can still lose if the serial line is not eight-bit
6660 clean. In cases like this, the user should clear "remote
6664 check_binary_download (CORE_ADDR addr)
6666 struct remote_state *rs = get_remote_state ();
6668 switch (remote_protocol_packets[PACKET_X].support)
6670 case PACKET_DISABLE:
6674 case PACKET_SUPPORT_UNKNOWN:
6680 p += hexnumstr (p, (ULONGEST) addr);
6682 p += hexnumstr (p, (ULONGEST) 0);
6686 putpkt_binary (rs->buf, (int) (p - rs->buf));
6687 getpkt (&rs->buf, &rs->buf_size, 0);
6689 if (rs->buf[0] == '\0')
6692 fprintf_unfiltered (gdb_stdlog,
6693 "binary downloading NOT "
6694 "supported by target\n");
6695 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6700 fprintf_unfiltered (gdb_stdlog,
6701 "binary downloading supported by target\n");
6702 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6709 /* Write memory data directly to the remote machine.
6710 This does not inform the data cache; the data cache uses this.
6711 HEADER is the starting part of the packet.
6712 MEMADDR is the address in the remote memory space.
6713 MYADDR is the address of the buffer in our space.
6714 LEN is the number of bytes.
6715 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6716 should send data as binary ('X'), or hex-encoded ('M').
6718 The function creates packet of the form
6719 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6721 where encoding of <DATA> is termined by PACKET_FORMAT.
6723 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6726 Returns the number of bytes transferred, or 0 (setting errno) for
6727 error. Only transfer a single packet. */
6730 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6731 const gdb_byte *myaddr, ssize_t len,
6732 char packet_format, int use_length)
6734 struct remote_state *rs = get_remote_state ();
6744 if (packet_format != 'X' && packet_format != 'M')
6745 internal_error (__FILE__, __LINE__,
6746 _("remote_write_bytes_aux: bad packet format"));
6751 payload_size = get_memory_write_packet_size ();
6753 /* The packet buffer will be large enough for the payload;
6754 get_memory_packet_size ensures this. */
6757 /* Compute the size of the actual payload by subtracting out the
6758 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6760 payload_size -= strlen ("$,:#NN");
6762 /* The comma won't be used. */
6764 header_length = strlen (header);
6765 payload_size -= header_length;
6766 payload_size -= hexnumlen (memaddr);
6768 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6770 strcat (rs->buf, header);
6771 p = rs->buf + strlen (header);
6773 /* Compute a best guess of the number of bytes actually transfered. */
6774 if (packet_format == 'X')
6776 /* Best guess at number of bytes that will fit. */
6777 todo = min (len, payload_size);
6779 payload_size -= hexnumlen (todo);
6780 todo = min (todo, payload_size);
6784 /* Num bytes that will fit. */
6785 todo = min (len, payload_size / 2);
6787 payload_size -= hexnumlen (todo);
6788 todo = min (todo, payload_size / 2);
6792 internal_error (__FILE__, __LINE__,
6793 _("minimum packet size too small to write data"));
6795 /* If we already need another packet, then try to align the end
6796 of this packet to a useful boundary. */
6797 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6798 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6800 /* Append "<memaddr>". */
6801 memaddr = remote_address_masked (memaddr);
6802 p += hexnumstr (p, (ULONGEST) memaddr);
6809 /* Append <len>. Retain the location/size of <len>. It may need to
6810 be adjusted once the packet body has been created. */
6812 plenlen = hexnumstr (p, (ULONGEST) todo);
6820 /* Append the packet body. */
6821 if (packet_format == 'X')
6823 /* Binary mode. Send target system values byte by byte, in
6824 increasing byte addresses. Only escape certain critical
6826 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6827 &nr_bytes, payload_size);
6829 /* If not all TODO bytes fit, then we'll need another packet. Make
6830 a second try to keep the end of the packet aligned. Don't do
6831 this if the packet is tiny. */
6832 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6836 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6838 if (new_nr_bytes != nr_bytes)
6839 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6840 (gdb_byte *) p, &nr_bytes,
6844 p += payload_length;
6845 if (use_length && nr_bytes < todo)
6847 /* Escape chars have filled up the buffer prematurely,
6848 and we have actually sent fewer bytes than planned.
6849 Fix-up the length field of the packet. Use the same
6850 number of characters as before. */
6851 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6852 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6857 /* Normal mode: Send target system values byte by byte, in
6858 increasing byte addresses. Each byte is encoded as a two hex
6860 nr_bytes = bin2hex (myaddr, p, todo);
6864 putpkt_binary (rs->buf, (int) (p - rs->buf));
6865 getpkt (&rs->buf, &rs->buf_size, 0);
6867 if (rs->buf[0] == 'E')
6869 /* There is no correspondance between what the remote protocol
6870 uses for errors and errno codes. We would like a cleaner way
6871 of representing errors (big enough to include errno codes,
6872 bfd_error codes, and others). But for now just return EIO. */
6877 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6878 fewer bytes than we'd planned. */
6882 /* Write memory data directly to the remote machine.
6883 This does not inform the data cache; the data cache uses this.
6884 MEMADDR is the address in the remote memory space.
6885 MYADDR is the address of the buffer in our space.
6886 LEN is the number of bytes.
6888 Returns number of bytes transferred, or 0 (setting errno) for
6889 error. Only transfer a single packet. */
6892 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
6894 char *packet_format = 0;
6896 /* Check whether the target supports binary download. */
6897 check_binary_download (memaddr);
6899 switch (remote_protocol_packets[PACKET_X].support)
6902 packet_format = "X";
6904 case PACKET_DISABLE:
6905 packet_format = "M";
6907 case PACKET_SUPPORT_UNKNOWN:
6908 internal_error (__FILE__, __LINE__,
6909 _("remote_write_bytes: bad internal state"));
6911 internal_error (__FILE__, __LINE__, _("bad switch"));
6914 return remote_write_bytes_aux (packet_format,
6915 memaddr, myaddr, len, packet_format[0], 1);
6918 /* Read memory data directly from the remote machine.
6919 This does not use the data cache; the data cache uses this.
6920 MEMADDR is the address in the remote memory space.
6921 MYADDR is the address of the buffer in our space.
6922 LEN is the number of bytes.
6924 Returns number of bytes transferred, or 0 for error. */
6927 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6929 struct remote_state *rs = get_remote_state ();
6930 int max_buf_size; /* Max size of packet output buffer. */
6938 max_buf_size = get_memory_read_packet_size ();
6939 /* The packet buffer will be large enough for the payload;
6940 get_memory_packet_size ensures this. */
6942 /* Number if bytes that will fit. */
6943 todo = min (len, max_buf_size / 2);
6945 /* Construct "m"<memaddr>","<len>". */
6946 memaddr = remote_address_masked (memaddr);
6949 p += hexnumstr (p, (ULONGEST) memaddr);
6951 p += hexnumstr (p, (ULONGEST) todo);
6954 getpkt (&rs->buf, &rs->buf_size, 0);
6955 if (rs->buf[0] == 'E'
6956 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6957 && rs->buf[3] == '\0')
6959 /* There is no correspondance between what the remote protocol
6960 uses for errors and errno codes. We would like a cleaner way
6961 of representing errors (big enough to include errno codes,
6962 bfd_error codes, and others). But for now just return
6967 /* Reply describes memory byte by byte, each byte encoded as two hex
6970 i = hex2bin (p, myaddr, todo);
6971 /* Return what we have. Let higher layers handle partial reads. */
6976 /* Read or write LEN bytes from inferior memory at MEMADDR,
6977 transferring to or from debugger address BUFFER. Write to inferior
6978 if SHOULD_WRITE is nonzero. Returns length of data written or
6979 read; 0 for error. TARGET is unused. */
6982 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
6983 int should_write, struct mem_attrib *attrib,
6984 struct target_ops *target)
6988 set_remote_traceframe ();
6989 set_general_thread (inferior_ptid);
6992 res = remote_write_bytes (mem_addr, buffer, mem_len);
6994 res = remote_read_bytes (mem_addr, buffer, mem_len);
6999 /* Sends a packet with content determined by the printf format string
7000 FORMAT and the remaining arguments, then gets the reply. Returns
7001 whether the packet was a success, a failure, or unknown. */
7003 static enum packet_result
7004 remote_send_printf (const char *format, ...)
7006 struct remote_state *rs = get_remote_state ();
7007 int max_size = get_remote_packet_size ();
7010 va_start (ap, format);
7013 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7014 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7016 if (putpkt (rs->buf) < 0)
7017 error (_("Communication problem with target."));
7020 getpkt (&rs->buf, &rs->buf_size, 0);
7022 return packet_check_result (rs->buf);
7026 restore_remote_timeout (void *p)
7028 int value = *(int *)p;
7030 remote_timeout = value;
7033 /* Flash writing can take quite some time. We'll set
7034 effectively infinite timeout for flash operations.
7035 In future, we'll need to decide on a better approach. */
7036 static const int remote_flash_timeout = 1000;
7039 remote_flash_erase (struct target_ops *ops,
7040 ULONGEST address, LONGEST length)
7042 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7043 int saved_remote_timeout = remote_timeout;
7044 enum packet_result ret;
7045 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7046 &saved_remote_timeout);
7048 remote_timeout = remote_flash_timeout;
7050 ret = remote_send_printf ("vFlashErase:%s,%s",
7051 phex (address, addr_size),
7055 case PACKET_UNKNOWN:
7056 error (_("Remote target does not support flash erase"));
7058 error (_("Error erasing flash with vFlashErase packet"));
7063 do_cleanups (back_to);
7067 remote_flash_write (struct target_ops *ops,
7068 ULONGEST address, LONGEST length,
7069 const gdb_byte *data)
7071 int saved_remote_timeout = remote_timeout;
7073 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7074 &saved_remote_timeout);
7076 remote_timeout = remote_flash_timeout;
7077 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
7078 do_cleanups (back_to);
7084 remote_flash_done (struct target_ops *ops)
7086 int saved_remote_timeout = remote_timeout;
7088 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7089 &saved_remote_timeout);
7091 remote_timeout = remote_flash_timeout;
7092 ret = remote_send_printf ("vFlashDone");
7093 do_cleanups (back_to);
7097 case PACKET_UNKNOWN:
7098 error (_("Remote target does not support vFlashDone"));
7100 error (_("Error finishing flash operation"));
7107 remote_files_info (struct target_ops *ignore)
7109 puts_filtered ("Debugging a target over a serial line.\n");
7112 /* Stuff for dealing with the packets which are part of this protocol.
7113 See comment at top of file for details. */
7115 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7116 error to higher layers. Called when a serial error is detected.
7117 The exception message is STRING, followed by a colon and a blank,
7118 the system error message for errno at function entry and final dot
7119 for output compatibility with throw_perror_with_name. */
7122 unpush_and_perror (const char *string)
7124 int saved_errno = errno;
7126 remote_unpush_target ();
7127 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7128 safe_strerror (saved_errno));
7131 /* Read a single character from the remote end. */
7134 readchar (int timeout)
7138 ch = serial_readchar (remote_desc, timeout);
7143 switch ((enum serial_rc) ch)
7146 remote_unpush_target ();
7147 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7150 unpush_and_perror (_("Remote communication error. "
7151 "Target disconnected."));
7153 case SERIAL_TIMEOUT:
7159 /* Wrapper for serial_write that closes the target and throws if
7163 remote_serial_write (const char *str, int len)
7165 if (serial_write (remote_desc, str, len))
7167 unpush_and_perror (_("Remote communication error. "
7168 "Target disconnected."));
7172 /* Send the command in *BUF to the remote machine, and read the reply
7173 into *BUF. Report an error if we get an error reply. Resize
7174 *BUF using xrealloc if necessary to hold the result, and update
7178 remote_send (char **buf,
7182 getpkt (buf, sizeof_buf, 0);
7184 if ((*buf)[0] == 'E')
7185 error (_("Remote failure reply: %s"), *buf);
7188 /* Return a pointer to an xmalloc'ed string representing an escaped
7189 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7190 etc. The caller is responsible for releasing the returned
7194 escape_buffer (const char *buf, int n)
7196 struct cleanup *old_chain;
7197 struct ui_file *stb;
7200 stb = mem_fileopen ();
7201 old_chain = make_cleanup_ui_file_delete (stb);
7203 fputstrn_unfiltered (buf, n, 0, stb);
7204 str = ui_file_xstrdup (stb, NULL);
7205 do_cleanups (old_chain);
7209 /* Display a null-terminated packet on stdout, for debugging, using C
7213 print_packet (char *buf)
7215 puts_filtered ("\"");
7216 fputstr_filtered (buf, '"', gdb_stdout);
7217 puts_filtered ("\"");
7223 return putpkt_binary (buf, strlen (buf));
7226 /* Send a packet to the remote machine, with error checking. The data
7227 of the packet is in BUF. The string in BUF can be at most
7228 get_remote_packet_size () - 5 to account for the $, # and checksum,
7229 and for a possible /0 if we are debugging (remote_debug) and want
7230 to print the sent packet as a string. */
7233 putpkt_binary (char *buf, int cnt)
7235 struct remote_state *rs = get_remote_state ();
7237 unsigned char csum = 0;
7238 char *buf2 = alloca (cnt + 6);
7245 /* Catch cases like trying to read memory or listing threads while
7246 we're waiting for a stop reply. The remote server wouldn't be
7247 ready to handle this request, so we'd hang and timeout. We don't
7248 have to worry about this in synchronous mode, because in that
7249 case it's not possible to issue a command while the target is
7250 running. This is not a problem in non-stop mode, because in that
7251 case, the stub is always ready to process serial input. */
7252 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
7253 error (_("Cannot execute this command while the target is running."));
7255 /* We're sending out a new packet. Make sure we don't look at a
7256 stale cached response. */
7257 rs->cached_wait_status = 0;
7259 /* Copy the packet into buffer BUF2, encapsulating it
7260 and giving it a checksum. */
7265 for (i = 0; i < cnt; i++)
7271 *p++ = tohex ((csum >> 4) & 0xf);
7272 *p++ = tohex (csum & 0xf);
7274 /* Send it over and over until we get a positive ack. */
7278 int started_error_output = 0;
7282 struct cleanup *old_chain;
7286 str = escape_buffer (buf2, p - buf2);
7287 old_chain = make_cleanup (xfree, str);
7288 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7289 gdb_flush (gdb_stdlog);
7290 do_cleanups (old_chain);
7292 remote_serial_write (buf2, p - buf2);
7294 /* If this is a no acks version of the remote protocol, send the
7295 packet and move on. */
7299 /* Read until either a timeout occurs (-2) or '+' is read.
7300 Handle any notification that arrives in the mean time. */
7303 ch = readchar (remote_timeout);
7311 case SERIAL_TIMEOUT:
7314 if (started_error_output)
7316 putchar_unfiltered ('\n');
7317 started_error_output = 0;
7326 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7330 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7332 case SERIAL_TIMEOUT:
7336 break; /* Retransmit buffer. */
7340 fprintf_unfiltered (gdb_stdlog,
7341 "Packet instead of Ack, ignoring it\n");
7342 /* It's probably an old response sent because an ACK
7343 was lost. Gobble up the packet and ack it so it
7344 doesn't get retransmitted when we resend this
7347 remote_serial_write ("+", 1);
7348 continue; /* Now, go look for +. */
7355 /* If we got a notification, handle it, and go back to looking
7357 /* We've found the start of a notification. Now
7358 collect the data. */
7359 val = read_frame (&rs->buf, &rs->buf_size);
7364 struct cleanup *old_chain;
7367 str = escape_buffer (rs->buf, val);
7368 old_chain = make_cleanup (xfree, str);
7369 fprintf_unfiltered (gdb_stdlog,
7370 " Notification received: %s\n",
7372 do_cleanups (old_chain);
7374 handle_notification (rs->buf);
7375 /* We're in sync now, rewait for the ack. */
7382 if (!started_error_output)
7384 started_error_output = 1;
7385 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7387 fputc_unfiltered (ch & 0177, gdb_stdlog);
7388 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7397 if (!started_error_output)
7399 started_error_output = 1;
7400 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7402 fputc_unfiltered (ch & 0177, gdb_stdlog);
7406 break; /* Here to retransmit. */
7410 /* This is wrong. If doing a long backtrace, the user should be
7411 able to get out next time we call QUIT, without anything as
7412 violent as interrupt_query. If we want to provide a way out of
7413 here without getting to the next QUIT, it should be based on
7414 hitting ^C twice as in remote_wait. */
7425 /* Come here after finding the start of a frame when we expected an
7426 ack. Do our best to discard the rest of this packet. */
7435 c = readchar (remote_timeout);
7438 case SERIAL_TIMEOUT:
7439 /* Nothing we can do. */
7442 /* Discard the two bytes of checksum and stop. */
7443 c = readchar (remote_timeout);
7445 c = readchar (remote_timeout);
7448 case '*': /* Run length encoding. */
7449 /* Discard the repeat count. */
7450 c = readchar (remote_timeout);
7455 /* A regular character. */
7461 /* Come here after finding the start of the frame. Collect the rest
7462 into *BUF, verifying the checksum, length, and handling run-length
7463 compression. NUL terminate the buffer. If there is not enough room,
7464 expand *BUF using xrealloc.
7466 Returns -1 on error, number of characters in buffer (ignoring the
7467 trailing NULL) on success. (could be extended to return one of the
7468 SERIAL status indications). */
7471 read_frame (char **buf_p,
7478 struct remote_state *rs = get_remote_state ();
7485 c = readchar (remote_timeout);
7488 case SERIAL_TIMEOUT:
7490 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7494 fputs_filtered ("Saw new packet start in middle of old one\n",
7496 return -1; /* Start a new packet, count retries. */
7499 unsigned char pktcsum;
7505 check_0 = readchar (remote_timeout);
7507 check_1 = readchar (remote_timeout);
7509 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7512 fputs_filtered ("Timeout in checksum, retrying\n",
7516 else if (check_0 < 0 || check_1 < 0)
7519 fputs_filtered ("Communication error in checksum\n",
7524 /* Don't recompute the checksum; with no ack packets we
7525 don't have any way to indicate a packet retransmission
7530 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7531 if (csum == pktcsum)
7536 struct cleanup *old_chain;
7539 str = escape_buffer (buf, bc);
7540 old_chain = make_cleanup (xfree, str);
7541 fprintf_unfiltered (gdb_stdlog,
7542 "Bad checksum, sentsum=0x%x, "
7543 "csum=0x%x, buf=%s\n",
7544 pktcsum, csum, str);
7545 do_cleanups (old_chain);
7547 /* Number of characters in buffer ignoring trailing
7551 case '*': /* Run length encoding. */
7556 c = readchar (remote_timeout);
7558 repeat = c - ' ' + 3; /* Compute repeat count. */
7560 /* The character before ``*'' is repeated. */
7562 if (repeat > 0 && repeat <= 255 && bc > 0)
7564 if (bc + repeat - 1 >= *sizeof_buf - 1)
7566 /* Make some more room in the buffer. */
7567 *sizeof_buf += repeat;
7568 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7572 memset (&buf[bc], buf[bc - 1], repeat);
7578 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7582 if (bc >= *sizeof_buf - 1)
7584 /* Make some more room in the buffer. */
7586 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7597 /* Read a packet from the remote machine, with error checking, and
7598 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7599 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7600 rather than timing out; this is used (in synchronous mode) to wait
7601 for a target that is is executing user code to stop. */
7602 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7603 don't have to change all the calls to getpkt to deal with the
7604 return value, because at the moment I don't know what the right
7605 thing to do it for those. */
7613 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7617 /* Read a packet from the remote machine, with error checking, and
7618 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7619 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7620 rather than timing out; this is used (in synchronous mode) to wait
7621 for a target that is is executing user code to stop. If FOREVER ==
7622 0, this function is allowed to time out gracefully and return an
7623 indication of this to the caller. Otherwise return the number of
7624 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7625 enough reason to return to the caller. *IS_NOTIF is an output
7626 boolean that indicates whether *BUF holds a notification or not
7627 (a regular packet). */
7630 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7631 int expecting_notif, int *is_notif)
7633 struct remote_state *rs = get_remote_state ();
7639 /* We're reading a new response. Make sure we don't look at a
7640 previously cached response. */
7641 rs->cached_wait_status = 0;
7643 strcpy (*buf, "timeout");
7646 timeout = watchdog > 0 ? watchdog : -1;
7647 else if (expecting_notif)
7648 timeout = 0; /* There should already be a char in the buffer. If
7651 timeout = remote_timeout;
7655 /* Process any number of notifications, and then return when
7659 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7661 for (tries = 1; tries <= MAX_TRIES; tries++)
7663 /* This can loop forever if the remote side sends us
7664 characters continuously, but if it pauses, we'll get
7665 SERIAL_TIMEOUT from readchar because of timeout. Then
7666 we'll count that as a retry.
7668 Note that even when forever is set, we will only wait
7669 forever prior to the start of a packet. After that, we
7670 expect characters to arrive at a brisk pace. They should
7671 show up within remote_timeout intervals. */
7673 c = readchar (timeout);
7674 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7676 if (c == SERIAL_TIMEOUT)
7678 if (expecting_notif)
7679 return -1; /* Don't complain, it's normal to not get
7680 anything in this case. */
7682 if (forever) /* Watchdog went off? Kill the target. */
7685 remote_unpush_target ();
7686 throw_error (TARGET_CLOSE_ERROR,
7687 _("Watchdog timeout has expired. "
7688 "Target detached."));
7691 fputs_filtered ("Timed out.\n", gdb_stdlog);
7695 /* We've found the start of a packet or notification.
7696 Now collect the data. */
7697 val = read_frame (buf, sizeof_buf);
7702 remote_serial_write ("-", 1);
7705 if (tries > MAX_TRIES)
7707 /* We have tried hard enough, and just can't receive the
7708 packet/notification. Give up. */
7709 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7711 /* Skip the ack char if we're in no-ack mode. */
7712 if (!rs->noack_mode)
7713 remote_serial_write ("+", 1);
7717 /* If we got an ordinary packet, return that to our caller. */
7722 struct cleanup *old_chain;
7725 str = escape_buffer (*buf, val);
7726 old_chain = make_cleanup (xfree, str);
7727 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7728 do_cleanups (old_chain);
7731 /* Skip the ack char if we're in no-ack mode. */
7732 if (!rs->noack_mode)
7733 remote_serial_write ("+", 1);
7734 if (is_notif != NULL)
7739 /* If we got a notification, handle it, and go back to looking
7743 gdb_assert (c == '%');
7747 struct cleanup *old_chain;
7750 str = escape_buffer (*buf, val);
7751 old_chain = make_cleanup (xfree, str);
7752 fprintf_unfiltered (gdb_stdlog,
7753 " Notification received: %s\n",
7755 do_cleanups (old_chain);
7757 if (is_notif != NULL)
7760 handle_notification (*buf);
7762 /* Notifications require no acknowledgement. */
7764 if (expecting_notif)
7771 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7773 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7777 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7780 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7785 /* A helper function that just calls putpkt; for type correctness. */
7788 putpkt_for_catch_errors (void *arg)
7790 return putpkt (arg);
7794 remote_kill (struct target_ops *ops)
7796 /* Use catch_errors so the user can quit from gdb even when we
7797 aren't on speaking terms with the remote system. */
7798 catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
7800 /* Don't wait for it to die. I'm not really sure it matters whether
7801 we do or not. For the existing stubs, kill is a noop. */
7802 target_mourn_inferior ();
7806 remote_vkill (int pid, struct remote_state *rs)
7808 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7811 /* Tell the remote target to detach. */
7812 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7814 getpkt (&rs->buf, &rs->buf_size, 0);
7816 if (packet_ok (rs->buf,
7817 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7819 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7826 extended_remote_kill (struct target_ops *ops)
7829 int pid = ptid_get_pid (inferior_ptid);
7830 struct remote_state *rs = get_remote_state ();
7832 res = remote_vkill (pid, rs);
7833 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7835 /* Don't try 'k' on a multi-process aware stub -- it has no way
7836 to specify the pid. */
7840 getpkt (&rs->buf, &rs->buf_size, 0);
7841 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7844 /* Don't wait for it to die. I'm not really sure it matters whether
7845 we do or not. For the existing stubs, kill is a noop. */
7851 error (_("Can't kill process"));
7853 target_mourn_inferior ();
7857 remote_mourn (struct target_ops *ops)
7859 remote_mourn_1 (ops);
7862 /* Worker function for remote_mourn. */
7864 remote_mourn_1 (struct target_ops *target)
7866 unpush_target (target);
7868 /* remote_close takes care of doing most of the clean up. */
7869 generic_mourn_inferior ();
7873 extended_remote_mourn_1 (struct target_ops *target)
7875 struct remote_state *rs = get_remote_state ();
7877 /* In case we got here due to an error, but we're going to stay
7879 rs->waiting_for_stop_reply = 0;
7881 /* If the current general thread belonged to the process we just
7882 detached from or has exited, the remote side current general
7883 thread becomes undefined. Considering a case like this:
7885 - We just got here due to a detach.
7886 - The process that we're detaching from happens to immediately
7887 report a global breakpoint being hit in non-stop mode, in the
7888 same thread we had selected before.
7889 - GDB attaches to this process again.
7890 - This event happens to be the next event we handle.
7892 GDB would consider that the current general thread didn't need to
7893 be set on the stub side (with Hg), since for all it knew,
7894 GENERAL_THREAD hadn't changed.
7896 Notice that although in all-stop mode, the remote server always
7897 sets the current thread to the thread reporting the stop event,
7898 that doesn't happen in non-stop mode; in non-stop, the stub *must
7899 not* change the current thread when reporting a breakpoint hit,
7900 due to the decoupling of event reporting and event handling.
7902 To keep things simple, we always invalidate our notion of the
7904 record_currthread (minus_one_ptid);
7906 /* Unlike "target remote", we do not want to unpush the target; then
7907 the next time the user says "run", we won't be connected. */
7909 /* Call common code to mark the inferior as not running. */
7910 generic_mourn_inferior ();
7912 if (!have_inferiors ())
7914 if (!remote_multi_process_p (rs))
7916 /* Check whether the target is running now - some remote stubs
7917 automatically restart after kill. */
7919 getpkt (&rs->buf, &rs->buf_size, 0);
7921 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7923 /* Assume that the target has been restarted. Set
7924 inferior_ptid so that bits of core GDB realizes
7925 there's something here, e.g., so that the user can
7926 say "kill" again. */
7927 inferior_ptid = magic_null_ptid;
7934 extended_remote_mourn (struct target_ops *ops)
7936 extended_remote_mourn_1 (ops);
7940 extended_remote_supports_disable_randomization (void)
7942 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7947 extended_remote_disable_randomization (int val)
7949 struct remote_state *rs = get_remote_state ();
7952 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7955 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7957 error (_("Target does not support QDisableRandomization."));
7958 if (strcmp (reply, "OK") != 0)
7959 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7963 extended_remote_run (char *args)
7965 struct remote_state *rs = get_remote_state ();
7968 /* If the user has disabled vRun support, or we have detected that
7969 support is not available, do not try it. */
7970 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7973 strcpy (rs->buf, "vRun;");
7974 len = strlen (rs->buf);
7976 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7977 error (_("Remote file name too long for run packet"));
7978 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7980 gdb_assert (args != NULL);
7983 struct cleanup *back_to;
7987 argv = gdb_buildargv (args);
7988 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7989 for (i = 0; argv[i] != NULL; i++)
7991 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7992 error (_("Argument list too long for run packet"));
7993 rs->buf[len++] = ';';
7994 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7996 do_cleanups (back_to);
7999 rs->buf[len++] = '\0';
8002 getpkt (&rs->buf, &rs->buf_size, 0);
8004 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
8006 /* We have a wait response. All is well. */
8009 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
8010 /* It wasn't disabled before, but it is now. */
8014 if (remote_exec_file[0] == '\0')
8015 error (_("Running the default executable on the remote target failed; "
8016 "try \"set remote exec-file\"?"));
8018 error (_("Running \"%s\" on the remote target failed"),
8023 /* In the extended protocol we want to be able to do things like
8024 "run" and have them basically work as expected. So we need
8025 a special create_inferior function. We support changing the
8026 executable file and the command line arguments, but not the
8030 extended_remote_create_inferior_1 (char *exec_file, char *args,
8031 char **env, int from_tty)
8035 struct remote_state *rs = get_remote_state ();
8037 /* If running asynchronously, register the target file descriptor
8038 with the event loop. */
8039 if (target_can_async_p ())
8040 target_async (inferior_event_handler, 0);
8042 /* Disable address space randomization if requested (and supported). */
8043 if (extended_remote_supports_disable_randomization ())
8044 extended_remote_disable_randomization (disable_randomization);
8046 /* Now restart the remote server. */
8047 run_worked = extended_remote_run (args) != -1;
8050 /* vRun was not supported. Fail if we need it to do what the
8052 if (remote_exec_file[0])
8053 error (_("Remote target does not support \"set remote exec-file\""));
8055 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8057 /* Fall back to "R". */
8058 extended_remote_restart ();
8061 if (!have_inferiors ())
8063 /* Clean up from the last time we ran, before we mark the target
8064 running again. This will mark breakpoints uninserted, and
8065 get_offsets may insert breakpoints. */
8066 init_thread_list ();
8067 init_wait_for_inferior ();
8070 /* vRun's success return is a stop reply. */
8071 stop_reply = run_worked ? rs->buf : NULL;
8072 add_current_inferior_and_thread (stop_reply);
8074 /* Get updated offsets, if the stub uses qOffsets. */
8079 extended_remote_create_inferior (struct target_ops *ops,
8080 char *exec_file, char *args,
8081 char **env, int from_tty)
8083 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
8087 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8088 the list of conditions (in agent expression bytecode format), if any, the
8089 target needs to evaluate. The output is placed into the packet buffer
8090 started from BUF and ended at BUF_END. */
8093 remote_add_target_side_condition (struct gdbarch *gdbarch,
8094 struct bp_target_info *bp_tgt, char *buf,
8097 struct agent_expr *aexpr = NULL;
8100 char *buf_start = buf;
8102 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8105 buf += strlen (buf);
8106 xsnprintf (buf, buf_end - buf, "%s", ";");
8109 /* Send conditions to the target and free the vector. */
8111 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8114 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8115 buf += strlen (buf);
8116 for (i = 0; i < aexpr->len; ++i)
8117 buf = pack_hex_byte (buf, aexpr->buf[i]);
8121 VEC_free (agent_expr_p, bp_tgt->conditions);
8126 remote_add_target_side_commands (struct gdbarch *gdbarch,
8127 struct bp_target_info *bp_tgt, char *buf)
8129 struct agent_expr *aexpr = NULL;
8132 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8135 buf += strlen (buf);
8137 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8138 buf += strlen (buf);
8140 /* Concatenate all the agent expressions that are commands into the
8143 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8146 sprintf (buf, "X%x,", aexpr->len);
8147 buf += strlen (buf);
8148 for (i = 0; i < aexpr->len; ++i)
8149 buf = pack_hex_byte (buf, aexpr->buf[i]);
8153 VEC_free (agent_expr_p, bp_tgt->tcommands);
8156 /* Insert a breakpoint. On targets that have software breakpoint
8157 support, we ask the remote target to do the work; on targets
8158 which don't, we insert a traditional memory breakpoint. */
8161 remote_insert_breakpoint (struct gdbarch *gdbarch,
8162 struct bp_target_info *bp_tgt)
8164 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8165 If it succeeds, then set the support to PACKET_ENABLE. If it
8166 fails, and the user has explicitly requested the Z support then
8167 report an error, otherwise, mark it disabled and go on. */
8169 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8171 CORE_ADDR addr = bp_tgt->placed_address;
8172 struct remote_state *rs;
8175 struct condition_list *cond = NULL;
8177 /* Make sure the remote is pointing at the right process, if
8179 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8180 set_general_process ();
8182 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8184 rs = get_remote_state ();
8186 endbuf = rs->buf + get_remote_packet_size ();
8191 addr = (ULONGEST) remote_address_masked (addr);
8192 p += hexnumstr (p, addr);
8193 xsnprintf (p, endbuf - p, ",%d", bpsize);
8195 if (remote_supports_cond_breakpoints ())
8196 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8198 if (remote_can_run_breakpoint_commands ())
8199 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8202 getpkt (&rs->buf, &rs->buf_size, 0);
8204 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8209 bp_tgt->placed_address = addr;
8210 bp_tgt->placed_size = bpsize;
8212 case PACKET_UNKNOWN:
8217 return memory_insert_breakpoint (gdbarch, bp_tgt);
8221 remote_remove_breakpoint (struct gdbarch *gdbarch,
8222 struct bp_target_info *bp_tgt)
8224 CORE_ADDR addr = bp_tgt->placed_address;
8225 struct remote_state *rs = get_remote_state ();
8227 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8230 char *endbuf = rs->buf + get_remote_packet_size ();
8232 /* Make sure the remote is pointing at the right process, if
8234 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8235 set_general_process ();
8241 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8242 p += hexnumstr (p, addr);
8243 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8246 getpkt (&rs->buf, &rs->buf_size, 0);
8248 return (rs->buf[0] == 'E');
8251 return memory_remove_breakpoint (gdbarch, bp_tgt);
8255 watchpoint_to_Z_packet (int type)
8260 return Z_PACKET_WRITE_WP;
8263 return Z_PACKET_READ_WP;
8266 return Z_PACKET_ACCESS_WP;
8269 internal_error (__FILE__, __LINE__,
8270 _("hw_bp_to_z: bad watchpoint type %d"), type);
8275 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
8276 struct expression *cond)
8278 struct remote_state *rs = get_remote_state ();
8279 char *endbuf = rs->buf + get_remote_packet_size ();
8281 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8283 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8286 /* Make sure the remote is pointing at the right process, if
8288 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8289 set_general_process ();
8291 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8292 p = strchr (rs->buf, '\0');
8293 addr = remote_address_masked (addr);
8294 p += hexnumstr (p, (ULONGEST) addr);
8295 xsnprintf (p, endbuf - p, ",%x", len);
8298 getpkt (&rs->buf, &rs->buf_size, 0);
8300 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8304 case PACKET_UNKNOWN:
8309 internal_error (__FILE__, __LINE__,
8310 _("remote_insert_watchpoint: reached end of function"));
8314 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8315 CORE_ADDR start, int length)
8317 CORE_ADDR diff = remote_address_masked (addr - start);
8319 return diff < length;
8324 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
8325 struct expression *cond)
8327 struct remote_state *rs = get_remote_state ();
8328 char *endbuf = rs->buf + get_remote_packet_size ();
8330 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8332 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8335 /* Make sure the remote is pointing at the right process, if
8337 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8338 set_general_process ();
8340 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8341 p = strchr (rs->buf, '\0');
8342 addr = remote_address_masked (addr);
8343 p += hexnumstr (p, (ULONGEST) addr);
8344 xsnprintf (p, endbuf - p, ",%x", len);
8346 getpkt (&rs->buf, &rs->buf_size, 0);
8348 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8351 case PACKET_UNKNOWN:
8356 internal_error (__FILE__, __LINE__,
8357 _("remote_remove_watchpoint: reached end of function"));
8361 int remote_hw_watchpoint_limit = -1;
8362 int remote_hw_watchpoint_length_limit = -1;
8363 int remote_hw_breakpoint_limit = -1;
8366 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
8368 if (remote_hw_watchpoint_length_limit == 0)
8370 else if (remote_hw_watchpoint_length_limit < 0)
8372 else if (len <= remote_hw_watchpoint_length_limit)
8379 remote_check_watch_resources (int type, int cnt, int ot)
8381 if (type == bp_hardware_breakpoint)
8383 if (remote_hw_breakpoint_limit == 0)
8385 else if (remote_hw_breakpoint_limit < 0)
8387 else if (cnt <= remote_hw_breakpoint_limit)
8392 if (remote_hw_watchpoint_limit == 0)
8394 else if (remote_hw_watchpoint_limit < 0)
8398 else if (cnt <= remote_hw_watchpoint_limit)
8405 remote_stopped_by_watchpoint (void)
8407 return remote_stopped_by_watchpoint_p;
8411 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8415 if (remote_stopped_by_watchpoint ())
8417 *addr_p = remote_watch_data_address;
8426 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
8427 struct bp_target_info *bp_tgt)
8430 struct remote_state *rs;
8434 /* The length field should be set to the size of a breakpoint
8435 instruction, even though we aren't inserting one ourselves. */
8437 gdbarch_remote_breakpoint_from_pc
8438 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
8440 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8443 /* Make sure the remote is pointing at the right process, if
8445 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8446 set_general_process ();
8448 rs = get_remote_state ();
8450 endbuf = rs->buf + get_remote_packet_size ();
8456 addr = remote_address_masked (bp_tgt->placed_address);
8457 p += hexnumstr (p, (ULONGEST) addr);
8458 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8460 if (remote_supports_cond_breakpoints ())
8461 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8463 if (remote_can_run_breakpoint_commands ())
8464 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8467 getpkt (&rs->buf, &rs->buf_size, 0);
8469 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8472 if (rs->buf[1] == '.')
8474 message = strchr (rs->buf + 2, '.');
8476 error (_("Remote failure reply: %s"), message + 1);
8479 case PACKET_UNKNOWN:
8484 internal_error (__FILE__, __LINE__,
8485 _("remote_insert_hw_breakpoint: reached end of function"));
8490 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
8491 struct bp_target_info *bp_tgt)
8494 struct remote_state *rs = get_remote_state ();
8496 char *endbuf = rs->buf + get_remote_packet_size ();
8498 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8501 /* Make sure the remote is pointing at the right process, if
8503 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8504 set_general_process ();
8510 addr = remote_address_masked (bp_tgt->placed_address);
8511 p += hexnumstr (p, (ULONGEST) addr);
8512 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8515 getpkt (&rs->buf, &rs->buf_size, 0);
8517 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8520 case PACKET_UNKNOWN:
8525 internal_error (__FILE__, __LINE__,
8526 _("remote_remove_hw_breakpoint: reached end of function"));
8529 /* Table used by the crc32 function to calcuate the checksum. */
8531 static unsigned long crc32_table[256] =
8534 static unsigned long
8535 crc32 (const unsigned char *buf, int len, unsigned int crc)
8537 if (!crc32_table[1])
8539 /* Initialize the CRC table and the decoding table. */
8543 for (i = 0; i < 256; i++)
8545 for (c = i << 24, j = 8; j > 0; --j)
8546 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
8553 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
8559 /* Verify memory using the "qCRC:" request. */
8562 remote_verify_memory (struct target_ops *ops,
8563 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8565 struct remote_state *rs = get_remote_state ();
8566 unsigned long host_crc, target_crc;
8569 /* Make sure the remote is pointing at the right process. */
8570 set_general_process ();
8572 /* FIXME: assumes lma can fit into long. */
8573 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8574 (long) lma, (long) size);
8577 /* Be clever; compute the host_crc before waiting for target
8579 host_crc = crc32 (data, size, 0xffffffff);
8581 getpkt (&rs->buf, &rs->buf_size, 0);
8582 if (rs->buf[0] == 'E')
8585 if (rs->buf[0] != 'C')
8586 error (_("remote target does not support this operation"));
8588 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8589 target_crc = target_crc * 16 + fromhex (*tmp);
8591 return (host_crc == target_crc);
8594 /* compare-sections command
8596 With no arguments, compares each loadable section in the exec bfd
8597 with the same memory range on the target, and reports mismatches.
8598 Useful for verifying the image on the target against the exec file. */
8601 compare_sections_command (char *args, int from_tty)
8604 struct cleanup *old_chain;
8606 const char *sectname;
8614 error (_("command cannot be used without an exec file"));
8616 /* Make sure the remote is pointing at the right process. */
8617 set_general_process ();
8619 for (s = exec_bfd->sections; s; s = s->next)
8621 if (!(s->flags & SEC_LOAD))
8622 continue; /* Skip non-loadable section. */
8624 size = bfd_get_section_size (s);
8626 continue; /* Skip zero-length section. */
8628 sectname = bfd_get_section_name (exec_bfd, s);
8629 if (args && strcmp (args, sectname) != 0)
8630 continue; /* Not the section selected by user. */
8632 matched = 1; /* Do this section. */
8635 sectdata = xmalloc (size);
8636 old_chain = make_cleanup (xfree, sectdata);
8637 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8639 res = target_verify_memory (sectdata, lma, size);
8642 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8643 paddress (target_gdbarch (), lma),
8644 paddress (target_gdbarch (), lma + size));
8646 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8647 paddress (target_gdbarch (), lma),
8648 paddress (target_gdbarch (), lma + size));
8650 printf_filtered ("matched.\n");
8653 printf_filtered ("MIS-MATCHED!\n");
8657 do_cleanups (old_chain);
8660 warning (_("One or more sections of the remote executable does not match\n\
8661 the loaded file\n"));
8662 if (args && !matched)
8663 printf_filtered (_("No loaded section named '%s'.\n"), args);
8666 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8667 into remote target. The number of bytes written to the remote
8668 target is returned, or -1 for error. */
8671 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8672 const char *annex, const gdb_byte *writebuf,
8673 ULONGEST offset, LONGEST len,
8674 struct packet_config *packet)
8678 struct remote_state *rs = get_remote_state ();
8679 int max_size = get_memory_write_packet_size ();
8681 if (packet->support == PACKET_DISABLE)
8684 /* Insert header. */
8685 i = snprintf (rs->buf, max_size,
8686 "qXfer:%s:write:%s:%s:",
8687 object_name, annex ? annex : "",
8688 phex_nz (offset, sizeof offset));
8689 max_size -= (i + 1);
8691 /* Escape as much data as fits into rs->buf. */
8692 buf_len = remote_escape_output
8693 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8695 if (putpkt_binary (rs->buf, i + buf_len) < 0
8696 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8697 || packet_ok (rs->buf, packet) != PACKET_OK)
8700 unpack_varlen_hex (rs->buf, &n);
8704 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8705 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8706 number of bytes read is returned, or 0 for EOF, or -1 for error.
8707 The number of bytes read may be less than LEN without indicating an
8708 EOF. PACKET is checked and updated to indicate whether the remote
8709 target supports this object. */
8712 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8714 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8715 struct packet_config *packet)
8717 static char *finished_object;
8718 static char *finished_annex;
8719 static ULONGEST finished_offset;
8721 struct remote_state *rs = get_remote_state ();
8722 LONGEST i, n, packet_len;
8724 if (packet->support == PACKET_DISABLE)
8727 /* Check whether we've cached an end-of-object packet that matches
8729 if (finished_object)
8731 if (strcmp (object_name, finished_object) == 0
8732 && strcmp (annex ? annex : "", finished_annex) == 0
8733 && offset == finished_offset)
8736 /* Otherwise, we're now reading something different. Discard
8738 xfree (finished_object);
8739 xfree (finished_annex);
8740 finished_object = NULL;
8741 finished_annex = NULL;
8744 /* Request only enough to fit in a single packet. The actual data
8745 may not, since we don't know how much of it will need to be escaped;
8746 the target is free to respond with slightly less data. We subtract
8747 five to account for the response type and the protocol frame. */
8748 n = min (get_remote_packet_size () - 5, len);
8749 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8750 object_name, annex ? annex : "",
8751 phex_nz (offset, sizeof offset),
8752 phex_nz (n, sizeof n));
8753 i = putpkt (rs->buf);
8758 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8759 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8762 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8763 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8765 /* 'm' means there is (or at least might be) more data after this
8766 batch. That does not make sense unless there's at least one byte
8767 of data in this reply. */
8768 if (rs->buf[0] == 'm' && packet_len == 1)
8769 error (_("Remote qXfer reply contained no data."));
8771 /* Got some data. */
8772 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8773 packet_len - 1, readbuf, n);
8775 /* 'l' is an EOF marker, possibly including a final block of data,
8776 or possibly empty. If we have the final block of a non-empty
8777 object, record this fact to bypass a subsequent partial read. */
8778 if (rs->buf[0] == 'l' && offset + i > 0)
8780 finished_object = xstrdup (object_name);
8781 finished_annex = xstrdup (annex ? annex : "");
8782 finished_offset = offset + i;
8789 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8790 const char *annex, gdb_byte *readbuf,
8791 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
8793 struct remote_state *rs;
8798 set_remote_traceframe ();
8799 set_general_thread (inferior_ptid);
8801 rs = get_remote_state ();
8803 /* Handle memory using the standard memory routines. */
8804 if (object == TARGET_OBJECT_MEMORY)
8810 /* If the remote target is connected but not running, we should
8811 pass this request down to a lower stratum (e.g. the executable
8813 if (!target_has_execution)
8816 if (writebuf != NULL)
8817 xfered = remote_write_bytes (offset, writebuf, len);
8819 xfered = remote_read_bytes (offset, readbuf, len);
8823 else if (xfered == 0 && errno == 0)
8829 /* Handle SPU memory using qxfer packets. */
8830 if (object == TARGET_OBJECT_SPU)
8833 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8834 &remote_protocol_packets
8835 [PACKET_qXfer_spu_read]);
8837 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8838 &remote_protocol_packets
8839 [PACKET_qXfer_spu_write]);
8842 /* Handle extra signal info using qxfer packets. */
8843 if (object == TARGET_OBJECT_SIGNAL_INFO)
8846 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8847 &remote_protocol_packets
8848 [PACKET_qXfer_siginfo_read]);
8850 return remote_write_qxfer (ops, "siginfo", annex,
8851 writebuf, offset, len,
8852 &remote_protocol_packets
8853 [PACKET_qXfer_siginfo_write]);
8856 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8859 return remote_read_qxfer (ops, "statictrace", annex,
8860 readbuf, offset, len,
8861 &remote_protocol_packets
8862 [PACKET_qXfer_statictrace_read]);
8867 /* Only handle flash writes. */
8868 if (writebuf != NULL)
8874 case TARGET_OBJECT_FLASH:
8875 xfered = remote_flash_write (ops, offset, len, writebuf);
8879 else if (xfered == 0 && errno == 0)
8889 /* Map pre-existing objects onto letters. DO NOT do this for new
8890 objects!!! Instead specify new query packets. */
8893 case TARGET_OBJECT_AVR:
8897 case TARGET_OBJECT_AUXV:
8898 gdb_assert (annex == NULL);
8899 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8900 &remote_protocol_packets[PACKET_qXfer_auxv]);
8902 case TARGET_OBJECT_AVAILABLE_FEATURES:
8903 return remote_read_qxfer
8904 (ops, "features", annex, readbuf, offset, len,
8905 &remote_protocol_packets[PACKET_qXfer_features]);
8907 case TARGET_OBJECT_LIBRARIES:
8908 return remote_read_qxfer
8909 (ops, "libraries", annex, readbuf, offset, len,
8910 &remote_protocol_packets[PACKET_qXfer_libraries]);
8912 case TARGET_OBJECT_LIBRARIES_SVR4:
8913 return remote_read_qxfer
8914 (ops, "libraries-svr4", annex, readbuf, offset, len,
8915 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8917 case TARGET_OBJECT_MEMORY_MAP:
8918 gdb_assert (annex == NULL);
8919 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8920 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8922 case TARGET_OBJECT_OSDATA:
8923 /* Should only get here if we're connected. */
8924 gdb_assert (remote_desc);
8925 return remote_read_qxfer
8926 (ops, "osdata", annex, readbuf, offset, len,
8927 &remote_protocol_packets[PACKET_qXfer_osdata]);
8929 case TARGET_OBJECT_THREADS:
8930 gdb_assert (annex == NULL);
8931 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8932 &remote_protocol_packets[PACKET_qXfer_threads]);
8934 case TARGET_OBJECT_TRACEFRAME_INFO:
8935 gdb_assert (annex == NULL);
8936 return remote_read_qxfer
8937 (ops, "traceframe-info", annex, readbuf, offset, len,
8938 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8940 case TARGET_OBJECT_FDPIC:
8941 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8942 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8944 case TARGET_OBJECT_OPENVMS_UIB:
8945 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
8946 &remote_protocol_packets[PACKET_qXfer_uib]);
8948 case TARGET_OBJECT_BTRACE:
8949 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
8950 &remote_protocol_packets[PACKET_qXfer_btrace]);
8956 /* Note: a zero OFFSET and LEN can be used to query the minimum
8958 if (offset == 0 && len == 0)
8959 return (get_remote_packet_size ());
8960 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8961 large enough let the caller deal with it. */
8962 if (len < get_remote_packet_size ())
8964 len = get_remote_packet_size ();
8966 /* Except for querying the minimum buffer size, target must be open. */
8968 error (_("remote query is only available after target open"));
8970 gdb_assert (annex != NULL);
8971 gdb_assert (readbuf != NULL);
8977 /* We used one buffer char for the remote protocol q command and
8978 another for the query type. As the remote protocol encapsulation
8979 uses 4 chars plus one extra in case we are debugging
8980 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8983 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8985 /* Bad caller may have sent forbidden characters. */
8986 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8991 gdb_assert (annex[i] == '\0');
8993 i = putpkt (rs->buf);
8997 getpkt (&rs->buf, &rs->buf_size, 0);
8998 strcpy ((char *) readbuf, rs->buf);
9000 return strlen ((char *) readbuf);
9004 remote_search_memory (struct target_ops* ops,
9005 CORE_ADDR start_addr, ULONGEST search_space_len,
9006 const gdb_byte *pattern, ULONGEST pattern_len,
9007 CORE_ADDR *found_addrp)
9009 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9010 struct remote_state *rs = get_remote_state ();
9011 int max_size = get_memory_write_packet_size ();
9012 struct packet_config *packet =
9013 &remote_protocol_packets[PACKET_qSearch_memory];
9014 /* Number of packet bytes used to encode the pattern;
9015 this could be more than PATTERN_LEN due to escape characters. */
9016 int escaped_pattern_len;
9017 /* Amount of pattern that was encodable in the packet. */
9018 int used_pattern_len;
9021 ULONGEST found_addr;
9023 /* Don't go to the target if we don't have to.
9024 This is done before checking packet->support to avoid the possibility that
9025 a success for this edge case means the facility works in general. */
9026 if (pattern_len > search_space_len)
9028 if (pattern_len == 0)
9030 *found_addrp = start_addr;
9034 /* If we already know the packet isn't supported, fall back to the simple
9035 way of searching memory. */
9037 if (packet->support == PACKET_DISABLE)
9039 /* Target doesn't provided special support, fall back and use the
9040 standard support (copy memory and do the search here). */
9041 return simple_search_memory (ops, start_addr, search_space_len,
9042 pattern, pattern_len, found_addrp);
9045 /* Make sure the remote is pointing at the right process. */
9046 set_general_process ();
9048 /* Insert header. */
9049 i = snprintf (rs->buf, max_size,
9050 "qSearch:memory:%s;%s;",
9051 phex_nz (start_addr, addr_size),
9052 phex_nz (search_space_len, sizeof (search_space_len)));
9053 max_size -= (i + 1);
9055 /* Escape as much data as fits into rs->buf. */
9056 escaped_pattern_len =
9057 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9058 &used_pattern_len, max_size);
9060 /* Bail if the pattern is too large. */
9061 if (used_pattern_len != pattern_len)
9062 error (_("Pattern is too large to transmit to remote target."));
9064 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9065 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9066 || packet_ok (rs->buf, packet) != PACKET_OK)
9068 /* The request may not have worked because the command is not
9069 supported. If so, fall back to the simple way. */
9070 if (packet->support == PACKET_DISABLE)
9072 return simple_search_memory (ops, start_addr, search_space_len,
9073 pattern, pattern_len, found_addrp);
9078 if (rs->buf[0] == '0')
9080 else if (rs->buf[0] == '1')
9083 if (rs->buf[1] != ',')
9084 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9085 unpack_varlen_hex (rs->buf + 2, &found_addr);
9086 *found_addrp = found_addr;
9089 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9095 remote_rcmd (char *command,
9096 struct ui_file *outbuf)
9098 struct remote_state *rs = get_remote_state ();
9102 error (_("remote rcmd is only available after target open"));
9104 /* Send a NULL command across as an empty command. */
9105 if (command == NULL)
9108 /* The query prefix. */
9109 strcpy (rs->buf, "qRcmd,");
9110 p = strchr (rs->buf, '\0');
9112 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9113 > get_remote_packet_size ())
9114 error (_("\"monitor\" command ``%s'' is too long."), command);
9116 /* Encode the actual command. */
9117 bin2hex ((gdb_byte *) command, p, 0);
9119 if (putpkt (rs->buf) < 0)
9120 error (_("Communication problem with target."));
9122 /* get/display the response */
9127 /* XXX - see also remote_get_noisy_reply(). */
9128 QUIT; /* Allow user to bail out with ^C. */
9130 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9132 /* Timeout. Continue to (try to) read responses.
9133 This is better than stopping with an error, assuming the stub
9134 is still executing the (long) monitor command.
9135 If needed, the user can interrupt gdb using C-c, obtaining
9136 an effect similar to stop on timeout. */
9141 error (_("Target does not support this command."));
9142 if (buf[0] == 'O' && buf[1] != 'K')
9144 remote_console_output (buf + 1); /* 'O' message from stub. */
9147 if (strcmp (buf, "OK") == 0)
9149 if (strlen (buf) == 3 && buf[0] == 'E'
9150 && isdigit (buf[1]) && isdigit (buf[2]))
9152 error (_("Protocol error with Rcmd"));
9154 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9156 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9158 fputc_unfiltered (c, outbuf);
9164 static VEC(mem_region_s) *
9165 remote_memory_map (struct target_ops *ops)
9167 VEC(mem_region_s) *result = NULL;
9168 char *text = target_read_stralloc (¤t_target,
9169 TARGET_OBJECT_MEMORY_MAP, NULL);
9173 struct cleanup *back_to = make_cleanup (xfree, text);
9175 result = parse_memory_map (text);
9176 do_cleanups (back_to);
9183 packet_command (char *args, int from_tty)
9185 struct remote_state *rs = get_remote_state ();
9188 error (_("command can only be used with remote target"));
9191 error (_("remote-packet command requires packet text as argument"));
9193 puts_filtered ("sending: ");
9194 print_packet (args);
9195 puts_filtered ("\n");
9198 getpkt (&rs->buf, &rs->buf_size, 0);
9199 puts_filtered ("received: ");
9200 print_packet (rs->buf);
9201 puts_filtered ("\n");
9205 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9207 static void display_thread_info (struct gdb_ext_thread_info *info);
9209 static void threadset_test_cmd (char *cmd, int tty);
9211 static void threadalive_test (char *cmd, int tty);
9213 static void threadlist_test_cmd (char *cmd, int tty);
9215 int get_and_display_threadinfo (threadref *ref);
9217 static void threadinfo_test_cmd (char *cmd, int tty);
9219 static int thread_display_step (threadref *ref, void *context);
9221 static void threadlist_update_test_cmd (char *cmd, int tty);
9223 static void init_remote_threadtests (void);
9225 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9228 threadset_test_cmd (char *cmd, int tty)
9230 int sample_thread = SAMPLE_THREAD;
9232 printf_filtered (_("Remote threadset test\n"));
9233 set_general_thread (sample_thread);
9238 threadalive_test (char *cmd, int tty)
9240 int sample_thread = SAMPLE_THREAD;
9241 int pid = ptid_get_pid (inferior_ptid);
9242 ptid_t ptid = ptid_build (pid, 0, sample_thread);
9244 if (remote_thread_alive (ptid))
9245 printf_filtered ("PASS: Thread alive test\n");
9247 printf_filtered ("FAIL: Thread alive test\n");
9250 void output_threadid (char *title, threadref *ref);
9253 output_threadid (char *title, threadref *ref)
9257 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9259 printf_filtered ("%s %s\n", title, (&hexid[0]));
9263 threadlist_test_cmd (char *cmd, int tty)
9266 threadref nextthread;
9267 int done, result_count;
9268 threadref threadlist[3];
9270 printf_filtered ("Remote Threadlist test\n");
9271 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9272 &result_count, &threadlist[0]))
9273 printf_filtered ("FAIL: threadlist test\n");
9276 threadref *scan = threadlist;
9277 threadref *limit = scan + result_count;
9279 while (scan < limit)
9280 output_threadid (" thread ", scan++);
9285 display_thread_info (struct gdb_ext_thread_info *info)
9287 output_threadid ("Threadid: ", &info->threadid);
9288 printf_filtered ("Name: %s\n ", info->shortname);
9289 printf_filtered ("State: %s\n", info->display);
9290 printf_filtered ("other: %s\n\n", info->more_display);
9294 get_and_display_threadinfo (threadref *ref)
9298 struct gdb_ext_thread_info threadinfo;
9300 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9301 | TAG_MOREDISPLAY | TAG_DISPLAY;
9302 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9303 display_thread_info (&threadinfo);
9308 threadinfo_test_cmd (char *cmd, int tty)
9310 int athread = SAMPLE_THREAD;
9314 int_to_threadref (&thread, athread);
9315 printf_filtered ("Remote Threadinfo test\n");
9316 if (!get_and_display_threadinfo (&thread))
9317 printf_filtered ("FAIL cannot get thread info\n");
9321 thread_display_step (threadref *ref, void *context)
9323 /* output_threadid(" threadstep ",ref); *//* simple test */
9324 return get_and_display_threadinfo (ref);
9328 threadlist_update_test_cmd (char *cmd, int tty)
9330 printf_filtered ("Remote Threadlist update test\n");
9331 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9335 init_remote_threadtests (void)
9337 add_com ("tlist", class_obscure, threadlist_test_cmd,
9338 _("Fetch and print the remote list of "
9339 "thread identifiers, one pkt only"));
9340 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9341 _("Fetch and display info about one thread"));
9342 add_com ("tset", class_obscure, threadset_test_cmd,
9343 _("Test setting to a different thread"));
9344 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9345 _("Iterate through updating all remote thread info"));
9346 add_com ("talive", class_obscure, threadalive_test,
9347 _(" Remote thread alive test "));
9352 /* Convert a thread ID to a string. Returns the string in a static
9356 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9358 static char buf[64];
9359 struct remote_state *rs = get_remote_state ();
9361 if (ptid_equal (ptid, null_ptid))
9362 return normal_pid_to_str (ptid);
9363 else if (ptid_is_pid (ptid))
9365 /* Printing an inferior target id. */
9367 /* When multi-process extensions are off, there's no way in the
9368 remote protocol to know the remote process id, if there's any
9369 at all. There's one exception --- when we're connected with
9370 target extended-remote, and we manually attached to a process
9371 with "attach PID". We don't record anywhere a flag that
9372 allows us to distinguish that case from the case of
9373 connecting with extended-remote and the stub already being
9374 attached to a process, and reporting yes to qAttached, hence
9375 no smart special casing here. */
9376 if (!remote_multi_process_p (rs))
9378 xsnprintf (buf, sizeof buf, "Remote target");
9382 return normal_pid_to_str (ptid);
9386 if (ptid_equal (magic_null_ptid, ptid))
9387 xsnprintf (buf, sizeof buf, "Thread <main>");
9388 else if (rs->extended && remote_multi_process_p (rs))
9389 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9390 ptid_get_pid (ptid), ptid_get_tid (ptid));
9392 xsnprintf (buf, sizeof buf, "Thread %ld",
9393 ptid_get_tid (ptid));
9398 /* Get the address of the thread local variable in OBJFILE which is
9399 stored at OFFSET within the thread local storage for thread PTID. */
9402 remote_get_thread_local_address (struct target_ops *ops,
9403 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9405 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
9407 struct remote_state *rs = get_remote_state ();
9409 char *endp = rs->buf + get_remote_packet_size ();
9410 enum packet_result result;
9412 strcpy (p, "qGetTLSAddr:");
9414 p = write_ptid (p, endp, ptid);
9416 p += hexnumstr (p, offset);
9418 p += hexnumstr (p, lm);
9422 getpkt (&rs->buf, &rs->buf_size, 0);
9423 result = packet_ok (rs->buf,
9424 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9425 if (result == PACKET_OK)
9429 unpack_varlen_hex (rs->buf, &result);
9432 else if (result == PACKET_UNKNOWN)
9433 throw_error (TLS_GENERIC_ERROR,
9434 _("Remote target doesn't support qGetTLSAddr packet"));
9436 throw_error (TLS_GENERIC_ERROR,
9437 _("Remote target failed to process qGetTLSAddr request"));
9440 throw_error (TLS_GENERIC_ERROR,
9441 _("TLS not supported or disabled on this target"));
9446 /* Provide thread local base, i.e. Thread Information Block address.
9447 Returns 1 if ptid is found and thread_local_base is non zero. */
9450 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
9452 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9454 struct remote_state *rs = get_remote_state ();
9456 char *endp = rs->buf + get_remote_packet_size ();
9457 enum packet_result result;
9459 strcpy (p, "qGetTIBAddr:");
9461 p = write_ptid (p, endp, ptid);
9465 getpkt (&rs->buf, &rs->buf_size, 0);
9466 result = packet_ok (rs->buf,
9467 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9468 if (result == PACKET_OK)
9472 unpack_varlen_hex (rs->buf, &result);
9474 *addr = (CORE_ADDR) result;
9477 else if (result == PACKET_UNKNOWN)
9478 error (_("Remote target doesn't support qGetTIBAddr packet"));
9480 error (_("Remote target failed to process qGetTIBAddr request"));
9483 error (_("qGetTIBAddr not supported or disabled on this target"));
9488 /* Support for inferring a target description based on the current
9489 architecture and the size of a 'g' packet. While the 'g' packet
9490 can have any size (since optional registers can be left off the
9491 end), some sizes are easily recognizable given knowledge of the
9492 approximate architecture. */
9494 struct remote_g_packet_guess
9497 const struct target_desc *tdesc;
9499 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9500 DEF_VEC_O(remote_g_packet_guess_s);
9502 struct remote_g_packet_data
9504 VEC(remote_g_packet_guess_s) *guesses;
9507 static struct gdbarch_data *remote_g_packet_data_handle;
9510 remote_g_packet_data_init (struct obstack *obstack)
9512 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9516 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9517 const struct target_desc *tdesc)
9519 struct remote_g_packet_data *data
9520 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9521 struct remote_g_packet_guess new_guess, *guess;
9524 gdb_assert (tdesc != NULL);
9527 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9529 if (guess->bytes == bytes)
9530 internal_error (__FILE__, __LINE__,
9531 _("Duplicate g packet description added for size %d"),
9534 new_guess.bytes = bytes;
9535 new_guess.tdesc = tdesc;
9536 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9539 /* Return 1 if remote_read_description would do anything on this target
9540 and architecture, 0 otherwise. */
9543 remote_read_description_p (struct target_ops *target)
9545 struct remote_g_packet_data *data
9546 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9548 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9554 static const struct target_desc *
9555 remote_read_description (struct target_ops *target)
9557 struct remote_g_packet_data *data
9558 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9560 /* Do not try this during initial connection, when we do not know
9561 whether there is a running but stopped thread. */
9562 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9565 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9567 struct remote_g_packet_guess *guess;
9569 int bytes = send_g_packet ();
9572 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9574 if (guess->bytes == bytes)
9575 return guess->tdesc;
9577 /* We discard the g packet. A minor optimization would be to
9578 hold on to it, and fill the register cache once we have selected
9579 an architecture, but it's too tricky to do safely. */
9585 /* Remote file transfer support. This is host-initiated I/O, not
9586 target-initiated; for target-initiated, see remote-fileio.c. */
9588 /* If *LEFT is at least the length of STRING, copy STRING to
9589 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9590 decrease *LEFT. Otherwise raise an error. */
9593 remote_buffer_add_string (char **buffer, int *left, char *string)
9595 int len = strlen (string);
9598 error (_("Packet too long for target."));
9600 memcpy (*buffer, string, len);
9604 /* NUL-terminate the buffer as a convenience, if there is
9610 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9611 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9612 decrease *LEFT. Otherwise raise an error. */
9615 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9618 if (2 * len > *left)
9619 error (_("Packet too long for target."));
9621 bin2hex (bytes, *buffer, len);
9625 /* NUL-terminate the buffer as a convenience, if there is
9631 /* If *LEFT is large enough, convert VALUE to hex and add it to
9632 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9633 decrease *LEFT. Otherwise raise an error. */
9636 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9638 int len = hexnumlen (value);
9641 error (_("Packet too long for target."));
9643 hexnumstr (*buffer, value);
9647 /* NUL-terminate the buffer as a convenience, if there is
9653 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9654 value, *REMOTE_ERRNO to the remote error number or zero if none
9655 was included, and *ATTACHMENT to point to the start of the annex
9656 if any. The length of the packet isn't needed here; there may
9657 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9659 Return 0 if the packet could be parsed, -1 if it could not. If
9660 -1 is returned, the other variables may not be initialized. */
9663 remote_hostio_parse_result (char *buffer, int *retcode,
9664 int *remote_errno, char **attachment)
9671 if (buffer[0] != 'F')
9675 *retcode = strtol (&buffer[1], &p, 16);
9676 if (errno != 0 || p == &buffer[1])
9679 /* Check for ",errno". */
9683 *remote_errno = strtol (p + 1, &p2, 16);
9684 if (errno != 0 || p + 1 == p2)
9689 /* Check for ";attachment". If there is no attachment, the
9690 packet should end here. */
9693 *attachment = p + 1;
9696 else if (*p == '\0')
9702 /* Send a prepared I/O packet to the target and read its response.
9703 The prepared packet is in the global RS->BUF before this function
9704 is called, and the answer is there when we return.
9706 COMMAND_BYTES is the length of the request to send, which may include
9707 binary data. WHICH_PACKET is the packet configuration to check
9708 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9709 is set to the error number and -1 is returned. Otherwise the value
9710 returned by the function is returned.
9712 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9713 attachment is expected; an error will be reported if there's a
9714 mismatch. If one is found, *ATTACHMENT will be set to point into
9715 the packet buffer and *ATTACHMENT_LEN will be set to the
9716 attachment's length. */
9719 remote_hostio_send_command (int command_bytes, int which_packet,
9720 int *remote_errno, char **attachment,
9721 int *attachment_len)
9723 struct remote_state *rs = get_remote_state ();
9724 int ret, bytes_read;
9725 char *attachment_tmp;
9728 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
9730 *remote_errno = FILEIO_ENOSYS;
9734 putpkt_binary (rs->buf, command_bytes);
9735 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9737 /* If it timed out, something is wrong. Don't try to parse the
9741 *remote_errno = FILEIO_EINVAL;
9745 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9748 *remote_errno = FILEIO_EINVAL;
9750 case PACKET_UNKNOWN:
9751 *remote_errno = FILEIO_ENOSYS;
9757 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9760 *remote_errno = FILEIO_EINVAL;
9764 /* Make sure we saw an attachment if and only if we expected one. */
9765 if ((attachment_tmp == NULL && attachment != NULL)
9766 || (attachment_tmp != NULL && attachment == NULL))
9768 *remote_errno = FILEIO_EINVAL;
9772 /* If an attachment was found, it must point into the packet buffer;
9773 work out how many bytes there were. */
9774 if (attachment_tmp != NULL)
9776 *attachment = attachment_tmp;
9777 *attachment_len = bytes_read - (*attachment - rs->buf);
9783 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9784 remote file descriptor, or -1 if an error occurs (and set
9788 remote_hostio_open (const char *filename, int flags, int mode,
9791 struct remote_state *rs = get_remote_state ();
9793 int left = get_remote_packet_size () - 1;
9795 remote_buffer_add_string (&p, &left, "vFile:open:");
9797 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9799 remote_buffer_add_string (&p, &left, ",");
9801 remote_buffer_add_int (&p, &left, flags);
9802 remote_buffer_add_string (&p, &left, ",");
9804 remote_buffer_add_int (&p, &left, mode);
9806 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9807 remote_errno, NULL, NULL);
9810 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9811 Return the number of bytes written, or -1 if an error occurs (and
9812 set *REMOTE_ERRNO). */
9815 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9816 ULONGEST offset, int *remote_errno)
9818 struct remote_state *rs = get_remote_state ();
9820 int left = get_remote_packet_size ();
9823 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9825 remote_buffer_add_int (&p, &left, fd);
9826 remote_buffer_add_string (&p, &left, ",");
9828 remote_buffer_add_int (&p, &left, offset);
9829 remote_buffer_add_string (&p, &left, ",");
9831 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9832 get_remote_packet_size () - (p - rs->buf));
9834 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9835 remote_errno, NULL, NULL);
9838 /* Read up to LEN bytes FD on the remote target into READ_BUF
9839 Return the number of bytes read, or -1 if an error occurs (and
9840 set *REMOTE_ERRNO). */
9843 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9844 ULONGEST offset, int *remote_errno)
9846 struct remote_state *rs = get_remote_state ();
9849 int left = get_remote_packet_size ();
9850 int ret, attachment_len;
9853 remote_buffer_add_string (&p, &left, "vFile:pread:");
9855 remote_buffer_add_int (&p, &left, fd);
9856 remote_buffer_add_string (&p, &left, ",");
9858 remote_buffer_add_int (&p, &left, len);
9859 remote_buffer_add_string (&p, &left, ",");
9861 remote_buffer_add_int (&p, &left, offset);
9863 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9864 remote_errno, &attachment,
9870 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9872 if (read_len != ret)
9873 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9878 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9879 (and set *REMOTE_ERRNO). */
9882 remote_hostio_close (int fd, int *remote_errno)
9884 struct remote_state *rs = get_remote_state ();
9886 int left = get_remote_packet_size () - 1;
9888 remote_buffer_add_string (&p, &left, "vFile:close:");
9890 remote_buffer_add_int (&p, &left, fd);
9892 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9893 remote_errno, NULL, NULL);
9896 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9897 occurs (and set *REMOTE_ERRNO). */
9900 remote_hostio_unlink (const char *filename, int *remote_errno)
9902 struct remote_state *rs = get_remote_state ();
9904 int left = get_remote_packet_size () - 1;
9906 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9908 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9911 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9912 remote_errno, NULL, NULL);
9915 /* Read value of symbolic link FILENAME on the remote target. Return
9916 a null-terminated string allocated via xmalloc, or NULL if an error
9917 occurs (and set *REMOTE_ERRNO). */
9920 remote_hostio_readlink (const char *filename, int *remote_errno)
9922 struct remote_state *rs = get_remote_state ();
9925 int left = get_remote_packet_size ();
9926 int len, attachment_len;
9930 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9932 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9935 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9936 remote_errno, &attachment,
9942 ret = xmalloc (len + 1);
9944 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9945 (gdb_byte *) ret, len);
9946 if (read_len != len)
9947 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9954 remote_fileio_errno_to_host (int errnum)
9978 case FILEIO_ENOTDIR:
9998 case FILEIO_ENAMETOOLONG:
9999 return ENAMETOOLONG;
10005 remote_hostio_error (int errnum)
10007 int host_error = remote_fileio_errno_to_host (errnum);
10009 if (host_error == -1)
10010 error (_("Unknown remote I/O error %d"), errnum);
10012 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10016 remote_hostio_close_cleanup (void *opaque)
10018 int fd = *(int *) opaque;
10021 remote_hostio_close (fd, &remote_errno);
10026 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10028 const char *filename = bfd_get_filename (abfd);
10029 int fd, remote_errno;
10032 gdb_assert (remote_filename_p (filename));
10034 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10037 errno = remote_fileio_errno_to_host (remote_errno);
10038 bfd_set_error (bfd_error_system_call);
10042 stream = xmalloc (sizeof (int));
10048 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10050 int fd = *(int *)stream;
10055 /* Ignore errors on close; these may happen if the remote
10056 connection was already torn down. */
10057 remote_hostio_close (fd, &remote_errno);
10059 /* Zero means success. */
10064 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10065 file_ptr nbytes, file_ptr offset)
10067 int fd = *(int *)stream;
10069 file_ptr pos, bytes;
10072 while (nbytes > pos)
10074 bytes = remote_hostio_pread (fd, (gdb_byte *) buf + pos, nbytes - pos,
10075 offset + pos, &remote_errno);
10077 /* Success, but no bytes, means end-of-file. */
10081 errno = remote_fileio_errno_to_host (remote_errno);
10082 bfd_set_error (bfd_error_system_call);
10093 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10095 /* FIXME: We should probably implement remote_hostio_stat. */
10096 sb->st_size = INT_MAX;
10101 remote_filename_p (const char *filename)
10103 return strncmp (filename, "remote:", 7) == 0;
10107 remote_bfd_open (const char *remote_file, const char *target)
10109 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10110 remote_bfd_iovec_open, NULL,
10111 remote_bfd_iovec_pread,
10112 remote_bfd_iovec_close,
10113 remote_bfd_iovec_stat);
10119 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10121 struct cleanup *back_to, *close_cleanup;
10122 int retcode, fd, remote_errno, bytes, io_size;
10125 int bytes_in_buffer;
10130 error (_("command can only be used with remote target"));
10132 file = gdb_fopen_cloexec (local_file, "rb");
10134 perror_with_name (local_file);
10135 back_to = make_cleanup_fclose (file);
10137 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10139 0700, &remote_errno);
10141 remote_hostio_error (remote_errno);
10143 /* Send up to this many bytes at once. They won't all fit in the
10144 remote packet limit, so we'll transfer slightly fewer. */
10145 io_size = get_remote_packet_size ();
10146 buffer = xmalloc (io_size);
10147 make_cleanup (xfree, buffer);
10149 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10151 bytes_in_buffer = 0;
10154 while (bytes_in_buffer || !saw_eof)
10158 bytes = fread (buffer + bytes_in_buffer, 1,
10159 io_size - bytes_in_buffer,
10164 error (_("Error reading %s."), local_file);
10167 /* EOF. Unless there is something still in the
10168 buffer from the last iteration, we are done. */
10170 if (bytes_in_buffer == 0)
10178 bytes += bytes_in_buffer;
10179 bytes_in_buffer = 0;
10181 retcode = remote_hostio_pwrite (fd, buffer, bytes,
10182 offset, &remote_errno);
10185 remote_hostio_error (remote_errno);
10186 else if (retcode == 0)
10187 error (_("Remote write of %d bytes returned 0!"), bytes);
10188 else if (retcode < bytes)
10190 /* Short write. Save the rest of the read data for the next
10192 bytes_in_buffer = bytes - retcode;
10193 memmove (buffer, buffer + retcode, bytes_in_buffer);
10199 discard_cleanups (close_cleanup);
10200 if (remote_hostio_close (fd, &remote_errno))
10201 remote_hostio_error (remote_errno);
10204 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10205 do_cleanups (back_to);
10209 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10211 struct cleanup *back_to, *close_cleanup;
10212 int fd, remote_errno, bytes, io_size;
10218 error (_("command can only be used with remote target"));
10220 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10222 remote_hostio_error (remote_errno);
10224 file = gdb_fopen_cloexec (local_file, "wb");
10226 perror_with_name (local_file);
10227 back_to = make_cleanup_fclose (file);
10229 /* Send up to this many bytes at once. They won't all fit in the
10230 remote packet limit, so we'll transfer slightly fewer. */
10231 io_size = get_remote_packet_size ();
10232 buffer = xmalloc (io_size);
10233 make_cleanup (xfree, buffer);
10235 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10240 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
10242 /* Success, but no bytes, means end-of-file. */
10245 remote_hostio_error (remote_errno);
10249 bytes = fwrite (buffer, 1, bytes, file);
10251 perror_with_name (local_file);
10254 discard_cleanups (close_cleanup);
10255 if (remote_hostio_close (fd, &remote_errno))
10256 remote_hostio_error (remote_errno);
10259 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10260 do_cleanups (back_to);
10264 remote_file_delete (const char *remote_file, int from_tty)
10266 int retcode, remote_errno;
10269 error (_("command can only be used with remote target"));
10271 retcode = remote_hostio_unlink (remote_file, &remote_errno);
10273 remote_hostio_error (remote_errno);
10276 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10280 remote_put_command (char *args, int from_tty)
10282 struct cleanup *back_to;
10286 error_no_arg (_("file to put"));
10288 argv = gdb_buildargv (args);
10289 back_to = make_cleanup_freeargv (argv);
10290 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10291 error (_("Invalid parameters to remote put"));
10293 remote_file_put (argv[0], argv[1], from_tty);
10295 do_cleanups (back_to);
10299 remote_get_command (char *args, int from_tty)
10301 struct cleanup *back_to;
10305 error_no_arg (_("file to get"));
10307 argv = gdb_buildargv (args);
10308 back_to = make_cleanup_freeargv (argv);
10309 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10310 error (_("Invalid parameters to remote get"));
10312 remote_file_get (argv[0], argv[1], from_tty);
10314 do_cleanups (back_to);
10318 remote_delete_command (char *args, int from_tty)
10320 struct cleanup *back_to;
10324 error_no_arg (_("file to delete"));
10326 argv = gdb_buildargv (args);
10327 back_to = make_cleanup_freeargv (argv);
10328 if (argv[0] == NULL || argv[1] != NULL)
10329 error (_("Invalid parameters to remote delete"));
10331 remote_file_delete (argv[0], from_tty);
10333 do_cleanups (back_to);
10337 remote_command (char *args, int from_tty)
10339 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10343 remote_can_execute_reverse (void)
10345 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10346 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10353 remote_supports_non_stop (void)
10359 remote_supports_disable_randomization (void)
10361 /* Only supported in extended mode. */
10366 remote_supports_multi_process (void)
10368 struct remote_state *rs = get_remote_state ();
10370 /* Only extended-remote handles being attached to multiple
10371 processes, even though plain remote can use the multi-process
10372 thread id extensions, so that GDB knows the target process's
10374 return rs->extended && remote_multi_process_p (rs);
10378 remote_supports_cond_tracepoints (void)
10380 struct remote_state *rs = get_remote_state ();
10382 return rs->cond_tracepoints;
10386 remote_supports_cond_breakpoints (void)
10388 struct remote_state *rs = get_remote_state ();
10390 return rs->cond_breakpoints;
10394 remote_supports_fast_tracepoints (void)
10396 struct remote_state *rs = get_remote_state ();
10398 return rs->fast_tracepoints;
10402 remote_supports_static_tracepoints (void)
10404 struct remote_state *rs = get_remote_state ();
10406 return rs->static_tracepoints;
10410 remote_supports_install_in_trace (void)
10412 struct remote_state *rs = get_remote_state ();
10414 return rs->install_in_trace;
10418 remote_supports_enable_disable_tracepoint (void)
10420 struct remote_state *rs = get_remote_state ();
10422 return rs->enable_disable_tracepoints;
10426 remote_supports_string_tracing (void)
10428 struct remote_state *rs = get_remote_state ();
10430 return rs->string_tracing;
10434 remote_can_run_breakpoint_commands (void)
10436 struct remote_state *rs = get_remote_state ();
10438 return rs->breakpoint_commands;
10442 remote_trace_init (void)
10445 remote_get_noisy_reply (&target_buf, &target_buf_size);
10446 if (strcmp (target_buf, "OK") != 0)
10447 error (_("Target does not support this command."));
10450 static void free_actions_list (char **actions_list);
10451 static void free_actions_list_cleanup_wrapper (void *);
10453 free_actions_list_cleanup_wrapper (void *al)
10455 free_actions_list (al);
10459 free_actions_list (char **actions_list)
10463 if (actions_list == 0)
10466 for (ndx = 0; actions_list[ndx]; ndx++)
10467 xfree (actions_list[ndx]);
10469 xfree (actions_list);
10472 /* Recursive routine to walk through command list including loops, and
10473 download packets for each command. */
10476 remote_download_command_source (int num, ULONGEST addr,
10477 struct command_line *cmds)
10479 struct remote_state *rs = get_remote_state ();
10480 struct command_line *cmd;
10482 for (cmd = cmds; cmd; cmd = cmd->next)
10484 QUIT; /* Allow user to bail out with ^C. */
10485 strcpy (rs->buf, "QTDPsrc:");
10486 encode_source_string (num, addr, "cmd", cmd->line,
10487 rs->buf + strlen (rs->buf),
10488 rs->buf_size - strlen (rs->buf));
10490 remote_get_noisy_reply (&target_buf, &target_buf_size);
10491 if (strcmp (target_buf, "OK"))
10492 warning (_("Target does not support source download."));
10494 if (cmd->control_type == while_control
10495 || cmd->control_type == while_stepping_control)
10497 remote_download_command_source (num, addr, *cmd->body_list);
10499 QUIT; /* Allow user to bail out with ^C. */
10500 strcpy (rs->buf, "QTDPsrc:");
10501 encode_source_string (num, addr, "cmd", "end",
10502 rs->buf + strlen (rs->buf),
10503 rs->buf_size - strlen (rs->buf));
10505 remote_get_noisy_reply (&target_buf, &target_buf_size);
10506 if (strcmp (target_buf, "OK"))
10507 warning (_("Target does not support source download."));
10513 remote_download_tracepoint (struct bp_location *loc)
10515 #define BUF_SIZE 2048
10519 char buf[BUF_SIZE];
10520 char **tdp_actions;
10521 char **stepping_actions;
10523 struct cleanup *old_chain = NULL;
10524 struct agent_expr *aexpr;
10525 struct cleanup *aexpr_chain = NULL;
10527 struct breakpoint *b = loc->owner;
10528 struct tracepoint *t = (struct tracepoint *) b;
10530 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10531 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10533 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10536 tpaddr = loc->address;
10537 sprintf_vma (addrbuf, tpaddr);
10538 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10539 addrbuf, /* address */
10540 (b->enable_state == bp_enabled ? 'E' : 'D'),
10541 t->step_count, t->pass_count);
10542 /* Fast tracepoints are mostly handled by the target, but we can
10543 tell the target how big of an instruction block should be moved
10545 if (b->type == bp_fast_tracepoint)
10547 /* Only test for support at download time; we may not know
10548 target capabilities at definition time. */
10549 if (remote_supports_fast_tracepoints ())
10553 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10554 tpaddr, &isize, NULL))
10555 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10558 /* If it passed validation at definition but fails now,
10559 something is very wrong. */
10560 internal_error (__FILE__, __LINE__,
10561 _("Fast tracepoint not "
10562 "valid during download"));
10565 /* Fast tracepoints are functionally identical to regular
10566 tracepoints, so don't take lack of support as a reason to
10567 give up on the trace run. */
10568 warning (_("Target does not support fast tracepoints, "
10569 "downloading %d as regular tracepoint"), b->number);
10571 else if (b->type == bp_static_tracepoint)
10573 /* Only test for support at download time; we may not know
10574 target capabilities at definition time. */
10575 if (remote_supports_static_tracepoints ())
10577 struct static_tracepoint_marker marker;
10579 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10580 strcat (buf, ":S");
10582 error (_("Static tracepoint not valid during download"));
10585 /* Fast tracepoints are functionally identical to regular
10586 tracepoints, so don't take lack of support as a reason
10587 to give up on the trace run. */
10588 error (_("Target does not support static tracepoints"));
10590 /* If the tracepoint has a conditional, make it into an agent
10591 expression and append to the definition. */
10594 /* Only test support at download time, we may not know target
10595 capabilities at definition time. */
10596 if (remote_supports_cond_tracepoints ())
10598 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10599 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10600 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10602 pkt = buf + strlen (buf);
10603 for (ndx = 0; ndx < aexpr->len; ++ndx)
10604 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10606 do_cleanups (aexpr_chain);
10609 warning (_("Target does not support conditional tracepoints, "
10610 "ignoring tp %d cond"), b->number);
10613 if (b->commands || *default_collect)
10616 remote_get_noisy_reply (&target_buf, &target_buf_size);
10617 if (strcmp (target_buf, "OK"))
10618 error (_("Target does not support tracepoints."));
10620 /* do_single_steps (t); */
10623 for (ndx = 0; tdp_actions[ndx]; ndx++)
10625 QUIT; /* Allow user to bail out with ^C. */
10626 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10627 b->number, addrbuf, /* address */
10629 ((tdp_actions[ndx + 1] || stepping_actions)
10632 remote_get_noisy_reply (&target_buf,
10634 if (strcmp (target_buf, "OK"))
10635 error (_("Error on target while setting tracepoints."));
10638 if (stepping_actions)
10640 for (ndx = 0; stepping_actions[ndx]; ndx++)
10642 QUIT; /* Allow user to bail out with ^C. */
10643 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10644 b->number, addrbuf, /* address */
10645 ((ndx == 0) ? "S" : ""),
10646 stepping_actions[ndx],
10647 (stepping_actions[ndx + 1] ? "-" : ""));
10649 remote_get_noisy_reply (&target_buf,
10651 if (strcmp (target_buf, "OK"))
10652 error (_("Error on target while setting tracepoints."));
10656 if (remote_protocol_packets[PACKET_TracepointSource].support
10659 if (b->addr_string)
10661 strcpy (buf, "QTDPsrc:");
10662 encode_source_string (b->number, loc->address,
10663 "at", b->addr_string, buf + strlen (buf),
10664 2048 - strlen (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 (b->cond_string)
10673 strcpy (buf, "QTDPsrc:");
10674 encode_source_string (b->number, loc->address,
10675 "cond", b->cond_string, buf + strlen (buf),
10676 2048 - strlen (buf));
10678 remote_get_noisy_reply (&target_buf, &target_buf_size);
10679 if (strcmp (target_buf, "OK"))
10680 warning (_("Target does not support source download."));
10682 remote_download_command_source (b->number, loc->address,
10683 breakpoint_commands (b));
10686 do_cleanups (old_chain);
10690 remote_can_download_tracepoint (void)
10692 struct remote_state *rs = get_remote_state ();
10693 struct trace_status *ts;
10696 /* Don't try to install tracepoints until we've relocated our
10697 symbols, and fetched and merged the target's tracepoint list with
10699 if (rs->starting_up)
10702 ts = current_trace_status ();
10703 status = remote_get_trace_status (ts);
10705 if (status == -1 || !ts->running_known || !ts->running)
10708 /* If we are in a tracing experiment, but remote stub doesn't support
10709 installing tracepoint in trace, we have to return. */
10710 if (!remote_supports_install_in_trace ())
10718 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10720 struct remote_state *rs = get_remote_state ();
10723 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10724 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10726 p = rs->buf + strlen (rs->buf);
10727 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10728 error (_("Trace state variable name too long for tsv definition packet"));
10729 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10732 remote_get_noisy_reply (&target_buf, &target_buf_size);
10733 if (*target_buf == '\0')
10734 error (_("Target does not support this command."));
10735 if (strcmp (target_buf, "OK") != 0)
10736 error (_("Error on target while downloading trace state variable."));
10740 remote_enable_tracepoint (struct bp_location *location)
10742 struct remote_state *rs = get_remote_state ();
10745 sprintf_vma (addr_buf, location->address);
10746 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10747 location->owner->number, addr_buf);
10749 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10750 if (*rs->buf == '\0')
10751 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10752 if (strcmp (rs->buf, "OK") != 0)
10753 error (_("Error on target while enabling tracepoint."));
10757 remote_disable_tracepoint (struct bp_location *location)
10759 struct remote_state *rs = get_remote_state ();
10762 sprintf_vma (addr_buf, location->address);
10763 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10764 location->owner->number, addr_buf);
10766 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10767 if (*rs->buf == '\0')
10768 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10769 if (strcmp (rs->buf, "OK") != 0)
10770 error (_("Error on target while disabling tracepoint."));
10774 remote_trace_set_readonly_regions (void)
10778 bfd_size_type size;
10784 return; /* No information to give. */
10786 strcpy (target_buf, "QTro");
10787 offset = strlen (target_buf);
10788 for (s = exec_bfd->sections; s; s = s->next)
10790 char tmp1[40], tmp2[40];
10793 if ((s->flags & SEC_LOAD) == 0 ||
10794 /* (s->flags & SEC_CODE) == 0 || */
10795 (s->flags & SEC_READONLY) == 0)
10799 vma = bfd_get_section_vma (abfd, s);
10800 size = bfd_get_section_size (s);
10801 sprintf_vma (tmp1, vma);
10802 sprintf_vma (tmp2, vma + size);
10803 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10804 if (offset + sec_length + 1 > target_buf_size)
10806 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10809 Too many sections for read-only sections definition packet."));
10812 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10814 offset += sec_length;
10818 putpkt (target_buf);
10819 getpkt (&target_buf, &target_buf_size, 0);
10824 remote_trace_start (void)
10826 putpkt ("QTStart");
10827 remote_get_noisy_reply (&target_buf, &target_buf_size);
10828 if (*target_buf == '\0')
10829 error (_("Target does not support this command."));
10830 if (strcmp (target_buf, "OK") != 0)
10831 error (_("Bogus reply from target: %s"), target_buf);
10835 remote_get_trace_status (struct trace_status *ts)
10837 /* Initialize it just to avoid a GCC false warning. */
10839 /* FIXME we need to get register block size some other way. */
10840 extern int trace_regblock_size;
10841 volatile struct gdb_exception ex;
10842 enum packet_result result;
10844 if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
10847 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10849 putpkt ("qTStatus");
10851 TRY_CATCH (ex, RETURN_MASK_ERROR)
10853 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10857 if (ex.error != TARGET_CLOSE_ERROR)
10859 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10862 throw_exception (ex);
10865 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10867 /* If the remote target doesn't do tracing, flag it. */
10868 if (result == PACKET_UNKNOWN)
10871 /* We're working with a live target. */
10872 ts->filename = NULL;
10875 error (_("Bogus trace status reply from target: %s"), target_buf);
10877 /* Function 'parse_trace_status' sets default value of each field of
10878 'ts' at first, so we don't have to do it here. */
10879 parse_trace_status (p, ts);
10881 return ts->running;
10885 remote_get_tracepoint_status (struct breakpoint *bp,
10886 struct uploaded_tp *utp)
10888 struct remote_state *rs = get_remote_state ();
10890 struct bp_location *loc;
10891 struct tracepoint *tp = (struct tracepoint *) bp;
10892 size_t size = get_remote_packet_size ();
10896 tp->base.hit_count = 0;
10897 tp->traceframe_usage = 0;
10898 for (loc = tp->base.loc; loc; loc = loc->next)
10900 /* If the tracepoint was never downloaded, don't go asking for
10902 if (tp->number_on_target == 0)
10904 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10905 phex_nz (loc->address, 0));
10907 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10908 if (reply && *reply)
10911 parse_tracepoint_status (reply + 1, bp, utp);
10917 utp->hit_count = 0;
10918 utp->traceframe_usage = 0;
10919 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10920 phex_nz (utp->addr, 0));
10922 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10923 if (reply && *reply)
10926 parse_tracepoint_status (reply + 1, bp, utp);
10932 remote_trace_stop (void)
10935 remote_get_noisy_reply (&target_buf, &target_buf_size);
10936 if (*target_buf == '\0')
10937 error (_("Target does not support this command."));
10938 if (strcmp (target_buf, "OK") != 0)
10939 error (_("Bogus reply from target: %s"), target_buf);
10943 remote_trace_find (enum trace_find_type type, int num,
10944 CORE_ADDR addr1, CORE_ADDR addr2,
10947 struct remote_state *rs = get_remote_state ();
10948 char *endbuf = rs->buf + get_remote_packet_size ();
10950 int target_frameno = -1, target_tracept = -1;
10952 /* Lookups other than by absolute frame number depend on the current
10953 trace selected, so make sure it is correct on the remote end
10955 if (type != tfind_number)
10956 set_remote_traceframe ();
10959 strcpy (p, "QTFrame:");
10960 p = strchr (p, '\0');
10964 xsnprintf (p, endbuf - p, "%x", num);
10967 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
10970 xsnprintf (p, endbuf - p, "tdp:%x", num);
10973 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10974 phex_nz (addr2, 0));
10976 case tfind_outside:
10977 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10978 phex_nz (addr2, 0));
10981 error (_("Unknown trace find type %d"), type);
10985 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
10986 if (*reply == '\0')
10987 error (_("Target does not support this command."));
10989 while (reply && *reply)
10994 target_frameno = (int) strtol (p, &reply, 16);
10996 error (_("Unable to parse trace frame number"));
10997 /* Don't update our remote traceframe number cache on failure
10998 to select a remote traceframe. */
10999 if (target_frameno == -1)
11004 target_tracept = (int) strtol (p, &reply, 16);
11006 error (_("Unable to parse tracepoint number"));
11008 case 'O': /* "OK"? */
11009 if (reply[1] == 'K' && reply[2] == '\0')
11012 error (_("Bogus reply from target: %s"), reply);
11015 error (_("Bogus reply from target: %s"), reply);
11018 *tpp = target_tracept;
11020 remote_traceframe_number = target_frameno;
11021 return target_frameno;
11025 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
11027 struct remote_state *rs = get_remote_state ();
11031 set_remote_traceframe ();
11033 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11035 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11036 if (reply && *reply)
11040 unpack_varlen_hex (reply + 1, &uval);
11041 *val = (LONGEST) uval;
11049 remote_save_trace_data (const char *filename)
11051 struct remote_state *rs = get_remote_state ();
11055 strcpy (p, "QTSave:");
11057 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11058 error (_("Remote file name too long for trace save packet"));
11059 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
11062 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11063 if (*reply == '\0')
11064 error (_("Target does not support this command."));
11065 if (strcmp (reply, "OK") != 0)
11066 error (_("Bogus reply from target: %s"), reply);
11070 /* This is basically a memory transfer, but needs to be its own packet
11071 because we don't know how the target actually organizes its trace
11072 memory, plus we want to be able to ask for as much as possible, but
11073 not be unhappy if we don't get as much as we ask for. */
11076 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
11078 struct remote_state *rs = get_remote_state ();
11084 strcpy (p, "qTBuffer:");
11086 p += hexnumstr (p, offset);
11088 p += hexnumstr (p, len);
11092 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11093 if (reply && *reply)
11095 /* 'l' by itself means we're at the end of the buffer and
11096 there is nothing more to get. */
11100 /* Convert the reply into binary. Limit the number of bytes to
11101 convert according to our passed-in buffer size, rather than
11102 what was returned in the packet; if the target is
11103 unexpectedly generous and gives us a bigger reply than we
11104 asked for, we don't want to crash. */
11105 rslt = hex2bin (target_buf, buf, len);
11109 /* Something went wrong, flag as an error. */
11114 remote_set_disconnected_tracing (int val)
11116 struct remote_state *rs = get_remote_state ();
11118 if (rs->disconnected_tracing)
11122 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11124 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11125 if (*reply == '\0')
11126 error (_("Target does not support this command."));
11127 if (strcmp (reply, "OK") != 0)
11128 error (_("Bogus reply from target: %s"), reply);
11131 warning (_("Target does not support disconnected tracing."));
11135 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11137 struct thread_info *info = find_thread_ptid (ptid);
11139 if (info && info->private)
11140 return info->private->core;
11145 remote_set_circular_trace_buffer (int val)
11147 struct remote_state *rs = get_remote_state ();
11150 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11152 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11153 if (*reply == '\0')
11154 error (_("Target does not support this command."));
11155 if (strcmp (reply, "OK") != 0)
11156 error (_("Bogus reply from target: %s"), reply);
11159 static struct traceframe_info *
11160 remote_traceframe_info (void)
11164 text = target_read_stralloc (¤t_target,
11165 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11168 struct traceframe_info *info;
11169 struct cleanup *back_to = make_cleanup (xfree, text);
11171 info = parse_traceframe_info (text);
11172 do_cleanups (back_to);
11179 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11180 instruction on which a fast tracepoint may be placed. Returns -1
11181 if the packet is not supported, and 0 if the minimum instruction
11182 length is unknown. */
11185 remote_get_min_fast_tracepoint_insn_len (void)
11187 struct remote_state *rs = get_remote_state ();
11190 /* If we're not debugging a process yet, the IPA can't be
11192 if (!target_has_execution)
11195 /* Make sure the remote is pointing at the right process. */
11196 set_general_process ();
11198 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11200 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11201 if (*reply == '\0')
11205 ULONGEST min_insn_len;
11207 unpack_varlen_hex (reply, &min_insn_len);
11209 return (int) min_insn_len;
11214 remote_set_trace_buffer_size (LONGEST val)
11216 if (remote_protocol_packets[PACKET_QTBuffer_size].support
11219 struct remote_state *rs = get_remote_state ();
11220 char *buf = rs->buf;
11221 char *endbuf = rs->buf + get_remote_packet_size ();
11222 enum packet_result result;
11224 gdb_assert (val >= 0 || val == -1);
11225 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11226 /* Send -1 as literal "-1" to avoid host size dependency. */
11230 buf += hexnumstr (buf, (ULONGEST) -val);
11233 buf += hexnumstr (buf, (ULONGEST) val);
11236 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11237 result = packet_ok (rs->buf,
11238 &remote_protocol_packets[PACKET_QTBuffer_size]);
11240 if (result != PACKET_OK)
11241 warning (_("Bogus reply from target: %s"), rs->buf);
11246 remote_set_trace_notes (const char *user, const char *notes,
11247 const char *stop_notes)
11249 struct remote_state *rs = get_remote_state ();
11251 char *buf = rs->buf;
11252 char *endbuf = rs->buf + get_remote_packet_size ();
11255 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11258 buf += xsnprintf (buf, endbuf - buf, "user:");
11259 nbytes = bin2hex ((gdb_byte *) user, buf, 0);
11265 buf += xsnprintf (buf, endbuf - buf, "notes:");
11266 nbytes = bin2hex ((gdb_byte *) notes, buf, 0);
11272 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11273 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, 0);
11277 /* Ensure the buffer is terminated. */
11281 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11282 if (*reply == '\0')
11285 if (strcmp (reply, "OK") != 0)
11286 error (_("Bogus reply from target: %s"), reply);
11292 remote_use_agent (int use)
11294 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11296 struct remote_state *rs = get_remote_state ();
11298 /* If the stub supports QAgent. */
11299 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11301 getpkt (&rs->buf, &rs->buf_size, 0);
11303 if (strcmp (rs->buf, "OK") == 0)
11314 remote_can_use_agent (void)
11316 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11319 struct btrace_target_info
11321 /* The ptid of the traced thread. */
11325 /* Check whether the target supports branch tracing. */
11328 remote_supports_btrace (void)
11330 if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11332 if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11334 if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11340 /* Enable branch tracing. */
11342 static struct btrace_target_info *
11343 remote_enable_btrace (ptid_t ptid)
11345 struct btrace_target_info *tinfo = NULL;
11346 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11347 struct remote_state *rs = get_remote_state ();
11348 char *buf = rs->buf;
11349 char *endbuf = rs->buf + get_remote_packet_size ();
11351 if (packet->support != PACKET_ENABLE)
11352 error (_("Target does not support branch tracing."));
11354 set_general_thread (ptid);
11356 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11358 getpkt (&rs->buf, &rs->buf_size, 0);
11360 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11362 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11363 error (_("Could not enable branch tracing for %s: %s"),
11364 target_pid_to_str (ptid), rs->buf + 2);
11366 error (_("Could not enable branch tracing for %s."),
11367 target_pid_to_str (ptid));
11370 tinfo = xzalloc (sizeof (*tinfo));
11371 tinfo->ptid = ptid;
11376 /* Disable branch tracing. */
11379 remote_disable_btrace (struct btrace_target_info *tinfo)
11381 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11382 struct remote_state *rs = get_remote_state ();
11383 char *buf = rs->buf;
11384 char *endbuf = rs->buf + get_remote_packet_size ();
11386 if (packet->support != PACKET_ENABLE)
11387 error (_("Target does not support branch tracing."));
11389 set_general_thread (tinfo->ptid);
11391 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11393 getpkt (&rs->buf, &rs->buf_size, 0);
11395 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11397 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11398 error (_("Could not disable branch tracing for %s: %s"),
11399 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11401 error (_("Could not disable branch tracing for %s."),
11402 target_pid_to_str (tinfo->ptid));
11408 /* Teardown branch tracing. */
11411 remote_teardown_btrace (struct btrace_target_info *tinfo)
11413 /* We must not talk to the target during teardown. */
11417 /* Read the branch trace. */
11419 static VEC (btrace_block_s) *
11420 remote_read_btrace (struct btrace_target_info *tinfo,
11421 enum btrace_read_type type)
11423 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11424 struct remote_state *rs = get_remote_state ();
11425 VEC (btrace_block_s) *btrace = NULL;
11429 if (packet->support != PACKET_ENABLE)
11430 error (_("Target does not support branch tracing."));
11432 #if !defined(HAVE_LIBEXPAT)
11433 error (_("Cannot process branch tracing result. XML parsing not supported."));
11438 case btrace_read_all:
11441 case btrace_read_new:
11445 internal_error (__FILE__, __LINE__,
11446 _("Bad branch tracing read type: %u."),
11447 (unsigned int) type);
11450 xml = target_read_stralloc (¤t_target,
11451 TARGET_OBJECT_BTRACE, annex);
11454 struct cleanup *cleanup = make_cleanup (xfree, xml);
11456 btrace = parse_xml_btrace (xml);
11457 do_cleanups (cleanup);
11464 remote_augmented_libraries_svr4_read (void)
11466 struct remote_state *rs = get_remote_state ();
11468 return rs->augmented_libraries_svr4_read;
11472 init_remote_ops (void)
11474 remote_ops.to_shortname = "remote";
11475 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11476 remote_ops.to_doc =
11477 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11478 Specify the serial device it is connected to\n\
11479 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11480 remote_ops.to_open = remote_open;
11481 remote_ops.to_close = remote_close;
11482 remote_ops.to_detach = remote_detach;
11483 remote_ops.to_disconnect = remote_disconnect;
11484 remote_ops.to_resume = remote_resume;
11485 remote_ops.to_wait = remote_wait;
11486 remote_ops.to_fetch_registers = remote_fetch_registers;
11487 remote_ops.to_store_registers = remote_store_registers;
11488 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11489 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
11490 remote_ops.to_files_info = remote_files_info;
11491 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11492 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11493 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11494 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11495 remote_ops.to_watchpoint_addr_within_range =
11496 remote_watchpoint_addr_within_range;
11497 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11498 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11499 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11500 remote_ops.to_region_ok_for_hw_watchpoint
11501 = remote_region_ok_for_hw_watchpoint;
11502 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11503 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11504 remote_ops.to_kill = remote_kill;
11505 remote_ops.to_load = generic_load;
11506 remote_ops.to_mourn_inferior = remote_mourn;
11507 remote_ops.to_pass_signals = remote_pass_signals;
11508 remote_ops.to_program_signals = remote_program_signals;
11509 remote_ops.to_thread_alive = remote_thread_alive;
11510 remote_ops.to_find_new_threads = remote_threads_info;
11511 remote_ops.to_pid_to_str = remote_pid_to_str;
11512 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11513 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11514 remote_ops.to_stop = remote_stop;
11515 remote_ops.to_xfer_partial = remote_xfer_partial;
11516 remote_ops.to_rcmd = remote_rcmd;
11517 remote_ops.to_log_command = serial_log_command;
11518 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11519 remote_ops.to_stratum = process_stratum;
11520 remote_ops.to_has_all_memory = default_child_has_all_memory;
11521 remote_ops.to_has_memory = default_child_has_memory;
11522 remote_ops.to_has_stack = default_child_has_stack;
11523 remote_ops.to_has_registers = default_child_has_registers;
11524 remote_ops.to_has_execution = default_child_has_execution;
11525 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11526 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11527 remote_ops.to_magic = OPS_MAGIC;
11528 remote_ops.to_memory_map = remote_memory_map;
11529 remote_ops.to_flash_erase = remote_flash_erase;
11530 remote_ops.to_flash_done = remote_flash_done;
11531 remote_ops.to_read_description = remote_read_description;
11532 remote_ops.to_search_memory = remote_search_memory;
11533 remote_ops.to_can_async_p = remote_can_async_p;
11534 remote_ops.to_is_async_p = remote_is_async_p;
11535 remote_ops.to_async = remote_async;
11536 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11537 remote_ops.to_terminal_ours = remote_terminal_ours;
11538 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11539 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11540 remote_ops.to_supports_disable_randomization
11541 = remote_supports_disable_randomization;
11542 remote_ops.to_fileio_open = remote_hostio_open;
11543 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11544 remote_ops.to_fileio_pread = remote_hostio_pread;
11545 remote_ops.to_fileio_close = remote_hostio_close;
11546 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11547 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11548 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11549 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11550 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11551 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11552 remote_ops.to_trace_init = remote_trace_init;
11553 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11554 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11555 remote_ops.to_download_trace_state_variable
11556 = remote_download_trace_state_variable;
11557 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11558 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11559 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11560 remote_ops.to_trace_start = remote_trace_start;
11561 remote_ops.to_get_trace_status = remote_get_trace_status;
11562 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11563 remote_ops.to_trace_stop = remote_trace_stop;
11564 remote_ops.to_trace_find = remote_trace_find;
11565 remote_ops.to_get_trace_state_variable_value
11566 = remote_get_trace_state_variable_value;
11567 remote_ops.to_save_trace_data = remote_save_trace_data;
11568 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11569 remote_ops.to_upload_trace_state_variables
11570 = remote_upload_trace_state_variables;
11571 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11572 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11573 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11574 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11575 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11576 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11577 remote_ops.to_core_of_thread = remote_core_of_thread;
11578 remote_ops.to_verify_memory = remote_verify_memory;
11579 remote_ops.to_get_tib_address = remote_get_tib_address;
11580 remote_ops.to_set_permissions = remote_set_permissions;
11581 remote_ops.to_static_tracepoint_marker_at
11582 = remote_static_tracepoint_marker_at;
11583 remote_ops.to_static_tracepoint_markers_by_strid
11584 = remote_static_tracepoint_markers_by_strid;
11585 remote_ops.to_traceframe_info = remote_traceframe_info;
11586 remote_ops.to_use_agent = remote_use_agent;
11587 remote_ops.to_can_use_agent = remote_can_use_agent;
11588 remote_ops.to_supports_btrace = remote_supports_btrace;
11589 remote_ops.to_enable_btrace = remote_enable_btrace;
11590 remote_ops.to_disable_btrace = remote_disable_btrace;
11591 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11592 remote_ops.to_read_btrace = remote_read_btrace;
11593 remote_ops.to_augmented_libraries_svr4_read =
11594 remote_augmented_libraries_svr4_read;
11597 /* Set up the extended remote vector by making a copy of the standard
11598 remote vector and adding to it. */
11601 init_extended_remote_ops (void)
11603 extended_remote_ops = remote_ops;
11605 extended_remote_ops.to_shortname = "extended-remote";
11606 extended_remote_ops.to_longname =
11607 "Extended remote serial target in gdb-specific protocol";
11608 extended_remote_ops.to_doc =
11609 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11610 Specify the serial device it is connected to (e.g. /dev/ttya).";
11611 extended_remote_ops.to_open = extended_remote_open;
11612 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11613 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11614 extended_remote_ops.to_detach = extended_remote_detach;
11615 extended_remote_ops.to_attach = extended_remote_attach;
11616 extended_remote_ops.to_kill = extended_remote_kill;
11617 extended_remote_ops.to_supports_disable_randomization
11618 = extended_remote_supports_disable_randomization;
11622 remote_can_async_p (void)
11624 if (!target_async_permitted)
11625 /* We only enable async when the user specifically asks for it. */
11628 /* We're async whenever the serial device is. */
11629 return serial_can_async_p (remote_desc);
11633 remote_is_async_p (void)
11635 if (!target_async_permitted)
11636 /* We only enable async when the user specifically asks for it. */
11639 /* We're async whenever the serial device is. */
11640 return serial_is_async_p (remote_desc);
11643 /* Pass the SERIAL event on and up to the client. One day this code
11644 will be able to delay notifying the client of an event until the
11645 point where an entire packet has been received. */
11647 static void (*async_client_callback) (enum inferior_event_type event_type,
11649 static void *async_client_context;
11650 static serial_event_ftype remote_async_serial_handler;
11653 remote_async_serial_handler (struct serial *scb, void *context)
11655 /* Don't propogate error information up to the client. Instead let
11656 the client find out about the error by querying the target. */
11657 async_client_callback (INF_REG_EVENT, async_client_context);
11661 remote_async_inferior_event_handler (gdb_client_data data)
11663 inferior_event_handler (INF_REG_EVENT, NULL);
11667 remote_async (void (*callback) (enum inferior_event_type event_type,
11668 void *context), void *context)
11670 if (callback != NULL)
11672 serial_async (remote_desc, remote_async_serial_handler, NULL);
11673 async_client_callback = callback;
11674 async_client_context = context;
11677 serial_async (remote_desc, NULL, NULL);
11681 set_remote_cmd (char *args, int from_tty)
11683 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
11687 show_remote_cmd (char *args, int from_tty)
11689 /* We can't just use cmd_show_list here, because we want to skip
11690 the redundant "show remote Z-packet" and the legacy aliases. */
11691 struct cleanup *showlist_chain;
11692 struct cmd_list_element *list = remote_show_cmdlist;
11693 struct ui_out *uiout = current_uiout;
11695 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11696 for (; list != NULL; list = list->next)
11697 if (strcmp (list->name, "Z-packet") == 0)
11699 else if (list->type == not_set_cmd)
11700 /* Alias commands are exactly like the original, except they
11701 don't have the normal type. */
11705 struct cleanup *option_chain
11706 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11708 ui_out_field_string (uiout, "name", list->name);
11709 ui_out_text (uiout, ": ");
11710 if (list->type == show_cmd)
11711 do_show_command ((char *) NULL, from_tty, list);
11713 cmd_func (list, NULL, from_tty);
11714 /* Close the tuple. */
11715 do_cleanups (option_chain);
11718 /* Close the tuple. */
11719 do_cleanups (showlist_chain);
11723 /* Function to be called whenever a new objfile (shlib) is detected. */
11725 remote_new_objfile (struct objfile *objfile)
11727 if (remote_desc != 0) /* Have a remote connection. */
11728 remote_check_symbols ();
11731 /* Pull all the tracepoints defined on the target and create local
11732 data structures representing them. We don't want to create real
11733 tracepoints yet, we don't want to mess up the user's existing
11737 remote_upload_tracepoints (struct uploaded_tp **utpp)
11739 struct remote_state *rs = get_remote_state ();
11742 /* Ask for a first packet of tracepoint definition. */
11744 getpkt (&rs->buf, &rs->buf_size, 0);
11746 while (*p && *p != 'l')
11748 parse_tracepoint_definition (p, utpp);
11749 /* Ask for another packet of tracepoint definition. */
11751 getpkt (&rs->buf, &rs->buf_size, 0);
11758 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
11760 struct remote_state *rs = get_remote_state ();
11763 /* Ask for a first packet of variable definition. */
11765 getpkt (&rs->buf, &rs->buf_size, 0);
11767 while (*p && *p != 'l')
11769 parse_tsv_definition (p, utsvp);
11770 /* Ask for another packet of variable definition. */
11772 getpkt (&rs->buf, &rs->buf_size, 0);
11778 /* The "set/show range-stepping" show hook. */
11781 show_range_stepping (struct ui_file *file, int from_tty,
11782 struct cmd_list_element *c,
11785 fprintf_filtered (file,
11786 _("Debugger's willingness to use range stepping "
11787 "is %s.\n"), value);
11790 /* The "set/show range-stepping" set hook. */
11793 set_range_stepping (char *ignore_args, int from_tty,
11794 struct cmd_list_element *c)
11796 /* Whene enabling, check whether range stepping is actually
11797 supported by the target, and warn if not. */
11798 if (use_range_stepping)
11800 if (remote_desc != NULL)
11802 struct remote_state *rs = get_remote_state ();
11804 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
11805 remote_vcont_probe (rs);
11807 if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
11808 && rs->supports_vCont.r)
11812 warning (_("Range stepping is not supported by the current target"));
11817 _initialize_remote (void)
11819 struct remote_state *rs;
11820 struct cmd_list_element *cmd;
11821 const char *cmd_name;
11823 /* architecture specific data */
11824 remote_gdbarch_data_handle =
11825 gdbarch_data_register_post_init (init_remote_state);
11826 remote_g_packet_data_handle =
11827 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11829 /* Initialize the per-target state. At the moment there is only one
11830 of these, not one per target. Only one target is active at a
11831 time. The default buffer size is unimportant; it will be expanded
11832 whenever a larger buffer is needed. */
11833 rs = get_remote_state_raw ();
11834 rs->buf_size = 400;
11835 rs->buf = xmalloc (rs->buf_size);
11837 init_remote_ops ();
11838 add_target (&remote_ops);
11840 init_extended_remote_ops ();
11841 add_target (&extended_remote_ops);
11843 /* Hook into new objfile notification. */
11844 observer_attach_new_objfile (remote_new_objfile);
11845 /* We're no longer interested in notification events of an inferior
11847 observer_attach_inferior_exit (discard_pending_stop_replies);
11849 /* Set up signal handlers. */
11850 sigint_remote_token =
11851 create_async_signal_handler (async_remote_interrupt, NULL);
11852 sigint_remote_twice_token =
11853 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11856 init_remote_threadtests ();
11859 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11860 /* set/show remote ... */
11862 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11863 Remote protocol specific variables\n\
11864 Configure various remote-protocol specific variables such as\n\
11865 the packets being used"),
11866 &remote_set_cmdlist, "set remote ",
11867 0 /* allow-unknown */, &setlist);
11868 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11869 Remote protocol specific variables\n\
11870 Configure various remote-protocol specific variables such as\n\
11871 the packets being used"),
11872 &remote_show_cmdlist, "show remote ",
11873 0 /* allow-unknown */, &showlist);
11875 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11876 Compare section data on target to the exec file.\n\
11877 Argument is a single section name (default: all loaded sections)."),
11880 add_cmd ("packet", class_maintenance, packet_command, _("\
11881 Send an arbitrary packet to a remote target.\n\
11882 maintenance packet TEXT\n\
11883 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11884 this command sends the string TEXT to the inferior, and displays the\n\
11885 response packet. GDB supplies the initial `$' character, and the\n\
11886 terminating `#' character and checksum."),
11889 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11890 Set whether to send break if interrupted."), _("\
11891 Show whether to send break if interrupted."), _("\
11892 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11893 set_remotebreak, show_remotebreak,
11894 &setlist, &showlist);
11895 cmd_name = "remotebreak";
11896 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11897 deprecate_cmd (cmd, "set remote interrupt-sequence");
11898 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11899 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11900 deprecate_cmd (cmd, "show remote interrupt-sequence");
11902 add_setshow_enum_cmd ("interrupt-sequence", class_support,
11903 interrupt_sequence_modes, &interrupt_sequence_mode,
11905 Set interrupt sequence to remote target."), _("\
11906 Show interrupt sequence to remote target."), _("\
11907 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11908 NULL, show_interrupt_sequence,
11909 &remote_set_cmdlist,
11910 &remote_show_cmdlist);
11912 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11913 &interrupt_on_connect, _("\
11914 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11915 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11916 If set, interrupt sequence is sent to remote target."),
11918 &remote_set_cmdlist, &remote_show_cmdlist);
11920 /* Install commands for configuring memory read/write packets. */
11922 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11923 Set the maximum number of bytes per memory write packet (deprecated)."),
11925 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11926 Show the maximum number of bytes per memory write packet (deprecated)."),
11928 add_cmd ("memory-write-packet-size", no_class,
11929 set_memory_write_packet_size, _("\
11930 Set the maximum number of bytes per memory-write packet.\n\
11931 Specify the number of bytes in a packet or 0 (zero) for the\n\
11932 default packet size. The actual limit is further reduced\n\
11933 dependent on the target. Specify ``fixed'' to disable the\n\
11934 further restriction and ``limit'' to enable that restriction."),
11935 &remote_set_cmdlist);
11936 add_cmd ("memory-read-packet-size", no_class,
11937 set_memory_read_packet_size, _("\
11938 Set the maximum number of bytes per memory-read packet.\n\
11939 Specify the number of bytes in a packet or 0 (zero) for the\n\
11940 default packet size. The actual limit is further reduced\n\
11941 dependent on the target. Specify ``fixed'' to disable the\n\
11942 further restriction and ``limit'' to enable that restriction."),
11943 &remote_set_cmdlist);
11944 add_cmd ("memory-write-packet-size", no_class,
11945 show_memory_write_packet_size,
11946 _("Show the maximum number of bytes per memory-write packet."),
11947 &remote_show_cmdlist);
11948 add_cmd ("memory-read-packet-size", no_class,
11949 show_memory_read_packet_size,
11950 _("Show the maximum number of bytes per memory-read packet."),
11951 &remote_show_cmdlist);
11953 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11954 &remote_hw_watchpoint_limit, _("\
11955 Set the maximum number of target hardware watchpoints."), _("\
11956 Show the maximum number of target hardware watchpoints."), _("\
11957 Specify a negative limit for unlimited."),
11958 NULL, NULL, /* FIXME: i18n: The maximum
11959 number of target hardware
11960 watchpoints is %s. */
11961 &remote_set_cmdlist, &remote_show_cmdlist);
11962 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11963 &remote_hw_watchpoint_length_limit, _("\
11964 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11965 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11966 Specify a negative limit for unlimited."),
11967 NULL, NULL, /* FIXME: i18n: The maximum
11968 length (in bytes) of a target
11969 hardware watchpoint is %s. */
11970 &remote_set_cmdlist, &remote_show_cmdlist);
11971 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11972 &remote_hw_breakpoint_limit, _("\
11973 Set the maximum number of target hardware breakpoints."), _("\
11974 Show the maximum number of target hardware breakpoints."), _("\
11975 Specify a negative limit for unlimited."),
11976 NULL, NULL, /* FIXME: i18n: The maximum
11977 number of target hardware
11978 breakpoints is %s. */
11979 &remote_set_cmdlist, &remote_show_cmdlist);
11981 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
11982 &remote_address_size, _("\
11983 Set the maximum size of the address (in bits) in a memory packet."), _("\
11984 Show the maximum size of the address (in bits) in a memory packet."), NULL,
11986 NULL, /* FIXME: i18n: */
11987 &setlist, &showlist);
11989 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
11990 "X", "binary-download", 1);
11992 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
11993 "vCont", "verbose-resume", 0);
11995 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11996 "QPassSignals", "pass-signals", 0);
11998 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
11999 "QProgramSignals", "program-signals", 0);
12001 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12002 "qSymbol", "symbol-lookup", 0);
12004 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12005 "P", "set-register", 1);
12007 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12008 "p", "fetch-register", 1);
12010 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12011 "Z0", "software-breakpoint", 0);
12013 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12014 "Z1", "hardware-breakpoint", 0);
12016 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12017 "Z2", "write-watchpoint", 0);
12019 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12020 "Z3", "read-watchpoint", 0);
12022 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12023 "Z4", "access-watchpoint", 0);
12025 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12026 "qXfer:auxv:read", "read-aux-vector", 0);
12028 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12029 "qXfer:features:read", "target-features", 0);
12031 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12032 "qXfer:libraries:read", "library-info", 0);
12034 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12035 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12037 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12038 "qXfer:memory-map:read", "memory-map", 0);
12040 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12041 "qXfer:spu:read", "read-spu-object", 0);
12043 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12044 "qXfer:spu:write", "write-spu-object", 0);
12046 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12047 "qXfer:osdata:read", "osdata", 0);
12049 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12050 "qXfer:threads:read", "threads", 0);
12052 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12053 "qXfer:siginfo:read", "read-siginfo-object", 0);
12055 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12056 "qXfer:siginfo:write", "write-siginfo-object", 0);
12058 add_packet_config_cmd
12059 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12060 "qXfer:traceframe-info:read", "traceframe-info", 0);
12062 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12063 "qXfer:uib:read", "unwind-info-block", 0);
12065 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12066 "qGetTLSAddr", "get-thread-local-storage-address",
12069 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12070 "qGetTIBAddr", "get-thread-information-block-address",
12073 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12074 "bc", "reverse-continue", 0);
12076 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12077 "bs", "reverse-step", 0);
12079 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12080 "qSupported", "supported-packets", 0);
12082 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12083 "qSearch:memory", "search-memory", 0);
12085 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12086 "qTStatus", "trace-status", 0);
12088 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12089 "vFile:open", "hostio-open", 0);
12091 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12092 "vFile:pread", "hostio-pread", 0);
12094 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12095 "vFile:pwrite", "hostio-pwrite", 0);
12097 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12098 "vFile:close", "hostio-close", 0);
12100 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12101 "vFile:unlink", "hostio-unlink", 0);
12103 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12104 "vFile:readlink", "hostio-readlink", 0);
12106 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12107 "vAttach", "attach", 0);
12109 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12112 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12113 "QStartNoAckMode", "noack", 0);
12115 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12116 "vKill", "kill", 0);
12118 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12119 "qAttached", "query-attached", 0);
12121 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12122 "ConditionalTracepoints",
12123 "conditional-tracepoints", 0);
12125 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12126 "ConditionalBreakpoints",
12127 "conditional-breakpoints", 0);
12129 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12130 "BreakpointCommands",
12131 "breakpoint-commands", 0);
12133 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12134 "FastTracepoints", "fast-tracepoints", 0);
12136 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12137 "TracepointSource", "TracepointSource", 0);
12139 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12140 "QAllow", "allow", 0);
12142 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12143 "StaticTracepoints", "static-tracepoints", 0);
12145 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12146 "InstallInTrace", "install-in-trace", 0);
12148 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12149 "qXfer:statictrace:read", "read-sdata-object", 0);
12151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12152 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12154 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12155 "QDisableRandomization", "disable-randomization", 0);
12157 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12158 "QAgent", "agent", 0);
12160 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12161 "QTBuffer:size", "trace-buffer-size", 0);
12163 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12164 "Qbtrace:off", "disable-btrace", 0);
12166 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12167 "Qbtrace:bts", "enable-btrace", 0);
12169 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12170 "qXfer:btrace", "read-btrace", 0);
12172 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12173 Z sub-packet has its own set and show commands, but users may
12174 have sets to this variable in their .gdbinit files (or in their
12176 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12177 &remote_Z_packet_detect, _("\
12178 Set use of remote protocol `Z' packets"), _("\
12179 Show use of remote protocol `Z' packets "), _("\
12180 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12182 set_remote_protocol_Z_packet_cmd,
12183 show_remote_protocol_Z_packet_cmd,
12184 /* FIXME: i18n: Use of remote protocol
12185 `Z' packets is %s. */
12186 &remote_set_cmdlist, &remote_show_cmdlist);
12188 add_prefix_cmd ("remote", class_files, remote_command, _("\
12189 Manipulate files on the remote system\n\
12190 Transfer files to and from the remote target system."),
12191 &remote_cmdlist, "remote ",
12192 0 /* allow-unknown */, &cmdlist);
12194 add_cmd ("put", class_files, remote_put_command,
12195 _("Copy a local file to the remote system."),
12198 add_cmd ("get", class_files, remote_get_command,
12199 _("Copy a remote file to the local system."),
12202 add_cmd ("delete", class_files, remote_delete_command,
12203 _("Delete a remote file."),
12206 remote_exec_file = xstrdup ("");
12207 add_setshow_string_noescape_cmd ("exec-file", class_files,
12208 &remote_exec_file, _("\
12209 Set the remote pathname for \"run\""), _("\
12210 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12211 &remote_set_cmdlist, &remote_show_cmdlist);
12213 add_setshow_boolean_cmd ("range-stepping", class_run,
12214 &use_range_stepping, _("\
12215 Enable or disable range stepping."), _("\
12216 Show whether target-assisted range stepping is enabled."), _("\
12217 If on, and the target supports it, when stepping a source line, GDB\n\
12218 tells the target to step the corresponding range of addresses itself instead\n\
12219 of issuing multiple single-steps. This speeds up source level\n\
12220 stepping. If off, GDB always issues single-steps, even if range\n\
12221 stepping is supported by the target. The default is on."),
12222 set_range_stepping,
12223 show_range_stepping,
12227 /* Eventually initialize fileio. See fileio.c */
12228 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12230 /* Take advantage of the fact that the LWP field is not used, to tag
12231 special ptids with it set to != 0. */
12232 magic_null_ptid = ptid_build (42000, 1, -1);
12233 not_sent_ptid = ptid_build (42000, 1, -2);
12234 any_thread_ptid = ptid_build (42000, 1, 0);
12236 target_buf_size = 2048;
12237 target_buf = xmalloc (target_buf_size);