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 async_cleanup_sigint_signal_handler (void *dummy);
92 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
93 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
94 int forever, int *is_notif);
96 static void async_handle_remote_sigint (int);
97 static void async_handle_remote_sigint_twice (int);
99 static void remote_files_info (struct target_ops *ignore);
101 static void remote_prepare_to_store (struct regcache *regcache);
103 static void remote_open (char *name, int from_tty);
105 static void extended_remote_open (char *name, int from_tty);
107 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
109 static void remote_close (void);
111 static void remote_mourn (struct target_ops *ops);
113 static void extended_remote_restart (void);
115 static void extended_remote_mourn (struct target_ops *);
117 static void remote_mourn_1 (struct target_ops *);
119 static void remote_send (char **buf, long *sizeof_buf_p);
121 static int readchar (int timeout);
123 static void remote_serial_write (const char *str, int len);
125 static void remote_kill (struct target_ops *ops);
127 static int tohex (int nib);
129 static int remote_can_async_p (void);
131 static int remote_is_async_p (void);
133 static void remote_async (void (*callback) (enum inferior_event_type event_type,
134 void *context), void *context);
136 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
138 static void sync_remote_interrupt_twice (int signo);
140 static void interrupt_query (void);
142 static void set_general_thread (struct ptid ptid);
143 static void set_continue_thread (struct ptid ptid);
145 static void get_offsets (void);
147 static void skip_frame (void);
149 static long read_frame (char **buf_p, long *sizeof_buf);
151 static int hexnumlen (ULONGEST num);
153 static void init_remote_ops (void);
155 static void init_extended_remote_ops (void);
157 static void remote_stop (ptid_t);
159 static int ishex (int ch, int *val);
161 static int stubhex (int ch);
163 static int hexnumstr (char *, ULONGEST);
165 static int hexnumnstr (char *, ULONGEST, int);
167 static CORE_ADDR remote_address_masked (CORE_ADDR);
169 static void print_packet (char *);
171 static void compare_sections_command (char *, int);
173 static void packet_command (char *, int);
175 static int stub_unpack_int (char *buff, int fieldlength);
177 static ptid_t remote_current_thread (ptid_t oldptid);
179 static void remote_find_new_threads (void);
181 static void record_currthread (ptid_t currthread);
183 static int fromhex (int a);
185 static int putpkt_binary (char *buf, int cnt);
187 static void check_binary_download (CORE_ADDR addr);
189 struct packet_config;
191 static void show_packet_config_cmd (struct packet_config *config);
193 static void update_packet_config (struct packet_config *config);
195 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
196 struct cmd_list_element *c);
198 static void show_remote_protocol_packet_cmd (struct ui_file *file,
200 struct cmd_list_element *c,
203 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
204 static ptid_t read_ptid (char *buf, char **obuf);
206 static void remote_set_permissions (void);
209 static int remote_get_trace_status (struct trace_status *ts);
211 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
213 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
215 static void remote_query_supported (void);
217 static void remote_check_symbols (void);
219 void _initialize_remote (void);
222 static void stop_reply_xfree (struct stop_reply *);
223 static void remote_parse_stop_reply (char *, struct stop_reply *);
224 static void push_stop_reply (struct stop_reply *);
225 static void discard_pending_stop_replies (struct inferior *);
226 static int peek_stop_reply (ptid_t ptid);
228 static void remote_async_inferior_event_handler (gdb_client_data);
230 static void remote_terminal_ours (void);
232 static int remote_read_description_p (struct target_ops *target);
234 static void remote_console_output (char *msg);
236 static int remote_supports_cond_breakpoints (void);
238 static int remote_can_run_breakpoint_commands (void);
242 static struct cmd_list_element *remote_cmdlist;
244 /* For "set remote" and "show remote". */
246 static struct cmd_list_element *remote_set_cmdlist;
247 static struct cmd_list_element *remote_show_cmdlist;
249 /* Stub vCont actions support.
251 Each field is a boolean flag indicating whether the stub reports
252 support for the corresponding action. */
254 struct vCont_action_support
263 /* Controls whether GDB is willing to use range stepping. */
265 static int use_range_stepping = 1;
267 /* Description of the remote protocol state for the currently
268 connected target. This is per-target state, and independent of the
269 selected architecture. */
273 /* A buffer to use for incoming packets, and its current size. The
274 buffer is grown dynamically for larger incoming packets.
275 Outgoing packets may also be constructed in this buffer.
276 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
277 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
282 /* True if we're going through initial connection setup (finding out
283 about the remote side's threads, relocating symbols, etc.). */
286 /* If we negotiated packet size explicitly (and thus can bypass
287 heuristics for the largest packet size that will not overflow
288 a buffer in the stub), this will be set to that packet size.
289 Otherwise zero, meaning to use the guessed size. */
290 long explicit_packet_size;
292 /* remote_wait is normally called when the target is running and
293 waits for a stop reply packet. But sometimes we need to call it
294 when the target is already stopped. We can send a "?" packet
295 and have remote_wait read the response. Or, if we already have
296 the response, we can stash it in BUF and tell remote_wait to
297 skip calling getpkt. This flag is set when BUF contains a
298 stop reply packet and the target is not waiting. */
299 int cached_wait_status;
301 /* True, if in no ack mode. That is, neither GDB nor the stub will
302 expect acks from each other. The connection is assumed to be
306 /* True if we're connected in extended remote mode. */
309 /* True if the stub reported support for multi-process
311 int multi_process_aware;
313 /* True if we resumed the target and we're waiting for the target to
314 stop. In the mean time, we can't start another command/query.
315 The remote server wouldn't be ready to process it, so we'd
316 timeout waiting for a reply that would never come and eventually
317 we'd close the connection. This can happen in asynchronous mode
318 because we allow GDB commands while the target is running. */
319 int waiting_for_stop_reply;
321 /* True if the stub reports support for non-stop mode. */
324 /* The status of the stub support for the various vCont actions. */
325 struct vCont_action_support supports_vCont;
327 /* True if the stub reports support for conditional tracepoints. */
328 int cond_tracepoints;
330 /* True if the stub reports support for target-side breakpoint
332 int cond_breakpoints;
334 /* True if the stub reports support for target-side breakpoint
336 int breakpoint_commands;
338 /* True if the stub reports support for fast tracepoints. */
339 int fast_tracepoints;
341 /* True if the stub reports support for static tracepoints. */
342 int static_tracepoints;
344 /* True if the stub reports support for installing tracepoint while
346 int install_in_trace;
348 /* True if the stub can continue running a trace while GDB is
350 int disconnected_tracing;
352 /* True if the stub reports support for enabling and disabling
353 tracepoints while a trace experiment is running. */
354 int enable_disable_tracepoints;
356 /* True if the stub can collect strings using tracenz bytecode. */
359 /* True if the stub supports qXfer:libraries-svr4:read with a
361 int augmented_libraries_svr4_read;
363 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
364 responded to that. */
368 /* Private data that we'll store in (struct thread_info)->private. */
369 struct private_thread_info
376 free_private_thread_info (struct private_thread_info *info)
382 /* Returns true if the multi-process extensions are in effect. */
384 remote_multi_process_p (struct remote_state *rs)
386 return rs->multi_process_aware;
389 /* This data could be associated with a target, but we do not always
390 have access to the current target when we need it, so for now it is
391 static. This will be fine for as long as only one target is in use
393 static struct remote_state remote_state;
395 static struct remote_state *
396 get_remote_state_raw (void)
398 return &remote_state;
401 /* Description of the remote protocol for a given architecture. */
405 long offset; /* Offset into G packet. */
406 long regnum; /* GDB's internal register number. */
407 LONGEST pnum; /* Remote protocol register number. */
408 int in_g_packet; /* Always part of G packet. */
409 /* long size in bytes; == register_size (target_gdbarch (), regnum);
411 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
415 struct remote_arch_state
417 /* Description of the remote protocol registers. */
418 long sizeof_g_packet;
420 /* Description of the remote protocol registers indexed by REGNUM
421 (making an array gdbarch_num_regs in size). */
422 struct packet_reg *regs;
424 /* This is the size (in chars) of the first response to the ``g''
425 packet. It is used as a heuristic when determining the maximum
426 size of memory-read and memory-write packets. A target will
427 typically only reserve a buffer large enough to hold the ``g''
428 packet. The size does not include packet overhead (headers and
430 long actual_register_packet_size;
432 /* This is the maximum size (in chars) of a non read/write packet.
433 It is also used as a cap on the size of read/write packets. */
434 long remote_packet_size;
437 long sizeof_pkt = 2000;
439 /* Utility: generate error from an incoming stub packet. */
441 trace_error (char *buf)
444 return; /* not an error msg */
447 case '1': /* malformed packet error */
448 if (*++buf == '0') /* general case: */
449 error (_("remote.c: error in outgoing packet."));
451 error (_("remote.c: error in outgoing packet at field #%ld."),
452 strtol (buf, NULL, 16));
454 error (_("Target returns error code '%s'."), buf);
458 /* Utility: wait for reply from stub, while accepting "O" packets. */
460 remote_get_noisy_reply (char **buf_p,
463 do /* Loop on reply from remote stub. */
467 QUIT; /* Allow user to bail out with ^C. */
468 getpkt (buf_p, sizeof_buf, 0);
472 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
475 CORE_ADDR from, to, org_to;
477 int adjusted_size = 0;
478 volatile struct gdb_exception ex;
480 p = buf + strlen ("qRelocInsn:");
481 pp = unpack_varlen_hex (p, &ul);
483 error (_("invalid qRelocInsn packet: %s"), buf);
487 unpack_varlen_hex (p, &ul);
492 TRY_CATCH (ex, RETURN_MASK_ALL)
494 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
498 adjusted_size = to - org_to;
500 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
503 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
505 /* Propagate memory errors silently back to the target.
506 The stub may have limited the range of addresses we
507 can write to, for example. */
512 /* Something unexpectedly bad happened. Be verbose so
513 we can tell what, and propagate the error back to the
514 stub, so it doesn't get stuck waiting for a
516 exception_fprintf (gdb_stderr, ex,
517 _("warning: relocating instruction: "));
521 else if (buf[0] == 'O' && buf[1] != 'K')
522 remote_console_output (buf + 1); /* 'O' message from stub */
524 return buf; /* Here's the actual reply. */
529 /* Handle for retreving the remote protocol data from gdbarch. */
530 static struct gdbarch_data *remote_gdbarch_data_handle;
532 static struct remote_arch_state *
533 get_remote_arch_state (void)
535 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
538 /* Fetch the global remote target state. */
540 static struct remote_state *
541 get_remote_state (void)
543 /* Make sure that the remote architecture state has been
544 initialized, because doing so might reallocate rs->buf. Any
545 function which calls getpkt also needs to be mindful of changes
546 to rs->buf, but this call limits the number of places which run
548 get_remote_arch_state ();
550 return get_remote_state_raw ();
554 compare_pnums (const void *lhs_, const void *rhs_)
556 const struct packet_reg * const *lhs = lhs_;
557 const struct packet_reg * const *rhs = rhs_;
559 if ((*lhs)->pnum < (*rhs)->pnum)
561 else if ((*lhs)->pnum == (*rhs)->pnum)
568 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
570 int regnum, num_remote_regs, offset;
571 struct packet_reg **remote_regs;
573 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
575 struct packet_reg *r = ®s[regnum];
577 if (register_size (gdbarch, regnum) == 0)
578 /* Do not try to fetch zero-sized (placeholder) registers. */
581 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
586 /* Define the g/G packet format as the contents of each register
587 with a remote protocol number, in order of ascending protocol
590 remote_regs = alloca (gdbarch_num_regs (gdbarch)
591 * sizeof (struct packet_reg *));
592 for (num_remote_regs = 0, regnum = 0;
593 regnum < gdbarch_num_regs (gdbarch);
595 if (regs[regnum].pnum != -1)
596 remote_regs[num_remote_regs++] = ®s[regnum];
598 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
601 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
603 remote_regs[regnum]->in_g_packet = 1;
604 remote_regs[regnum]->offset = offset;
605 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
611 /* Given the architecture described by GDBARCH, return the remote
612 protocol register's number and the register's offset in the g/G
613 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
614 If the target does not have a mapping for REGNUM, return false,
615 otherwise, return true. */
618 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
619 int *pnum, int *poffset)
622 struct packet_reg *regs;
623 struct cleanup *old_chain;
625 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
627 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
628 old_chain = make_cleanup (xfree, regs);
630 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
632 *pnum = regs[regnum].pnum;
633 *poffset = regs[regnum].offset;
635 do_cleanups (old_chain);
641 init_remote_state (struct gdbarch *gdbarch)
643 struct remote_state *rs = get_remote_state_raw ();
644 struct remote_arch_state *rsa;
646 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
648 /* Use the architecture to build a regnum<->pnum table, which will be
649 1:1 unless a feature set specifies otherwise. */
650 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
651 gdbarch_num_regs (gdbarch),
654 /* Record the maximum possible size of the g packet - it may turn out
656 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
658 /* Default maximum number of characters in a packet body. Many
659 remote stubs have a hardwired buffer size of 400 bytes
660 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
661 as the maximum packet-size to ensure that the packet and an extra
662 NUL character can always fit in the buffer. This stops GDB
663 trashing stubs that try to squeeze an extra NUL into what is
664 already a full buffer (As of 1999-12-04 that was most stubs). */
665 rsa->remote_packet_size = 400 - 1;
667 /* This one is filled in when a ``g'' packet is received. */
668 rsa->actual_register_packet_size = 0;
670 /* Should rsa->sizeof_g_packet needs more space than the
671 default, adjust the size accordingly. Remember that each byte is
672 encoded as two characters. 32 is the overhead for the packet
673 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
674 (``$NN:G...#NN'') is a better guess, the below has been padded a
676 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
677 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
679 /* Make sure that the packet buffer is plenty big enough for
680 this architecture. */
681 if (rs->buf_size < rsa->remote_packet_size)
683 rs->buf_size = 2 * rsa->remote_packet_size;
684 rs->buf = xrealloc (rs->buf, rs->buf_size);
690 /* Return the current allowed size of a remote packet. This is
691 inferred from the current architecture, and should be used to
692 limit the length of outgoing packets. */
694 get_remote_packet_size (void)
696 struct remote_state *rs = get_remote_state ();
697 struct remote_arch_state *rsa = get_remote_arch_state ();
699 if (rs->explicit_packet_size)
700 return rs->explicit_packet_size;
702 return rsa->remote_packet_size;
705 static struct packet_reg *
706 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
708 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
712 struct packet_reg *r = &rsa->regs[regnum];
714 gdb_assert (r->regnum == regnum);
719 static struct packet_reg *
720 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
724 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
726 struct packet_reg *r = &rsa->regs[i];
734 /* FIXME: graces/2002-08-08: These variables should eventually be
735 bound to an instance of the target object (as in gdbarch-tdep()),
736 when such a thing exists. */
738 /* This is set to the data address of the access causing the target
739 to stop for a watchpoint. */
740 static CORE_ADDR remote_watch_data_address;
742 /* This is non-zero if target stopped for a watchpoint. */
743 static int remote_stopped_by_watchpoint_p;
745 static struct target_ops remote_ops;
747 static struct target_ops extended_remote_ops;
749 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
750 ``forever'' still use the normal timeout mechanism. This is
751 currently used by the ASYNC code to guarentee that target reads
752 during the initial connect always time-out. Once getpkt has been
753 modified to return a timeout indication and, in turn
754 remote_wait()/wait_for_inferior() have gained a timeout parameter
756 static int wait_forever_enabled_p = 1;
758 /* Allow the user to specify what sequence to send to the remote
759 when he requests a program interruption: Although ^C is usually
760 what remote systems expect (this is the default, here), it is
761 sometimes preferable to send a break. On other systems such
762 as the Linux kernel, a break followed by g, which is Magic SysRq g
763 is required in order to interrupt the execution. */
764 const char interrupt_sequence_control_c[] = "Ctrl-C";
765 const char interrupt_sequence_break[] = "BREAK";
766 const char interrupt_sequence_break_g[] = "BREAK-g";
767 static const char *const interrupt_sequence_modes[] =
769 interrupt_sequence_control_c,
770 interrupt_sequence_break,
771 interrupt_sequence_break_g,
774 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
777 show_interrupt_sequence (struct ui_file *file, int from_tty,
778 struct cmd_list_element *c,
781 if (interrupt_sequence_mode == interrupt_sequence_control_c)
782 fprintf_filtered (file,
783 _("Send the ASCII ETX character (Ctrl-c) "
784 "to the remote target to interrupt the "
785 "execution of the program.\n"));
786 else if (interrupt_sequence_mode == interrupt_sequence_break)
787 fprintf_filtered (file,
788 _("send a break signal to the remote target "
789 "to interrupt the execution of the program.\n"));
790 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
791 fprintf_filtered (file,
792 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
793 "the remote target to interrupt the execution "
794 "of Linux kernel.\n"));
796 internal_error (__FILE__, __LINE__,
797 _("Invalid value for interrupt_sequence_mode: %s."),
798 interrupt_sequence_mode);
801 /* This boolean variable specifies whether interrupt_sequence is sent
802 to the remote target when gdb connects to it.
803 This is mostly needed when you debug the Linux kernel: The Linux kernel
804 expects BREAK g which is Magic SysRq g for connecting gdb. */
805 static int interrupt_on_connect = 0;
807 /* This variable is used to implement the "set/show remotebreak" commands.
808 Since these commands are now deprecated in favor of "set/show remote
809 interrupt-sequence", it no longer has any effect on the code. */
810 static int remote_break;
813 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
816 interrupt_sequence_mode = interrupt_sequence_break;
818 interrupt_sequence_mode = interrupt_sequence_control_c;
822 show_remotebreak (struct ui_file *file, int from_tty,
823 struct cmd_list_element *c,
828 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
829 remote_open knows that we don't have a file open when the program
831 static struct serial *remote_desc = NULL;
833 /* This variable sets the number of bits in an address that are to be
834 sent in a memory ("M" or "m") packet. Normally, after stripping
835 leading zeros, the entire address would be sent. This variable
836 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
837 initial implementation of remote.c restricted the address sent in
838 memory packets to ``host::sizeof long'' bytes - (typically 32
839 bits). Consequently, for 64 bit targets, the upper 32 bits of an
840 address was never sent. Since fixing this bug may cause a break in
841 some remote targets this variable is principly provided to
842 facilitate backward compatibility. */
844 static unsigned int remote_address_size;
846 /* Temporary to track who currently owns the terminal. See
847 remote_terminal_* for more details. */
849 static int remote_async_terminal_ours_p;
851 /* The executable file to use for "run" on the remote side. */
853 static char *remote_exec_file = "";
856 /* User configurable variables for the number of characters in a
857 memory read/write packet. MIN (rsa->remote_packet_size,
858 rsa->sizeof_g_packet) is the default. Some targets need smaller
859 values (fifo overruns, et.al.) and some users need larger values
860 (speed up transfers). The variables ``preferred_*'' (the user
861 request), ``current_*'' (what was actually set) and ``forced_*''
862 (Positive - a soft limit, negative - a hard limit). */
864 struct memory_packet_config
871 /* Compute the current size of a read/write packet. Since this makes
872 use of ``actual_register_packet_size'' the computation is dynamic. */
875 get_memory_packet_size (struct memory_packet_config *config)
877 struct remote_state *rs = get_remote_state ();
878 struct remote_arch_state *rsa = get_remote_arch_state ();
880 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
881 law?) that some hosts don't cope very well with large alloca()
882 calls. Eventually the alloca() code will be replaced by calls to
883 xmalloc() and make_cleanups() allowing this restriction to either
884 be lifted or removed. */
885 #ifndef MAX_REMOTE_PACKET_SIZE
886 #define MAX_REMOTE_PACKET_SIZE 16384
888 /* NOTE: 20 ensures we can write at least one byte. */
889 #ifndef MIN_REMOTE_PACKET_SIZE
890 #define MIN_REMOTE_PACKET_SIZE 20
895 if (config->size <= 0)
896 what_they_get = MAX_REMOTE_PACKET_SIZE;
898 what_they_get = config->size;
902 what_they_get = get_remote_packet_size ();
903 /* Limit the packet to the size specified by the user. */
905 && what_they_get > config->size)
906 what_they_get = config->size;
908 /* Limit it to the size of the targets ``g'' response unless we have
909 permission from the stub to use a larger packet size. */
910 if (rs->explicit_packet_size == 0
911 && rsa->actual_register_packet_size > 0
912 && what_they_get > rsa->actual_register_packet_size)
913 what_they_get = rsa->actual_register_packet_size;
915 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
916 what_they_get = MAX_REMOTE_PACKET_SIZE;
917 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
918 what_they_get = MIN_REMOTE_PACKET_SIZE;
920 /* Make sure there is room in the global buffer for this packet
921 (including its trailing NUL byte). */
922 if (rs->buf_size < what_they_get + 1)
924 rs->buf_size = 2 * what_they_get;
925 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
928 return what_they_get;
931 /* Update the size of a read/write packet. If they user wants
932 something really big then do a sanity check. */
935 set_memory_packet_size (char *args, struct memory_packet_config *config)
937 int fixed_p = config->fixed_p;
938 long size = config->size;
941 error (_("Argument required (integer, `fixed' or `limited')."));
942 else if (strcmp (args, "hard") == 0
943 || strcmp (args, "fixed") == 0)
945 else if (strcmp (args, "soft") == 0
946 || strcmp (args, "limit") == 0)
952 size = strtoul (args, &end, 0);
954 error (_("Invalid %s (bad syntax)."), config->name);
956 /* Instead of explicitly capping the size of a packet to
957 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
958 instead allowed to set the size to something arbitrarily
960 if (size > MAX_REMOTE_PACKET_SIZE)
961 error (_("Invalid %s (too large)."), config->name);
965 if (fixed_p && !config->fixed_p)
967 if (! query (_("The target may not be able to correctly handle a %s\n"
968 "of %ld bytes. Change the packet size? "),
970 error (_("Packet size not changed."));
972 /* Update the config. */
973 config->fixed_p = fixed_p;
978 show_memory_packet_size (struct memory_packet_config *config)
980 printf_filtered (_("The %s is %ld. "), config->name, config->size);
982 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
983 get_memory_packet_size (config));
985 printf_filtered (_("Packets are limited to %ld bytes.\n"),
986 get_memory_packet_size (config));
989 static struct memory_packet_config memory_write_packet_config =
991 "memory-write-packet-size",
995 set_memory_write_packet_size (char *args, int from_tty)
997 set_memory_packet_size (args, &memory_write_packet_config);
1001 show_memory_write_packet_size (char *args, int from_tty)
1003 show_memory_packet_size (&memory_write_packet_config);
1007 get_memory_write_packet_size (void)
1009 return get_memory_packet_size (&memory_write_packet_config);
1012 static struct memory_packet_config memory_read_packet_config =
1014 "memory-read-packet-size",
1018 set_memory_read_packet_size (char *args, int from_tty)
1020 set_memory_packet_size (args, &memory_read_packet_config);
1024 show_memory_read_packet_size (char *args, int from_tty)
1026 show_memory_packet_size (&memory_read_packet_config);
1030 get_memory_read_packet_size (void)
1032 long size = get_memory_packet_size (&memory_read_packet_config);
1034 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1035 extra buffer size argument before the memory read size can be
1036 increased beyond this. */
1037 if (size > get_remote_packet_size ())
1038 size = get_remote_packet_size ();
1043 /* Generic configuration support for packets the stub optionally
1044 supports. Allows the user to specify the use of the packet as well
1045 as allowing GDB to auto-detect support in the remote stub. */
1049 PACKET_SUPPORT_UNKNOWN = 0,
1054 struct packet_config
1058 enum auto_boolean detect;
1059 enum packet_support support;
1062 /* Analyze a packet's return value and update the packet config
1073 update_packet_config (struct packet_config *config)
1075 switch (config->detect)
1077 case AUTO_BOOLEAN_TRUE:
1078 config->support = PACKET_ENABLE;
1080 case AUTO_BOOLEAN_FALSE:
1081 config->support = PACKET_DISABLE;
1083 case AUTO_BOOLEAN_AUTO:
1084 config->support = PACKET_SUPPORT_UNKNOWN;
1090 show_packet_config_cmd (struct packet_config *config)
1092 char *support = "internal-error";
1094 switch (config->support)
1097 support = "enabled";
1099 case PACKET_DISABLE:
1100 support = "disabled";
1102 case PACKET_SUPPORT_UNKNOWN:
1103 support = "unknown";
1106 switch (config->detect)
1108 case AUTO_BOOLEAN_AUTO:
1109 printf_filtered (_("Support for the `%s' packet "
1110 "is auto-detected, currently %s.\n"),
1111 config->name, support);
1113 case AUTO_BOOLEAN_TRUE:
1114 case AUTO_BOOLEAN_FALSE:
1115 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1116 config->name, support);
1122 add_packet_config_cmd (struct packet_config *config, const char *name,
1123 const char *title, int legacy)
1129 config->name = name;
1130 config->title = title;
1131 config->detect = AUTO_BOOLEAN_AUTO;
1132 config->support = PACKET_SUPPORT_UNKNOWN;
1133 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1135 show_doc = xstrprintf ("Show current use of remote "
1136 "protocol `%s' (%s) packet",
1138 /* set/show TITLE-packet {auto,on,off} */
1139 cmd_name = xstrprintf ("%s-packet", title);
1140 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1141 &config->detect, set_doc,
1142 show_doc, NULL, /* help_doc */
1143 set_remote_protocol_packet_cmd,
1144 show_remote_protocol_packet_cmd,
1145 &remote_set_cmdlist, &remote_show_cmdlist);
1146 /* The command code copies the documentation strings. */
1149 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1154 legacy_name = xstrprintf ("%s-packet", name);
1155 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1156 &remote_set_cmdlist);
1157 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1158 &remote_show_cmdlist);
1162 static enum packet_result
1163 packet_check_result (const char *buf)
1167 /* The stub recognized the packet request. Check that the
1168 operation succeeded. */
1170 && isxdigit (buf[1]) && isxdigit (buf[2])
1172 /* "Enn" - definitly an error. */
1173 return PACKET_ERROR;
1175 /* Always treat "E." as an error. This will be used for
1176 more verbose error messages, such as E.memtypes. */
1177 if (buf[0] == 'E' && buf[1] == '.')
1178 return PACKET_ERROR;
1180 /* The packet may or may not be OK. Just assume it is. */
1184 /* The stub does not support the packet. */
1185 return PACKET_UNKNOWN;
1188 static enum packet_result
1189 packet_ok (const char *buf, struct packet_config *config)
1191 enum packet_result result;
1193 result = packet_check_result (buf);
1198 /* The stub recognized the packet request. */
1199 switch (config->support)
1201 case PACKET_SUPPORT_UNKNOWN:
1203 fprintf_unfiltered (gdb_stdlog,
1204 "Packet %s (%s) is supported\n",
1205 config->name, config->title);
1206 config->support = PACKET_ENABLE;
1208 case PACKET_DISABLE:
1209 internal_error (__FILE__, __LINE__,
1210 _("packet_ok: attempt to use a disabled packet"));
1216 case PACKET_UNKNOWN:
1217 /* The stub does not support the packet. */
1218 switch (config->support)
1221 if (config->detect == AUTO_BOOLEAN_AUTO)
1222 /* If the stub previously indicated that the packet was
1223 supported then there is a protocol error.. */
1224 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1225 config->name, config->title);
1227 /* The user set it wrong. */
1228 error (_("Enabled packet %s (%s) not recognized by stub"),
1229 config->name, config->title);
1231 case PACKET_SUPPORT_UNKNOWN:
1233 fprintf_unfiltered (gdb_stdlog,
1234 "Packet %s (%s) is NOT supported\n",
1235 config->name, config->title);
1236 config->support = PACKET_DISABLE;
1238 case PACKET_DISABLE:
1260 PACKET_vFile_pwrite,
1262 PACKET_vFile_unlink,
1263 PACKET_vFile_readlink,
1265 PACKET_qXfer_features,
1266 PACKET_qXfer_libraries,
1267 PACKET_qXfer_libraries_svr4,
1268 PACKET_qXfer_memory_map,
1269 PACKET_qXfer_spu_read,
1270 PACKET_qXfer_spu_write,
1271 PACKET_qXfer_osdata,
1272 PACKET_qXfer_threads,
1273 PACKET_qXfer_statictrace_read,
1274 PACKET_qXfer_traceframe_info,
1280 PACKET_QPassSignals,
1281 PACKET_QProgramSignals,
1282 PACKET_qSearch_memory,
1285 PACKET_QStartNoAckMode,
1287 PACKET_qXfer_siginfo_read,
1288 PACKET_qXfer_siginfo_write,
1290 PACKET_ConditionalTracepoints,
1291 PACKET_ConditionalBreakpoints,
1292 PACKET_BreakpointCommands,
1293 PACKET_FastTracepoints,
1294 PACKET_StaticTracepoints,
1295 PACKET_InstallInTrace,
1298 PACKET_TracepointSource,
1301 PACKET_QDisableRandomization,
1303 PACKET_QTBuffer_size,
1306 PACKET_qXfer_btrace,
1310 static struct packet_config remote_protocol_packets[PACKET_MAX];
1313 set_remote_protocol_packet_cmd (char *args, int from_tty,
1314 struct cmd_list_element *c)
1316 struct packet_config *packet;
1318 for (packet = remote_protocol_packets;
1319 packet < &remote_protocol_packets[PACKET_MAX];
1322 if (&packet->detect == c->var)
1324 update_packet_config (packet);
1328 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1333 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1334 struct cmd_list_element *c,
1337 struct packet_config *packet;
1339 for (packet = remote_protocol_packets;
1340 packet < &remote_protocol_packets[PACKET_MAX];
1343 if (&packet->detect == c->var)
1345 show_packet_config_cmd (packet);
1349 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1353 /* Should we try one of the 'Z' requests? */
1357 Z_PACKET_SOFTWARE_BP,
1358 Z_PACKET_HARDWARE_BP,
1365 /* For compatibility with older distributions. Provide a ``set remote
1366 Z-packet ...'' command that updates all the Z packet types. */
1368 static enum auto_boolean remote_Z_packet_detect;
1371 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1372 struct cmd_list_element *c)
1376 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1378 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1379 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1384 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1385 struct cmd_list_element *c,
1390 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1392 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1396 /* Should we try the 'ThreadInfo' query packet?
1398 This variable (NOT available to the user: auto-detect only!)
1399 determines whether GDB will use the new, simpler "ThreadInfo"
1400 query or the older, more complex syntax for thread queries.
1401 This is an auto-detect variable (set to true at each connect,
1402 and set to false when the target fails to recognize it). */
1404 static int use_threadinfo_query;
1405 static int use_threadextra_query;
1407 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1408 static struct async_signal_handler *async_sigint_remote_twice_token;
1409 static struct async_signal_handler *async_sigint_remote_token;
1412 /* Asynchronous signal handle registered as event loop source for
1413 when we have pending events ready to be passed to the core. */
1415 static struct async_event_handler *remote_async_inferior_event_token;
1419 static ptid_t magic_null_ptid;
1420 static ptid_t not_sent_ptid;
1421 static ptid_t any_thread_ptid;
1423 /* These are the threads which we last sent to the remote system. The
1424 TID member will be -1 for all or -2 for not sent yet. */
1426 static ptid_t general_thread;
1427 static ptid_t continue_thread;
1429 /* This is the traceframe which we last selected on the remote system.
1430 It will be -1 if no traceframe is selected. */
1431 static int remote_traceframe_number = -1;
1433 /* Find out if the stub attached to PID (and hence GDB should offer to
1434 detach instead of killing it when bailing out). */
1437 remote_query_attached (int pid)
1439 struct remote_state *rs = get_remote_state ();
1440 size_t size = get_remote_packet_size ();
1442 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1445 if (remote_multi_process_p (rs))
1446 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1448 xsnprintf (rs->buf, size, "qAttached");
1451 getpkt (&rs->buf, &rs->buf_size, 0);
1453 switch (packet_ok (rs->buf,
1454 &remote_protocol_packets[PACKET_qAttached]))
1457 if (strcmp (rs->buf, "1") == 0)
1461 warning (_("Remote failure reply: %s"), rs->buf);
1463 case PACKET_UNKNOWN:
1470 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1471 has been invented by GDB, instead of reported by the target. Since
1472 we can be connected to a remote system before before knowing about
1473 any inferior, mark the target with execution when we find the first
1474 inferior. If ATTACHED is 1, then we had just attached to this
1475 inferior. If it is 0, then we just created this inferior. If it
1476 is -1, then try querying the remote stub to find out if it had
1477 attached to the inferior or not. */
1479 static struct inferior *
1480 remote_add_inferior (int fake_pid_p, int pid, int attached)
1482 struct inferior *inf;
1484 /* Check whether this process we're learning about is to be
1485 considered attached, or if is to be considered to have been
1486 spawned by the stub. */
1488 attached = remote_query_attached (pid);
1490 if (gdbarch_has_global_solist (target_gdbarch ()))
1492 /* If the target shares code across all inferiors, then every
1493 attach adds a new inferior. */
1494 inf = add_inferior (pid);
1496 /* ... and every inferior is bound to the same program space.
1497 However, each inferior may still have its own address
1499 inf->aspace = maybe_new_address_space ();
1500 inf->pspace = current_program_space;
1504 /* In the traditional debugging scenario, there's a 1-1 match
1505 between program/address spaces. We simply bind the inferior
1506 to the program space's address space. */
1507 inf = current_inferior ();
1508 inferior_appeared (inf, pid);
1511 inf->attach_flag = attached;
1512 inf->fake_pid_p = fake_pid_p;
1517 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1518 according to RUNNING. */
1521 remote_add_thread (ptid_t ptid, int running)
1525 set_executing (ptid, running);
1526 set_running (ptid, running);
1529 /* Come here when we learn about a thread id from the remote target.
1530 It may be the first time we hear about such thread, so take the
1531 opportunity to add it to GDB's thread list. In case this is the
1532 first time we're noticing its corresponding inferior, add it to
1533 GDB's inferior list as well. */
1536 remote_notice_new_inferior (ptid_t currthread, int running)
1538 /* If this is a new thread, add it to GDB's thread list.
1539 If we leave it up to WFI to do this, bad things will happen. */
1541 if (in_thread_list (currthread) && is_exited (currthread))
1543 /* We're seeing an event on a thread id we knew had exited.
1544 This has to be a new thread reusing the old id. Add it. */
1545 remote_add_thread (currthread, running);
1549 if (!in_thread_list (currthread))
1551 struct inferior *inf = NULL;
1552 int pid = ptid_get_pid (currthread);
1554 if (ptid_is_pid (inferior_ptid)
1555 && pid == ptid_get_pid (inferior_ptid))
1557 /* inferior_ptid has no thread member yet. This can happen
1558 with the vAttach -> remote_wait,"TAAthread:" path if the
1559 stub doesn't support qC. This is the first stop reported
1560 after an attach, so this is the main thread. Update the
1561 ptid in the thread list. */
1562 if (in_thread_list (pid_to_ptid (pid)))
1563 thread_change_ptid (inferior_ptid, currthread);
1566 remote_add_thread (currthread, running);
1567 inferior_ptid = currthread;
1572 if (ptid_equal (magic_null_ptid, inferior_ptid))
1574 /* inferior_ptid is not set yet. This can happen with the
1575 vRun -> remote_wait,"TAAthread:" path if the stub
1576 doesn't support qC. This is the first stop reported
1577 after an attach, so this is the main thread. Update the
1578 ptid in the thread list. */
1579 thread_change_ptid (inferior_ptid, currthread);
1583 /* When connecting to a target remote, or to a target
1584 extended-remote which already was debugging an inferior, we
1585 may not know about it yet. Add it before adding its child
1586 thread, so notifications are emitted in a sensible order. */
1587 if (!in_inferior_list (ptid_get_pid (currthread)))
1589 struct remote_state *rs = get_remote_state ();
1590 int fake_pid_p = !remote_multi_process_p (rs);
1592 inf = remote_add_inferior (fake_pid_p,
1593 ptid_get_pid (currthread), -1);
1596 /* This is really a new thread. Add it. */
1597 remote_add_thread (currthread, running);
1599 /* If we found a new inferior, let the common code do whatever
1600 it needs to with it (e.g., read shared libraries, insert
1603 notice_new_inferior (currthread, running, 0);
1607 /* Return the private thread data, creating it if necessary. */
1609 static struct private_thread_info *
1610 demand_private_info (ptid_t ptid)
1612 struct thread_info *info = find_thread_ptid (ptid);
1618 info->private = xmalloc (sizeof (*(info->private)));
1619 info->private_dtor = free_private_thread_info;
1620 info->private->core = -1;
1621 info->private->extra = 0;
1624 return info->private;
1627 /* Call this function as a result of
1628 1) A halt indication (T packet) containing a thread id
1629 2) A direct query of currthread
1630 3) Successful execution of set thread */
1633 record_currthread (ptid_t currthread)
1635 general_thread = currthread;
1638 static char *last_pass_packet;
1640 /* If 'QPassSignals' is supported, tell the remote stub what signals
1641 it can simply pass through to the inferior without reporting. */
1644 remote_pass_signals (int numsigs, unsigned char *pass_signals)
1646 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1648 char *pass_packet, *p;
1651 gdb_assert (numsigs < 256);
1652 for (i = 0; i < numsigs; i++)
1654 if (pass_signals[i])
1657 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1658 strcpy (pass_packet, "QPassSignals:");
1659 p = pass_packet + strlen (pass_packet);
1660 for (i = 0; i < numsigs; i++)
1662 if (pass_signals[i])
1665 *p++ = tohex (i >> 4);
1666 *p++ = tohex (i & 15);
1675 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1677 struct remote_state *rs = get_remote_state ();
1678 char *buf = rs->buf;
1680 putpkt (pass_packet);
1681 getpkt (&rs->buf, &rs->buf_size, 0);
1682 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1683 if (last_pass_packet)
1684 xfree (last_pass_packet);
1685 last_pass_packet = pass_packet;
1688 xfree (pass_packet);
1692 /* The last QProgramSignals packet sent to the target. We bypass
1693 sending a new program signals list down to the target if the new
1694 packet is exactly the same as the last we sent. IOW, we only let
1695 the target know about program signals list changes. */
1697 static char *last_program_signals_packet;
1699 /* If 'QProgramSignals' is supported, tell the remote stub what
1700 signals it should pass through to the inferior when detaching. */
1703 remote_program_signals (int numsigs, unsigned char *signals)
1705 if (remote_protocol_packets[PACKET_QProgramSignals].support != PACKET_DISABLE)
1710 gdb_assert (numsigs < 256);
1711 for (i = 0; i < numsigs; i++)
1716 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1717 strcpy (packet, "QProgramSignals:");
1718 p = packet + strlen (packet);
1719 for (i = 0; i < numsigs; i++)
1721 if (signal_pass_state (i))
1724 *p++ = tohex (i >> 4);
1725 *p++ = tohex (i & 15);
1734 if (!last_program_signals_packet
1735 || strcmp (last_program_signals_packet, packet) != 0)
1737 struct remote_state *rs = get_remote_state ();
1738 char *buf = rs->buf;
1741 getpkt (&rs->buf, &rs->buf_size, 0);
1742 packet_ok (buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1743 xfree (last_program_signals_packet);
1744 last_program_signals_packet = packet;
1751 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1752 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1753 thread. If GEN is set, set the general thread, if not, then set
1754 the step/continue thread. */
1756 set_thread (struct ptid ptid, int gen)
1758 struct remote_state *rs = get_remote_state ();
1759 ptid_t state = gen ? general_thread : continue_thread;
1760 char *buf = rs->buf;
1761 char *endbuf = rs->buf + get_remote_packet_size ();
1763 if (ptid_equal (state, ptid))
1767 *buf++ = gen ? 'g' : 'c';
1768 if (ptid_equal (ptid, magic_null_ptid))
1769 xsnprintf (buf, endbuf - buf, "0");
1770 else if (ptid_equal (ptid, any_thread_ptid))
1771 xsnprintf (buf, endbuf - buf, "0");
1772 else if (ptid_equal (ptid, minus_one_ptid))
1773 xsnprintf (buf, endbuf - buf, "-1");
1775 write_ptid (buf, endbuf, ptid);
1777 getpkt (&rs->buf, &rs->buf_size, 0);
1779 general_thread = ptid;
1781 continue_thread = ptid;
1785 set_general_thread (struct ptid ptid)
1787 set_thread (ptid, 1);
1791 set_continue_thread (struct ptid ptid)
1793 set_thread (ptid, 0);
1796 /* Change the remote current process. Which thread within the process
1797 ends up selected isn't important, as long as it is the same process
1798 as what INFERIOR_PTID points to.
1800 This comes from that fact that there is no explicit notion of
1801 "selected process" in the protocol. The selected process for
1802 general operations is the process the selected general thread
1806 set_general_process (void)
1808 struct remote_state *rs = get_remote_state ();
1810 /* If the remote can't handle multiple processes, don't bother. */
1811 if (!rs->extended || !remote_multi_process_p (rs))
1814 /* We only need to change the remote current thread if it's pointing
1815 at some other process. */
1816 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1817 set_general_thread (inferior_ptid);
1821 /* Return nonzero if the thread PTID is still alive on the remote
1825 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1827 struct remote_state *rs = get_remote_state ();
1830 if (ptid_equal (ptid, magic_null_ptid))
1831 /* The main thread is always alive. */
1834 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1835 /* The main thread is always alive. This can happen after a
1836 vAttach, if the remote side doesn't support
1841 endp = rs->buf + get_remote_packet_size ();
1844 write_ptid (p, endp, ptid);
1847 getpkt (&rs->buf, &rs->buf_size, 0);
1848 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1851 /* About these extended threadlist and threadinfo packets. They are
1852 variable length packets but, the fields within them are often fixed
1853 length. They are redundent enough to send over UDP as is the
1854 remote protocol in general. There is a matching unit test module
1857 #define OPAQUETHREADBYTES 8
1859 /* a 64 bit opaque identifier */
1860 typedef unsigned char threadref[OPAQUETHREADBYTES];
1862 /* WARNING: This threadref data structure comes from the remote O.S.,
1863 libstub protocol encoding, and remote.c. It is not particularly
1866 /* Right now, the internal structure is int. We want it to be bigger.
1867 Plan to fix this. */
1869 typedef int gdb_threadref; /* Internal GDB thread reference. */
1871 /* gdb_ext_thread_info is an internal GDB data structure which is
1872 equivalent to the reply of the remote threadinfo packet. */
1874 struct gdb_ext_thread_info
1876 threadref threadid; /* External form of thread reference. */
1877 int active; /* Has state interesting to GDB?
1879 char display[256]; /* Brief state display, name,
1880 blocked/suspended. */
1881 char shortname[32]; /* To be used to name threads. */
1882 char more_display[256]; /* Long info, statistics, queue depth,
1886 /* The volume of remote transfers can be limited by submitting
1887 a mask containing bits specifying the desired information.
1888 Use a union of these values as the 'selection' parameter to
1889 get_thread_info. FIXME: Make these TAG names more thread specific. */
1891 #define TAG_THREADID 1
1892 #define TAG_EXISTS 2
1893 #define TAG_DISPLAY 4
1894 #define TAG_THREADNAME 8
1895 #define TAG_MOREDISPLAY 16
1897 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1899 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1901 static char *unpack_nibble (char *buf, int *val);
1903 static char *pack_nibble (char *buf, int nibble);
1905 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1907 static char *unpack_byte (char *buf, int *value);
1909 static char *pack_int (char *buf, int value);
1911 static char *unpack_int (char *buf, int *value);
1913 static char *unpack_string (char *src, char *dest, int length);
1915 static char *pack_threadid (char *pkt, threadref *id);
1917 static char *unpack_threadid (char *inbuf, threadref *id);
1919 void int_to_threadref (threadref *id, int value);
1921 static int threadref_to_int (threadref *ref);
1923 static void copy_threadref (threadref *dest, threadref *src);
1925 static int threadmatch (threadref *dest, threadref *src);
1927 static char *pack_threadinfo_request (char *pkt, int mode,
1930 static int remote_unpack_thread_info_response (char *pkt,
1931 threadref *expectedref,
1932 struct gdb_ext_thread_info
1936 static int remote_get_threadinfo (threadref *threadid,
1937 int fieldset, /*TAG mask */
1938 struct gdb_ext_thread_info *info);
1940 static char *pack_threadlist_request (char *pkt, int startflag,
1942 threadref *nextthread);
1944 static int parse_threadlist_response (char *pkt,
1946 threadref *original_echo,
1947 threadref *resultlist,
1950 static int remote_get_threadlist (int startflag,
1951 threadref *nextthread,
1955 threadref *threadlist);
1957 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1959 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1960 void *context, int looplimit);
1962 static int remote_newthread_step (threadref *ref, void *context);
1965 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1966 buffer we're allowed to write to. Returns
1967 BUF+CHARACTERS_WRITTEN. */
1970 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1973 struct remote_state *rs = get_remote_state ();
1975 if (remote_multi_process_p (rs))
1977 pid = ptid_get_pid (ptid);
1979 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1981 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1983 tid = ptid_get_tid (ptid);
1985 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1987 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1992 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1993 passed the last parsed char. Returns null_ptid on error. */
1996 read_ptid (char *buf, char **obuf)
2000 ULONGEST pid = 0, tid = 0;
2004 /* Multi-process ptid. */
2005 pp = unpack_varlen_hex (p + 1, &pid);
2007 error (_("invalid remote ptid: %s"), p);
2010 pp = unpack_varlen_hex (p + 1, &tid);
2013 return ptid_build (pid, 0, tid);
2016 /* No multi-process. Just a tid. */
2017 pp = unpack_varlen_hex (p, &tid);
2019 /* Since the stub is not sending a process id, then default to
2020 what's in inferior_ptid, unless it's null at this point. If so,
2021 then since there's no way to know the pid of the reported
2022 threads, use the magic number. */
2023 if (ptid_equal (inferior_ptid, null_ptid))
2024 pid = ptid_get_pid (magic_null_ptid);
2026 pid = ptid_get_pid (inferior_ptid);
2030 return ptid_build (pid, 0, tid);
2033 /* Encode 64 bits in 16 chars of hex. */
2035 static const char hexchars[] = "0123456789abcdef";
2038 ishex (int ch, int *val)
2040 if ((ch >= 'a') && (ch <= 'f'))
2042 *val = ch - 'a' + 10;
2045 if ((ch >= 'A') && (ch <= 'F'))
2047 *val = ch - 'A' + 10;
2050 if ((ch >= '0') && (ch <= '9'))
2061 if (ch >= 'a' && ch <= 'f')
2062 return ch - 'a' + 10;
2063 if (ch >= '0' && ch <= '9')
2065 if (ch >= 'A' && ch <= 'F')
2066 return ch - 'A' + 10;
2071 stub_unpack_int (char *buff, int fieldlength)
2078 nibble = stubhex (*buff++);
2082 retval = retval << 4;
2088 unpack_varlen_hex (char *buff, /* packet to parse */
2092 ULONGEST retval = 0;
2094 while (ishex (*buff, &nibble))
2097 retval = retval << 4;
2098 retval |= nibble & 0x0f;
2105 unpack_nibble (char *buf, int *val)
2107 *val = fromhex (*buf++);
2112 pack_nibble (char *buf, int nibble)
2114 *buf++ = hexchars[(nibble & 0x0f)];
2119 pack_hex_byte (char *pkt, int byte)
2121 *pkt++ = hexchars[(byte >> 4) & 0xf];
2122 *pkt++ = hexchars[(byte & 0xf)];
2127 unpack_byte (char *buf, int *value)
2129 *value = stub_unpack_int (buf, 2);
2134 pack_int (char *buf, int value)
2136 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2137 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2138 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2139 buf = pack_hex_byte (buf, (value & 0xff));
2144 unpack_int (char *buf, int *value)
2146 *value = stub_unpack_int (buf, 8);
2150 #if 0 /* Currently unused, uncomment when needed. */
2151 static char *pack_string (char *pkt, char *string);
2154 pack_string (char *pkt, char *string)
2159 len = strlen (string);
2161 len = 200; /* Bigger than most GDB packets, junk??? */
2162 pkt = pack_hex_byte (pkt, len);
2166 if ((ch == '\0') || (ch == '#'))
2167 ch = '*'; /* Protect encapsulation. */
2172 #endif /* 0 (unused) */
2175 unpack_string (char *src, char *dest, int length)
2184 pack_threadid (char *pkt, threadref *id)
2187 unsigned char *altid;
2189 altid = (unsigned char *) id;
2190 limit = pkt + BUF_THREAD_ID_SIZE;
2192 pkt = pack_hex_byte (pkt, *altid++);
2198 unpack_threadid (char *inbuf, threadref *id)
2201 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2204 altref = (char *) id;
2206 while (inbuf < limit)
2208 x = stubhex (*inbuf++);
2209 y = stubhex (*inbuf++);
2210 *altref++ = (x << 4) | y;
2215 /* Externally, threadrefs are 64 bits but internally, they are still
2216 ints. This is due to a mismatch of specifications. We would like
2217 to use 64bit thread references internally. This is an adapter
2221 int_to_threadref (threadref *id, int value)
2223 unsigned char *scan;
2225 scan = (unsigned char *) id;
2231 *scan++ = (value >> 24) & 0xff;
2232 *scan++ = (value >> 16) & 0xff;
2233 *scan++ = (value >> 8) & 0xff;
2234 *scan++ = (value & 0xff);
2238 threadref_to_int (threadref *ref)
2241 unsigned char *scan;
2247 value = (value << 8) | ((*scan++) & 0xff);
2252 copy_threadref (threadref *dest, threadref *src)
2255 unsigned char *csrc, *cdest;
2257 csrc = (unsigned char *) src;
2258 cdest = (unsigned char *) dest;
2265 threadmatch (threadref *dest, threadref *src)
2267 /* Things are broken right now, so just assume we got a match. */
2269 unsigned char *srcp, *destp;
2271 srcp = (char *) src;
2272 destp = (char *) dest;
2276 result &= (*srcp++ == *destp++) ? 1 : 0;
2283 threadid:1, # always request threadid
2290 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2293 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2295 *pkt++ = 'q'; /* Info Query */
2296 *pkt++ = 'P'; /* process or thread info */
2297 pkt = pack_int (pkt, mode); /* mode */
2298 pkt = pack_threadid (pkt, id); /* threadid */
2299 *pkt = '\0'; /* terminate */
2303 /* These values tag the fields in a thread info response packet. */
2304 /* Tagging the fields allows us to request specific fields and to
2305 add more fields as time goes by. */
2307 #define TAG_THREADID 1 /* Echo the thread identifier. */
2308 #define TAG_EXISTS 2 /* Is this process defined enough to
2309 fetch registers and its stack? */
2310 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2311 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2312 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2316 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2317 struct gdb_ext_thread_info *info)
2319 struct remote_state *rs = get_remote_state ();
2323 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2326 /* info->threadid = 0; FIXME: implement zero_threadref. */
2328 info->display[0] = '\0';
2329 info->shortname[0] = '\0';
2330 info->more_display[0] = '\0';
2332 /* Assume the characters indicating the packet type have been
2334 pkt = unpack_int (pkt, &mask); /* arg mask */
2335 pkt = unpack_threadid (pkt, &ref);
2338 warning (_("Incomplete response to threadinfo request."));
2339 if (!threadmatch (&ref, expectedref))
2340 { /* This is an answer to a different request. */
2341 warning (_("ERROR RMT Thread info mismatch."));
2344 copy_threadref (&info->threadid, &ref);
2346 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2348 /* Packets are terminated with nulls. */
2349 while ((pkt < limit) && mask && *pkt)
2351 pkt = unpack_int (pkt, &tag); /* tag */
2352 pkt = unpack_byte (pkt, &length); /* length */
2353 if (!(tag & mask)) /* Tags out of synch with mask. */
2355 warning (_("ERROR RMT: threadinfo tag mismatch."));
2359 if (tag == TAG_THREADID)
2363 warning (_("ERROR RMT: length of threadid is not 16."));
2367 pkt = unpack_threadid (pkt, &ref);
2368 mask = mask & ~TAG_THREADID;
2371 if (tag == TAG_EXISTS)
2373 info->active = stub_unpack_int (pkt, length);
2375 mask = mask & ~(TAG_EXISTS);
2378 warning (_("ERROR RMT: 'exists' length too long."));
2384 if (tag == TAG_THREADNAME)
2386 pkt = unpack_string (pkt, &info->shortname[0], length);
2387 mask = mask & ~TAG_THREADNAME;
2390 if (tag == TAG_DISPLAY)
2392 pkt = unpack_string (pkt, &info->display[0], length);
2393 mask = mask & ~TAG_DISPLAY;
2396 if (tag == TAG_MOREDISPLAY)
2398 pkt = unpack_string (pkt, &info->more_display[0], length);
2399 mask = mask & ~TAG_MOREDISPLAY;
2402 warning (_("ERROR RMT: unknown thread info tag."));
2403 break; /* Not a tag we know about. */
2409 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2410 struct gdb_ext_thread_info *info)
2412 struct remote_state *rs = get_remote_state ();
2415 pack_threadinfo_request (rs->buf, fieldset, threadid);
2417 getpkt (&rs->buf, &rs->buf_size, 0);
2419 if (rs->buf[0] == '\0')
2422 result = remote_unpack_thread_info_response (rs->buf + 2,
2427 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2430 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2431 threadref *nextthread)
2433 *pkt++ = 'q'; /* info query packet */
2434 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2435 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2436 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2437 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2442 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2445 parse_threadlist_response (char *pkt, int result_limit,
2446 threadref *original_echo, threadref *resultlist,
2449 struct remote_state *rs = get_remote_state ();
2451 int count, resultcount, done;
2454 /* Assume the 'q' and 'M chars have been stripped. */
2455 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2456 /* done parse past here */
2457 pkt = unpack_byte (pkt, &count); /* count field */
2458 pkt = unpack_nibble (pkt, &done);
2459 /* The first threadid is the argument threadid. */
2460 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2461 while ((count-- > 0) && (pkt < limit))
2463 pkt = unpack_threadid (pkt, resultlist++);
2464 if (resultcount++ >= result_limit)
2473 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2474 int *done, int *result_count, threadref *threadlist)
2476 struct remote_state *rs = get_remote_state ();
2477 static threadref echo_nextthread;
2480 /* Trancate result limit to be smaller than the packet size. */
2481 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2482 >= get_remote_packet_size ())
2483 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2485 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2487 getpkt (&rs->buf, &rs->buf_size, 0);
2489 if (*rs->buf == '\0')
2493 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2496 if (!threadmatch (&echo_nextthread, nextthread))
2498 /* FIXME: This is a good reason to drop the packet. */
2499 /* Possably, there is a duplicate response. */
2501 retransmit immediatly - race conditions
2502 retransmit after timeout - yes
2504 wait for packet, then exit
2506 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2507 return 0; /* I choose simply exiting. */
2509 if (*result_count <= 0)
2513 warning (_("RMT ERROR : failed to get remote thread list."));
2516 return result; /* break; */
2518 if (*result_count > result_limit)
2521 warning (_("RMT ERROR: threadlist response longer than requested."));
2527 /* This is the interface between remote and threads, remotes upper
2530 /* remote_find_new_threads retrieves the thread list and for each
2531 thread in the list, looks up the thread in GDB's internal list,
2532 adding the thread if it does not already exist. This involves
2533 getting partial thread lists from the remote target so, polling the
2534 quit_flag is required. */
2537 /* About this many threadisds fit in a packet. */
2539 #define MAXTHREADLISTRESULTS 32
2542 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2545 int done, i, result_count;
2549 static threadref nextthread;
2550 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2555 if (loopcount++ > looplimit)
2558 warning (_("Remote fetch threadlist -infinite loop-."));
2561 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2562 &done, &result_count, resultthreadlist))
2567 /* Clear for later iterations. */
2569 /* Setup to resume next batch of thread references, set nextthread. */
2570 if (result_count >= 1)
2571 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2573 while (result_count--)
2574 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2581 remote_newthread_step (threadref *ref, void *context)
2583 int pid = ptid_get_pid (inferior_ptid);
2584 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2586 if (!in_thread_list (ptid))
2588 return 1; /* continue iterator */
2591 #define CRAZY_MAX_THREADS 1000
2594 remote_current_thread (ptid_t oldpid)
2596 struct remote_state *rs = get_remote_state ();
2599 getpkt (&rs->buf, &rs->buf_size, 0);
2600 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2601 return read_ptid (&rs->buf[2], NULL);
2606 /* Find new threads for info threads command.
2607 * Original version, using John Metzler's thread protocol.
2611 remote_find_new_threads (void)
2613 remote_threadlist_iterator (remote_newthread_step, 0,
2617 #if defined(HAVE_LIBEXPAT)
2619 typedef struct thread_item
2625 DEF_VEC_O(thread_item_t);
2627 struct threads_parsing_context
2629 VEC (thread_item_t) *items;
2633 start_thread (struct gdb_xml_parser *parser,
2634 const struct gdb_xml_element *element,
2635 void *user_data, VEC(gdb_xml_value_s) *attributes)
2637 struct threads_parsing_context *data = user_data;
2639 struct thread_item item;
2641 struct gdb_xml_value *attr;
2643 id = xml_find_attribute (attributes, "id")->value;
2644 item.ptid = read_ptid (id, NULL);
2646 attr = xml_find_attribute (attributes, "core");
2648 item.core = *(ULONGEST *) attr->value;
2654 VEC_safe_push (thread_item_t, data->items, &item);
2658 end_thread (struct gdb_xml_parser *parser,
2659 const struct gdb_xml_element *element,
2660 void *user_data, const char *body_text)
2662 struct threads_parsing_context *data = user_data;
2664 if (body_text && *body_text)
2665 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2668 const struct gdb_xml_attribute thread_attributes[] = {
2669 { "id", GDB_XML_AF_NONE, NULL, NULL },
2670 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2671 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2674 const struct gdb_xml_element thread_children[] = {
2675 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2678 const struct gdb_xml_element threads_children[] = {
2679 { "thread", thread_attributes, thread_children,
2680 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2681 start_thread, end_thread },
2682 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2685 const struct gdb_xml_element threads_elements[] = {
2686 { "threads", NULL, threads_children,
2687 GDB_XML_EF_NONE, NULL, NULL },
2688 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2691 /* Discard the contents of the constructed thread info context. */
2694 clear_threads_parsing_context (void *p)
2696 struct threads_parsing_context *context = p;
2698 struct thread_item *item;
2700 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2701 xfree (item->extra);
2703 VEC_free (thread_item_t, context->items);
2709 * Find all threads for info threads command.
2710 * Uses new thread protocol contributed by Cisco.
2711 * Falls back and attempts to use the older method (above)
2712 * if the target doesn't respond to the new method.
2716 remote_threads_info (struct target_ops *ops)
2718 struct remote_state *rs = get_remote_state ();
2722 if (remote_desc == 0) /* paranoia */
2723 error (_("Command can only be used when connected to the remote target."));
2725 #if defined(HAVE_LIBEXPAT)
2726 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2728 char *xml = target_read_stralloc (¤t_target,
2729 TARGET_OBJECT_THREADS, NULL);
2731 struct cleanup *back_to = make_cleanup (xfree, xml);
2735 struct threads_parsing_context context;
2737 context.items = NULL;
2738 make_cleanup (clear_threads_parsing_context, &context);
2740 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2741 threads_elements, xml, &context) == 0)
2744 struct thread_item *item;
2747 VEC_iterate (thread_item_t, context.items, i, item);
2750 if (!ptid_equal (item->ptid, null_ptid))
2752 struct private_thread_info *info;
2753 /* In non-stop mode, we assume new found threads
2754 are running until proven otherwise with a
2755 stop reply. In all-stop, we can only get
2756 here if all threads are stopped. */
2757 int running = non_stop ? 1 : 0;
2759 remote_notice_new_inferior (item->ptid, running);
2761 info = demand_private_info (item->ptid);
2762 info->core = item->core;
2763 info->extra = item->extra;
2770 do_cleanups (back_to);
2775 if (use_threadinfo_query)
2777 putpkt ("qfThreadInfo");
2778 getpkt (&rs->buf, &rs->buf_size, 0);
2780 if (bufp[0] != '\0') /* q packet recognized */
2782 struct cleanup *old_chain;
2785 /* remote_notice_new_inferior (in the loop below) may make
2786 new RSP calls, which clobber rs->buf. Work with a
2788 bufp = saved_reply = xstrdup (rs->buf);
2789 old_chain = make_cleanup (free_current_contents, &saved_reply);
2791 while (*bufp++ == 'm') /* reply contains one or more TID */
2795 new_thread = read_ptid (bufp, &bufp);
2796 if (!ptid_equal (new_thread, null_ptid))
2798 /* In non-stop mode, we assume new found threads
2799 are running until proven otherwise with a
2800 stop reply. In all-stop, we can only get
2801 here if all threads are stopped. */
2802 int running = non_stop ? 1 : 0;
2804 remote_notice_new_inferior (new_thread, running);
2807 while (*bufp++ == ','); /* comma-separated list */
2808 free_current_contents (&saved_reply);
2809 putpkt ("qsThreadInfo");
2810 getpkt (&rs->buf, &rs->buf_size, 0);
2811 bufp = saved_reply = xstrdup (rs->buf);
2813 do_cleanups (old_chain);
2818 /* Only qfThreadInfo is supported in non-stop mode. */
2822 /* Else fall back to old method based on jmetzler protocol. */
2823 use_threadinfo_query = 0;
2824 remote_find_new_threads ();
2829 * Collect a descriptive string about the given thread.
2830 * The target may say anything it wants to about the thread
2831 * (typically info about its blocked / runnable state, name, etc.).
2832 * This string will appear in the info threads display.
2834 * Optional: targets are not required to implement this function.
2838 remote_threads_extra_info (struct thread_info *tp)
2840 struct remote_state *rs = get_remote_state ();
2844 struct gdb_ext_thread_info threadinfo;
2845 static char display_buf[100]; /* arbitrary... */
2846 int n = 0; /* position in display_buf */
2848 if (remote_desc == 0) /* paranoia */
2849 internal_error (__FILE__, __LINE__,
2850 _("remote_threads_extra_info"));
2852 if (ptid_equal (tp->ptid, magic_null_ptid)
2853 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2854 /* This is the main thread which was added by GDB. The remote
2855 server doesn't know about it. */
2858 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2860 struct thread_info *info = find_thread_ptid (tp->ptid);
2862 if (info && info->private)
2863 return info->private->extra;
2868 if (use_threadextra_query)
2871 char *endb = rs->buf + get_remote_packet_size ();
2873 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2875 write_ptid (b, endb, tp->ptid);
2878 getpkt (&rs->buf, &rs->buf_size, 0);
2879 if (rs->buf[0] != 0)
2881 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2882 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2883 display_buf [result] = '\0';
2888 /* If the above query fails, fall back to the old method. */
2889 use_threadextra_query = 0;
2890 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2891 | TAG_MOREDISPLAY | TAG_DISPLAY;
2892 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2893 if (remote_get_threadinfo (&id, set, &threadinfo))
2894 if (threadinfo.active)
2896 if (*threadinfo.shortname)
2897 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2898 " Name: %s,", threadinfo.shortname);
2899 if (*threadinfo.display)
2900 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2901 " State: %s,", threadinfo.display);
2902 if (*threadinfo.more_display)
2903 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2904 " Priority: %s", threadinfo.more_display);
2908 /* For purely cosmetic reasons, clear up trailing commas. */
2909 if (',' == display_buf[n-1])
2910 display_buf[n-1] = ' ';
2919 remote_static_tracepoint_marker_at (CORE_ADDR addr,
2920 struct static_tracepoint_marker *marker)
2922 struct remote_state *rs = get_remote_state ();
2925 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2927 p += hexnumstr (p, addr);
2929 getpkt (&rs->buf, &rs->buf_size, 0);
2933 error (_("Remote failure reply: %s"), p);
2937 parse_static_tracepoint_marker_definition (p, &p, marker);
2944 static VEC(static_tracepoint_marker_p) *
2945 remote_static_tracepoint_markers_by_strid (const char *strid)
2947 struct remote_state *rs = get_remote_state ();
2948 VEC(static_tracepoint_marker_p) *markers = NULL;
2949 struct static_tracepoint_marker *marker = NULL;
2950 struct cleanup *old_chain;
2953 /* Ask for a first packet of static tracepoint marker
2956 getpkt (&rs->buf, &rs->buf_size, 0);
2959 error (_("Remote failure reply: %s"), p);
2961 old_chain = make_cleanup (free_current_marker, &marker);
2966 marker = XCNEW (struct static_tracepoint_marker);
2970 parse_static_tracepoint_marker_definition (p, &p, marker);
2972 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2974 VEC_safe_push (static_tracepoint_marker_p,
2980 release_static_tracepoint_marker (marker);
2981 memset (marker, 0, sizeof (*marker));
2984 while (*p++ == ','); /* comma-separated list */
2985 /* Ask for another packet of static tracepoint definition. */
2987 getpkt (&rs->buf, &rs->buf_size, 0);
2991 do_cleanups (old_chain);
2996 /* Implement the to_get_ada_task_ptid function for the remote targets. */
2999 remote_get_ada_task_ptid (long lwp, long thread)
3001 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
3005 /* Restart the remote side; this is an extended protocol operation. */
3008 extended_remote_restart (void)
3010 struct remote_state *rs = get_remote_state ();
3012 /* Send the restart command; for reasons I don't understand the
3013 remote side really expects a number after the "R". */
3014 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3017 remote_fileio_reset ();
3020 /* Clean up connection to a remote debugger. */
3025 if (remote_desc == NULL)
3026 return; /* already closed */
3028 /* Make sure we leave stdin registered in the event loop, and we
3029 don't leave the async SIGINT signal handler installed. */
3030 remote_terminal_ours ();
3032 serial_close (remote_desc);
3035 /* We don't have a connection to the remote stub anymore. Get rid
3036 of all the inferiors and their threads we were controlling.
3037 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3038 will be unable to find the thread corresponding to (pid, 0, 0). */
3039 inferior_ptid = null_ptid;
3040 discard_all_inferiors ();
3042 /* Stop replies may from inferiors which are still unknown to GDB.
3043 We are closing the remote target, so we should discard
3044 everything, including the stop replies from GDB-unknown
3046 discard_pending_stop_replies (NULL);
3048 if (remote_async_inferior_event_token)
3049 delete_async_event_handler (&remote_async_inferior_event_token);
3051 remote_notif_unregister_async_event_handler ();
3053 trace_reset_local_state ();
3056 /* Query the remote side for the text, data and bss offsets. */
3061 struct remote_state *rs = get_remote_state ();
3064 int lose, num_segments = 0, do_sections, do_segments;
3065 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3066 struct section_offsets *offs;
3067 struct symfile_segment_data *data;
3069 if (symfile_objfile == NULL)
3072 putpkt ("qOffsets");
3073 getpkt (&rs->buf, &rs->buf_size, 0);
3076 if (buf[0] == '\000')
3077 return; /* Return silently. Stub doesn't support
3081 warning (_("Remote failure reply: %s"), buf);
3085 /* Pick up each field in turn. This used to be done with scanf, but
3086 scanf will make trouble if CORE_ADDR size doesn't match
3087 conversion directives correctly. The following code will work
3088 with any size of CORE_ADDR. */
3089 text_addr = data_addr = bss_addr = 0;
3093 if (strncmp (ptr, "Text=", 5) == 0)
3096 /* Don't use strtol, could lose on big values. */
3097 while (*ptr && *ptr != ';')
3098 text_addr = (text_addr << 4) + fromhex (*ptr++);
3100 if (strncmp (ptr, ";Data=", 6) == 0)
3103 while (*ptr && *ptr != ';')
3104 data_addr = (data_addr << 4) + fromhex (*ptr++);
3109 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3112 while (*ptr && *ptr != ';')
3113 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3115 if (bss_addr != data_addr)
3116 warning (_("Target reported unsupported offsets: %s"), buf);
3121 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3124 /* Don't use strtol, could lose on big values. */
3125 while (*ptr && *ptr != ';')
3126 text_addr = (text_addr << 4) + fromhex (*ptr++);
3129 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3132 while (*ptr && *ptr != ';')
3133 data_addr = (data_addr << 4) + fromhex (*ptr++);
3141 error (_("Malformed response to offset query, %s"), buf);
3142 else if (*ptr != '\0')
3143 warning (_("Target reported unsupported offsets: %s"), buf);
3145 offs = ((struct section_offsets *)
3146 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3147 memcpy (offs, symfile_objfile->section_offsets,
3148 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3150 data = get_symfile_segment_data (symfile_objfile->obfd);
3151 do_segments = (data != NULL);
3152 do_sections = num_segments == 0;
3154 if (num_segments > 0)
3156 segments[0] = text_addr;
3157 segments[1] = data_addr;
3159 /* If we have two segments, we can still try to relocate everything
3160 by assuming that the .text and .data offsets apply to the whole
3161 text and data segments. Convert the offsets given in the packet
3162 to base addresses for symfile_map_offsets_to_segments. */
3163 else if (data && data->num_segments == 2)
3165 segments[0] = data->segment_bases[0] + text_addr;
3166 segments[1] = data->segment_bases[1] + data_addr;
3169 /* If the object file has only one segment, assume that it is text
3170 rather than data; main programs with no writable data are rare,
3171 but programs with no code are useless. Of course the code might
3172 have ended up in the data segment... to detect that we would need
3173 the permissions here. */
3174 else if (data && data->num_segments == 1)
3176 segments[0] = data->segment_bases[0] + text_addr;
3179 /* There's no way to relocate by segment. */
3185 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3186 offs, num_segments, segments);
3188 if (ret == 0 && !do_sections)
3189 error (_("Can not handle qOffsets TextSeg "
3190 "response with this symbol file"));
3197 free_symfile_segment_data (data);
3201 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3203 /* This is a temporary kludge to force data and bss to use the
3204 same offsets because that's what nlmconv does now. The real
3205 solution requires changes to the stub and remote.c that I
3206 don't have time to do right now. */
3208 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3209 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3212 objfile_relocate (symfile_objfile, offs);
3215 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3216 threads we know are stopped already. This is used during the
3217 initial remote connection in non-stop mode --- threads that are
3218 reported as already being stopped are left stopped. */
3221 set_stop_requested_callback (struct thread_info *thread, void *data)
3223 /* If we have a stop reply for this thread, it must be stopped. */
3224 if (peek_stop_reply (thread->ptid))
3225 set_stop_requested (thread->ptid, 1);
3230 /* Send interrupt_sequence to remote target. */
3232 send_interrupt_sequence (void)
3234 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3235 remote_serial_write ("\x03", 1);
3236 else if (interrupt_sequence_mode == interrupt_sequence_break)
3237 serial_send_break (remote_desc);
3238 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3240 serial_send_break (remote_desc);
3241 remote_serial_write ("g", 1);
3244 internal_error (__FILE__, __LINE__,
3245 _("Invalid value for interrupt_sequence_mode: %s."),
3246 interrupt_sequence_mode);
3250 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3251 and extract the PTID. Returns NULL_PTID if not found. */
3254 stop_reply_extract_thread (char *stop_reply)
3256 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3260 /* Txx r:val ; r:val (...) */
3263 /* Look for "register" named "thread". */
3268 p1 = strchr (p, ':');
3272 if (strncmp (p, "thread", p1 - p) == 0)
3273 return read_ptid (++p1, &p);
3275 p1 = strchr (p, ';');
3287 /* Query the remote target for which is the current thread/process,
3288 add it to our tables, and update INFERIOR_PTID. The caller is
3289 responsible for setting the state such that the remote end is ready
3290 to return the current thread.
3292 This function is called after handling the '?' or 'vRun' packets,
3293 whose response is a stop reply from which we can also try
3294 extracting the thread. If the target doesn't support the explicit
3295 qC query, we infer the current thread from that stop reply, passed
3296 in in WAIT_STATUS, which may be NULL. */
3299 add_current_inferior_and_thread (char *wait_status)
3301 struct remote_state *rs = get_remote_state ();
3303 ptid_t ptid = null_ptid;
3305 inferior_ptid = null_ptid;
3307 /* Now, if we have thread information, update inferior_ptid. First
3308 if we have a stop reply handy, maybe it's a T stop reply with a
3309 "thread" register we can extract the current thread from. If
3310 not, ask the remote which is the current thread, with qC. The
3311 former method avoids a roundtrip. Note we don't use
3312 remote_parse_stop_reply as that makes use of the target
3313 architecture, which we haven't yet fully determined at this
3315 if (wait_status != NULL)
3316 ptid = stop_reply_extract_thread (wait_status);
3317 if (ptid_equal (ptid, null_ptid))
3318 ptid = remote_current_thread (inferior_ptid);
3320 if (!ptid_equal (ptid, null_ptid))
3322 if (!remote_multi_process_p (rs))
3325 inferior_ptid = ptid;
3329 /* Without this, some commands which require an active target
3330 (such as kill) won't work. This variable serves (at least)
3331 double duty as both the pid of the target process (if it has
3332 such), and as a flag indicating that a target is active. */
3333 inferior_ptid = magic_null_ptid;
3337 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3339 /* Add the main thread. */
3340 add_thread_silent (inferior_ptid);
3344 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3346 struct remote_state *rs = get_remote_state ();
3347 struct packet_config *noack_config;
3348 char *wait_status = NULL;
3350 immediate_quit++; /* Allow user to interrupt it. */
3353 if (interrupt_on_connect)
3354 send_interrupt_sequence ();
3356 /* Ack any packet which the remote side has already sent. */
3357 serial_write (remote_desc, "+", 1);
3359 /* Signal other parts that we're going through the initial setup,
3360 and so things may not be stable yet. */
3361 rs->starting_up = 1;
3363 /* The first packet we send to the target is the optional "supported
3364 packets" request. If the target can answer this, it will tell us
3365 which later probes to skip. */
3366 remote_query_supported ();
3368 /* If the stub wants to get a QAllow, compose one and send it. */
3369 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3370 remote_set_permissions ();
3372 /* Next, we possibly activate noack mode.
3374 If the QStartNoAckMode packet configuration is set to AUTO,
3375 enable noack mode if the stub reported a wish for it with
3378 If set to TRUE, then enable noack mode even if the stub didn't
3379 report it in qSupported. If the stub doesn't reply OK, the
3380 session ends with an error.
3382 If FALSE, then don't activate noack mode, regardless of what the
3383 stub claimed should be the default with qSupported. */
3385 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3387 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3388 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3389 && noack_config->support == PACKET_ENABLE))
3391 putpkt ("QStartNoAckMode");
3392 getpkt (&rs->buf, &rs->buf_size, 0);
3393 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3399 /* Tell the remote that we are using the extended protocol. */
3401 getpkt (&rs->buf, &rs->buf_size, 0);
3404 /* Let the target know which signals it is allowed to pass down to
3406 update_signals_program_target ();
3408 /* Next, if the target can specify a description, read it. We do
3409 this before anything involving memory or registers. */
3410 target_find_description ();
3412 /* Next, now that we know something about the target, update the
3413 address spaces in the program spaces. */
3414 update_address_spaces ();
3416 /* On OSs where the list of libraries is global to all
3417 processes, we fetch them early. */
3418 if (gdbarch_has_global_solist (target_gdbarch ()))
3419 solib_add (NULL, from_tty, target, auto_solib_add);
3423 if (!rs->non_stop_aware)
3424 error (_("Non-stop mode requested, but remote "
3425 "does not support non-stop"));
3427 putpkt ("QNonStop:1");
3428 getpkt (&rs->buf, &rs->buf_size, 0);
3430 if (strcmp (rs->buf, "OK") != 0)
3431 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3433 /* Find about threads and processes the stub is already
3434 controlling. We default to adding them in the running state.
3435 The '?' query below will then tell us about which threads are
3437 remote_threads_info (target);
3439 else if (rs->non_stop_aware)
3441 /* Don't assume that the stub can operate in all-stop mode.
3442 Request it explicitly. */
3443 putpkt ("QNonStop:0");
3444 getpkt (&rs->buf, &rs->buf_size, 0);
3446 if (strcmp (rs->buf, "OK") != 0)
3447 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3450 /* Upload TSVs regardless of whether the target is running or not. The
3451 remote stub, such as GDBserver, may have some predefined or builtin
3452 TSVs, even if the target is not running. */
3453 if (remote_get_trace_status (current_trace_status ()) != -1)
3455 struct uploaded_tsv *uploaded_tsvs = NULL;
3457 remote_upload_trace_state_variables (&uploaded_tsvs);
3458 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3461 /* Check whether the target is running now. */
3463 getpkt (&rs->buf, &rs->buf_size, 0);
3469 struct inferior *inf;
3471 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3474 error (_("The target is not running (try extended-remote?)"));
3476 /* We're connected, but not running. Drop out before we
3477 call start_remote. */
3478 rs->starting_up = 0;
3483 /* Save the reply for later. */
3484 wait_status = alloca (strlen (rs->buf) + 1);
3485 strcpy (wait_status, rs->buf);
3488 /* Let the stub know that we want it to return the thread. */
3489 set_continue_thread (minus_one_ptid);
3491 add_current_inferior_and_thread (wait_status);
3493 /* init_wait_for_inferior should be called before get_offsets in order
3494 to manage `inserted' flag in bp loc in a correct state.
3495 breakpoint_init_inferior, called from init_wait_for_inferior, set
3496 `inserted' flag to 0, while before breakpoint_re_set, called from
3497 start_remote, set `inserted' flag to 1. In the initialization of
3498 inferior, breakpoint_init_inferior should be called first, and then
3499 breakpoint_re_set can be called. If this order is broken, state of
3500 `inserted' flag is wrong, and cause some problems on breakpoint
3502 init_wait_for_inferior ();
3504 get_offsets (); /* Get text, data & bss offsets. */
3506 /* If we could not find a description using qXfer, and we know
3507 how to do it some other way, try again. This is not
3508 supported for non-stop; it could be, but it is tricky if
3509 there are no stopped threads when we connect. */
3510 if (remote_read_description_p (target)
3511 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3513 target_clear_description ();
3514 target_find_description ();
3517 /* Use the previously fetched status. */
3518 gdb_assert (wait_status != NULL);
3519 strcpy (rs->buf, wait_status);
3520 rs->cached_wait_status = 1;
3523 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3527 /* Clear WFI global state. Do this before finding about new
3528 threads and inferiors, and setting the current inferior.
3529 Otherwise we would clear the proceed status of the current
3530 inferior when we want its stop_soon state to be preserved
3531 (see notice_new_inferior). */
3532 init_wait_for_inferior ();
3534 /* In non-stop, we will either get an "OK", meaning that there
3535 are no stopped threads at this time; or, a regular stop
3536 reply. In the latter case, there may be more than one thread
3537 stopped --- we pull them all out using the vStopped
3539 if (strcmp (rs->buf, "OK") != 0)
3541 struct notif_client *notif = ¬if_client_stop;
3543 /* remote_notif_get_pending_replies acks this one, and gets
3545 notif_client_stop.pending_event
3546 = remote_notif_parse (notif, rs->buf);
3547 remote_notif_get_pending_events (notif);
3549 /* Make sure that threads that were stopped remain
3551 iterate_over_threads (set_stop_requested_callback, NULL);
3554 if (target_can_async_p ())
3555 target_async (inferior_event_handler, 0);
3557 if (thread_count () == 0)
3560 error (_("The target is not running (try extended-remote?)"));
3562 /* We're connected, but not running. Drop out before we
3563 call start_remote. */
3564 rs->starting_up = 0;
3568 /* Let the stub know that we want it to return the thread. */
3570 /* Force the stub to choose a thread. */
3571 set_general_thread (null_ptid);
3574 inferior_ptid = remote_current_thread (minus_one_ptid);
3575 if (ptid_equal (inferior_ptid, minus_one_ptid))
3576 error (_("remote didn't report the current thread in non-stop mode"));
3578 get_offsets (); /* Get text, data & bss offsets. */
3580 /* In non-stop mode, any cached wait status will be stored in
3581 the stop reply queue. */
3582 gdb_assert (wait_status == NULL);
3584 /* Report all signals during attach/startup. */
3585 remote_pass_signals (0, NULL);
3588 /* If we connected to a live target, do some additional setup. */
3589 if (target_has_execution)
3591 if (exec_bfd) /* No use without an exec file. */
3592 remote_check_symbols ();
3595 /* Possibly the target has been engaged in a trace run started
3596 previously; find out where things are at. */
3597 if (remote_get_trace_status (current_trace_status ()) != -1)
3599 struct uploaded_tp *uploaded_tps = NULL;
3601 if (current_trace_status ()->running)
3602 printf_filtered (_("Trace is already running on the target.\n"));
3604 remote_upload_tracepoints (&uploaded_tps);
3606 merge_uploaded_tracepoints (&uploaded_tps);
3609 /* The thread and inferior lists are now synchronized with the
3610 target, our symbols have been relocated, and we're merged the
3611 target's tracepoints with ours. We're done with basic start
3613 rs->starting_up = 0;
3615 /* If breakpoints are global, insert them now. */
3616 if (gdbarch_has_global_breakpoints (target_gdbarch ())
3617 && breakpoints_always_inserted_mode ())
3618 insert_breakpoints ();
3621 /* Open a connection to a remote debugger.
3622 NAME is the filename used for communication. */
3625 remote_open (char *name, int from_tty)
3627 remote_open_1 (name, from_tty, &remote_ops, 0);
3630 /* Open a connection to a remote debugger using the extended
3631 remote gdb protocol. NAME is the filename used for communication. */
3634 extended_remote_open (char *name, int from_tty)
3636 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3639 /* Generic code for opening a connection to a remote target. */
3642 init_all_packet_configs (void)
3646 for (i = 0; i < PACKET_MAX; i++)
3647 update_packet_config (&remote_protocol_packets[i]);
3650 /* Symbol look-up. */
3653 remote_check_symbols (void)
3655 struct remote_state *rs = get_remote_state ();
3656 char *msg, *reply, *tmp;
3657 struct minimal_symbol *sym;
3660 /* The remote side has no concept of inferiors that aren't running
3661 yet, it only knows about running processes. If we're connected
3662 but our current inferior is not running, we should not invite the
3663 remote target to request symbol lookups related to its
3664 (unrelated) current process. */
3665 if (!target_has_execution)
3668 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3671 /* Make sure the remote is pointing at the right process. Note
3672 there's no way to select "no process". */
3673 set_general_process ();
3675 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3676 because we need both at the same time. */
3677 msg = alloca (get_remote_packet_size ());
3679 /* Invite target to request symbol lookups. */
3681 putpkt ("qSymbol::");
3682 getpkt (&rs->buf, &rs->buf_size, 0);
3683 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3686 while (strncmp (reply, "qSymbol:", 8) == 0)
3689 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3691 sym = lookup_minimal_symbol (msg, NULL, NULL);
3693 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3696 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3697 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3699 /* If this is a function address, return the start of code
3700 instead of any data function descriptor. */
3701 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3705 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3706 phex_nz (sym_addr, addr_size), &reply[8]);
3710 getpkt (&rs->buf, &rs->buf_size, 0);
3715 static struct serial *
3716 remote_serial_open (char *name)
3718 static int udp_warning = 0;
3720 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3721 of in ser-tcp.c, because it is the remote protocol assuming that the
3722 serial connection is reliable and not the serial connection promising
3724 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3726 warning (_("The remote protocol may be unreliable over UDP.\n"
3727 "Some events may be lost, rendering further debugging "
3732 return serial_open (name);
3735 /* Inform the target of our permission settings. The permission flags
3736 work without this, but if the target knows the settings, it can do
3737 a couple things. First, it can add its own check, to catch cases
3738 that somehow manage to get by the permissions checks in target
3739 methods. Second, if the target is wired to disallow particular
3740 settings (for instance, a system in the field that is not set up to
3741 be able to stop at a breakpoint), it can object to any unavailable
3745 remote_set_permissions (void)
3747 struct remote_state *rs = get_remote_state ();
3749 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3750 "WriteReg:%x;WriteMem:%x;"
3751 "InsertBreak:%x;InsertTrace:%x;"
3752 "InsertFastTrace:%x;Stop:%x",
3753 may_write_registers, may_write_memory,
3754 may_insert_breakpoints, may_insert_tracepoints,
3755 may_insert_fast_tracepoints, may_stop);
3757 getpkt (&rs->buf, &rs->buf_size, 0);
3759 /* If the target didn't like the packet, warn the user. Do not try
3760 to undo the user's settings, that would just be maddening. */
3761 if (strcmp (rs->buf, "OK") != 0)
3762 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3765 /* This type describes each known response to the qSupported
3767 struct protocol_feature
3769 /* The name of this protocol feature. */
3772 /* The default for this protocol feature. */
3773 enum packet_support default_support;
3775 /* The function to call when this feature is reported, or after
3776 qSupported processing if the feature is not supported.
3777 The first argument points to this structure. The second
3778 argument indicates whether the packet requested support be
3779 enabled, disabled, or probed (or the default, if this function
3780 is being called at the end of processing and this feature was
3781 not reported). The third argument may be NULL; if not NULL, it
3782 is a NUL-terminated string taken from the packet following
3783 this feature's name and an equals sign. */
3784 void (*func) (const struct protocol_feature *, enum packet_support,
3787 /* The corresponding packet for this feature. Only used if
3788 FUNC is remote_supported_packet. */
3793 remote_supported_packet (const struct protocol_feature *feature,
3794 enum packet_support support,
3795 const char *argument)
3799 warning (_("Remote qSupported response supplied an unexpected value for"
3800 " \"%s\"."), feature->name);
3804 if (remote_protocol_packets[feature->packet].support
3805 == PACKET_SUPPORT_UNKNOWN)
3806 remote_protocol_packets[feature->packet].support = support;
3810 remote_packet_size (const struct protocol_feature *feature,
3811 enum packet_support support, const char *value)
3813 struct remote_state *rs = get_remote_state ();
3818 if (support != PACKET_ENABLE)
3821 if (value == NULL || *value == '\0')
3823 warning (_("Remote target reported \"%s\" without a size."),
3829 packet_size = strtol (value, &value_end, 16);
3830 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3832 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3833 feature->name, value);
3837 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3839 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3840 packet_size, MAX_REMOTE_PACKET_SIZE);
3841 packet_size = MAX_REMOTE_PACKET_SIZE;
3844 /* Record the new maximum packet size. */
3845 rs->explicit_packet_size = packet_size;
3849 remote_multi_process_feature (const struct protocol_feature *feature,
3850 enum packet_support support, const char *value)
3852 struct remote_state *rs = get_remote_state ();
3854 rs->multi_process_aware = (support == PACKET_ENABLE);
3858 remote_non_stop_feature (const struct protocol_feature *feature,
3859 enum packet_support support, const char *value)
3861 struct remote_state *rs = get_remote_state ();
3863 rs->non_stop_aware = (support == PACKET_ENABLE);
3867 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3868 enum packet_support support,
3871 struct remote_state *rs = get_remote_state ();
3873 rs->cond_tracepoints = (support == PACKET_ENABLE);
3877 remote_cond_breakpoint_feature (const struct protocol_feature *feature,
3878 enum packet_support support,
3881 struct remote_state *rs = get_remote_state ();
3883 rs->cond_breakpoints = (support == PACKET_ENABLE);
3887 remote_breakpoint_commands_feature (const struct protocol_feature *feature,
3888 enum packet_support support,
3891 struct remote_state *rs = get_remote_state ();
3893 rs->breakpoint_commands = (support == PACKET_ENABLE);
3897 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3898 enum packet_support support,
3901 struct remote_state *rs = get_remote_state ();
3903 rs->fast_tracepoints = (support == PACKET_ENABLE);
3907 remote_static_tracepoint_feature (const struct protocol_feature *feature,
3908 enum packet_support support,
3911 struct remote_state *rs = get_remote_state ();
3913 rs->static_tracepoints = (support == PACKET_ENABLE);
3917 remote_install_in_trace_feature (const struct protocol_feature *feature,
3918 enum packet_support support,
3921 struct remote_state *rs = get_remote_state ();
3923 rs->install_in_trace = (support == PACKET_ENABLE);
3927 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3928 enum packet_support support,
3931 struct remote_state *rs = get_remote_state ();
3933 rs->disconnected_tracing = (support == PACKET_ENABLE);
3937 remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3938 enum packet_support support,
3941 struct remote_state *rs = get_remote_state ();
3943 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3947 remote_string_tracing_feature (const struct protocol_feature *feature,
3948 enum packet_support support,
3951 struct remote_state *rs = get_remote_state ();
3953 rs->string_tracing = (support == PACKET_ENABLE);
3957 remote_augmented_libraries_svr4_read_feature
3958 (const struct protocol_feature *feature,
3959 enum packet_support support, const char *value)
3961 struct remote_state *rs = get_remote_state ();
3963 rs->augmented_libraries_svr4_read = (support == PACKET_ENABLE);
3966 static const struct protocol_feature remote_protocol_features[] = {
3967 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3968 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3969 PACKET_qXfer_auxv },
3970 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3971 PACKET_qXfer_features },
3972 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3973 PACKET_qXfer_libraries },
3974 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3975 PACKET_qXfer_libraries_svr4 },
3976 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3977 remote_augmented_libraries_svr4_read_feature, -1 },
3978 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3979 PACKET_qXfer_memory_map },
3980 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3981 PACKET_qXfer_spu_read },
3982 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3983 PACKET_qXfer_spu_write },
3984 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3985 PACKET_qXfer_osdata },
3986 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3987 PACKET_qXfer_threads },
3988 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3989 PACKET_qXfer_traceframe_info },
3990 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3991 PACKET_QPassSignals },
3992 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3993 PACKET_QProgramSignals },
3994 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3995 PACKET_QStartNoAckMode },
3996 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
3997 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
3998 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3999 PACKET_qXfer_siginfo_read },
4000 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4001 PACKET_qXfer_siginfo_write },
4002 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
4003 PACKET_ConditionalTracepoints },
4004 { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
4005 PACKET_ConditionalBreakpoints },
4006 { "BreakpointCommands", PACKET_DISABLE, remote_breakpoint_commands_feature,
4007 PACKET_BreakpointCommands },
4008 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
4009 PACKET_FastTracepoints },
4010 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
4011 PACKET_StaticTracepoints },
4012 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
4013 PACKET_InstallInTrace},
4014 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
4016 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4018 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4020 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4021 PACKET_TracepointSource },
4022 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4024 { "EnableDisableTracepoints", PACKET_DISABLE,
4025 remote_enable_disable_tracepoint_feature, -1 },
4026 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4027 PACKET_qXfer_fdpic },
4028 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4030 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4031 PACKET_QDisableRandomization },
4032 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4033 { "QTBuffer:size", PACKET_DISABLE,
4034 remote_supported_packet, PACKET_QTBuffer_size},
4035 { "tracenz", PACKET_DISABLE,
4036 remote_string_tracing_feature, -1 },
4037 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4038 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4039 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4040 PACKET_qXfer_btrace }
4043 static char *remote_support_xml;
4045 /* Register string appended to "xmlRegisters=" in qSupported query. */
4048 register_remote_support_xml (const char *xml)
4050 #if defined(HAVE_LIBEXPAT)
4051 if (remote_support_xml == NULL)
4052 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4055 char *copy = xstrdup (remote_support_xml + 13);
4056 char *p = strtok (copy, ",");
4060 if (strcmp (p, xml) == 0)
4067 while ((p = strtok (NULL, ",")) != NULL);
4070 remote_support_xml = reconcat (remote_support_xml,
4071 remote_support_xml, ",", xml,
4078 remote_query_supported_append (char *msg, const char *append)
4081 return reconcat (msg, msg, ";", append, (char *) NULL);
4083 return xstrdup (append);
4087 remote_query_supported (void)
4089 struct remote_state *rs = get_remote_state ();
4092 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4094 /* The packet support flags are handled differently for this packet
4095 than for most others. We treat an error, a disabled packet, and
4096 an empty response identically: any features which must be reported
4097 to be used will be automatically disabled. An empty buffer
4098 accomplishes this, since that is also the representation for a list
4099 containing no features. */
4102 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
4105 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4107 q = remote_query_supported_append (q, "multiprocess+");
4109 if (remote_support_xml)
4110 q = remote_query_supported_append (q, remote_support_xml);
4112 q = remote_query_supported_append (q, "qRelocInsn+");
4114 q = reconcat (q, "qSupported:", q, (char *) NULL);
4117 do_cleanups (old_chain);
4119 getpkt (&rs->buf, &rs->buf_size, 0);
4121 /* If an error occured, warn, but do not return - just reset the
4122 buffer to empty and go on to disable features. */
4123 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4126 warning (_("Remote failure reply: %s"), rs->buf);
4131 memset (seen, 0, sizeof (seen));
4136 enum packet_support is_supported;
4137 char *p, *end, *name_end, *value;
4139 /* First separate out this item from the rest of the packet. If
4140 there's another item after this, we overwrite the separator
4141 (terminated strings are much easier to work with). */
4143 end = strchr (p, ';');
4146 end = p + strlen (p);
4156 warning (_("empty item in \"qSupported\" response"));
4161 name_end = strchr (p, '=');
4164 /* This is a name=value entry. */
4165 is_supported = PACKET_ENABLE;
4166 value = name_end + 1;
4175 is_supported = PACKET_ENABLE;
4179 is_supported = PACKET_DISABLE;
4183 is_supported = PACKET_SUPPORT_UNKNOWN;
4187 warning (_("unrecognized item \"%s\" "
4188 "in \"qSupported\" response"), p);
4194 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4195 if (strcmp (remote_protocol_features[i].name, p) == 0)
4197 const struct protocol_feature *feature;
4200 feature = &remote_protocol_features[i];
4201 feature->func (feature, is_supported, value);
4206 /* If we increased the packet size, make sure to increase the global
4207 buffer size also. We delay this until after parsing the entire
4208 qSupported packet, because this is the same buffer we were
4210 if (rs->buf_size < rs->explicit_packet_size)
4212 rs->buf_size = rs->explicit_packet_size;
4213 rs->buf = xrealloc (rs->buf, rs->buf_size);
4216 /* Handle the defaults for unmentioned features. */
4217 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4220 const struct protocol_feature *feature;
4222 feature = &remote_protocol_features[i];
4223 feature->func (feature, feature->default_support, NULL);
4227 /* Remove any of the remote.c targets from target stack. Upper targets depend
4228 on it so remove them first. */
4231 remote_unpush_target (void)
4233 pop_all_targets_above (process_stratum - 1);
4237 remote_open_1 (char *name, int from_tty,
4238 struct target_ops *target, int extended_p)
4240 struct remote_state *rs = get_remote_state ();
4243 error (_("To open a remote debug connection, you need to specify what\n"
4244 "serial device is attached to the remote system\n"
4245 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4247 /* See FIXME above. */
4248 if (!target_async_permitted)
4249 wait_forever_enabled_p = 1;
4251 /* If we're connected to a running target, target_preopen will kill it.
4252 Ask this question first, before target_preopen has a chance to kill
4254 if (remote_desc != NULL && !have_inferiors ())
4257 && !query (_("Already connected to a remote target. Disconnect? ")))
4258 error (_("Still connected."));
4261 /* Here the possibly existing remote target gets unpushed. */
4262 target_preopen (from_tty);
4264 /* Make sure we send the passed signals list the next time we resume. */
4265 xfree (last_pass_packet);
4266 last_pass_packet = NULL;
4268 /* Make sure we send the program signals list the next time we
4270 xfree (last_program_signals_packet);
4271 last_program_signals_packet = NULL;
4273 remote_fileio_reset ();
4274 reopen_exec_file ();
4277 remote_desc = remote_serial_open (name);
4279 perror_with_name (name);
4281 if (baud_rate != -1)
4283 if (serial_setbaudrate (remote_desc, baud_rate))
4285 /* The requested speed could not be set. Error out to
4286 top level after closing remote_desc. Take care to
4287 set remote_desc to NULL to avoid closing remote_desc
4289 serial_close (remote_desc);
4291 perror_with_name (name);
4295 serial_raw (remote_desc);
4297 /* If there is something sitting in the buffer we might take it as a
4298 response to a command, which would be bad. */
4299 serial_flush_input (remote_desc);
4303 puts_filtered ("Remote debugging using ");
4304 puts_filtered (name);
4305 puts_filtered ("\n");
4307 push_target (target); /* Switch to using remote target now. */
4309 /* Register extra event sources in the event loop. */
4310 remote_async_inferior_event_token
4311 = create_async_event_handler (remote_async_inferior_event_handler,
4313 remote_notif_register_async_event_handler ();
4315 /* Reset the target state; these things will be queried either by
4316 remote_query_supported or as they are needed. */
4317 init_all_packet_configs ();
4318 rs->cached_wait_status = 0;
4319 rs->explicit_packet_size = 0;
4321 rs->multi_process_aware = 0;
4322 rs->extended = extended_p;
4323 rs->non_stop_aware = 0;
4324 rs->waiting_for_stop_reply = 0;
4325 rs->ctrlc_pending_p = 0;
4327 general_thread = not_sent_ptid;
4328 continue_thread = not_sent_ptid;
4329 remote_traceframe_number = -1;
4331 /* Probe for ability to use "ThreadInfo" query, as required. */
4332 use_threadinfo_query = 1;
4333 use_threadextra_query = 1;
4335 if (target_async_permitted)
4337 /* With this target we start out by owning the terminal. */
4338 remote_async_terminal_ours_p = 1;
4340 /* FIXME: cagney/1999-09-23: During the initial connection it is
4341 assumed that the target is already ready and able to respond to
4342 requests. Unfortunately remote_start_remote() eventually calls
4343 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4344 around this. Eventually a mechanism that allows
4345 wait_for_inferior() to expect/get timeouts will be
4347 wait_forever_enabled_p = 0;
4350 /* First delete any symbols previously loaded from shared libraries. */
4351 no_shared_libraries (NULL, 0);
4354 init_thread_list ();
4356 /* Start the remote connection. If error() or QUIT, discard this
4357 target (we'd otherwise be in an inconsistent state) and then
4358 propogate the error on up the exception chain. This ensures that
4359 the caller doesn't stumble along blindly assuming that the
4360 function succeeded. The CLI doesn't have this problem but other
4361 UI's, such as MI do.
4363 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4364 this function should return an error indication letting the
4365 caller restore the previous state. Unfortunately the command
4366 ``target remote'' is directly wired to this function making that
4367 impossible. On a positive note, the CLI side of this problem has
4368 been fixed - the function set_cmd_context() makes it possible for
4369 all the ``target ....'' commands to share a common callback
4370 function. See cli-dump.c. */
4372 volatile struct gdb_exception ex;
4374 TRY_CATCH (ex, RETURN_MASK_ALL)
4376 remote_start_remote (from_tty, target, extended_p);
4380 /* Pop the partially set up target - unless something else did
4381 already before throwing the exception. */
4382 if (remote_desc != NULL)
4383 remote_unpush_target ();
4384 if (target_async_permitted)
4385 wait_forever_enabled_p = 1;
4386 throw_exception (ex);
4390 if (target_async_permitted)
4391 wait_forever_enabled_p = 1;
4394 /* This takes a program previously attached to and detaches it. After
4395 this is done, GDB can be used to debug some other program. We
4396 better not have left any breakpoints in the target program or it'll
4397 die when it hits one. */
4400 remote_detach_1 (char *args, int from_tty, int extended)
4402 int pid = ptid_get_pid (inferior_ptid);
4403 struct remote_state *rs = get_remote_state ();
4406 error (_("Argument given to \"detach\" when remotely debugging."));
4408 if (!target_has_execution)
4409 error (_("No process to detach from."));
4413 char *exec_file = get_exec_file (0);
4414 if (exec_file == NULL)
4416 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4417 target_pid_to_str (pid_to_ptid (pid)));
4418 gdb_flush (gdb_stdout);
4421 /* Tell the remote target to detach. */
4422 if (remote_multi_process_p (rs))
4423 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4425 strcpy (rs->buf, "D");
4428 getpkt (&rs->buf, &rs->buf_size, 0);
4430 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4432 else if (rs->buf[0] == '\0')
4433 error (_("Remote doesn't know how to detach"));
4435 error (_("Can't detach process."));
4437 if (from_tty && !extended)
4438 puts_filtered (_("Ending remote debugging.\n"));
4440 target_mourn_inferior ();
4444 remote_detach (struct target_ops *ops, char *args, int from_tty)
4446 remote_detach_1 (args, from_tty, 0);
4450 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
4452 remote_detach_1 (args, from_tty, 1);
4455 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4458 remote_disconnect (struct target_ops *target, char *args, int from_tty)
4461 error (_("Argument given to \"disconnect\" when remotely debugging."));
4463 /* Make sure we unpush even the extended remote targets; mourn
4464 won't do it. So call remote_mourn_1 directly instead of
4465 target_mourn_inferior. */
4466 remote_mourn_1 (target);
4469 puts_filtered ("Ending remote debugging.\n");
4472 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4473 be chatty about it. */
4476 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4478 struct remote_state *rs = get_remote_state ();
4480 char *wait_status = NULL;
4482 pid = parse_pid_to_attach (args);
4484 /* Remote PID can be freely equal to getpid, do not check it here the same
4485 way as in other targets. */
4487 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4488 error (_("This target does not support attaching to a process"));
4492 char *exec_file = get_exec_file (0);
4495 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4496 target_pid_to_str (pid_to_ptid (pid)));
4498 printf_unfiltered (_("Attaching to %s\n"),
4499 target_pid_to_str (pid_to_ptid (pid)));
4501 gdb_flush (gdb_stdout);
4504 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4506 getpkt (&rs->buf, &rs->buf_size, 0);
4508 if (packet_ok (rs->buf,
4509 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
4513 /* Save the reply for later. */
4514 wait_status = alloca (strlen (rs->buf) + 1);
4515 strcpy (wait_status, rs->buf);
4517 else if (strcmp (rs->buf, "OK") != 0)
4518 error (_("Attaching to %s failed with: %s"),
4519 target_pid_to_str (pid_to_ptid (pid)),
4522 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4523 error (_("This target does not support attaching to a process"));
4525 error (_("Attaching to %s failed"),
4526 target_pid_to_str (pid_to_ptid (pid)));
4528 set_current_inferior (remote_add_inferior (0, pid, 1));
4530 inferior_ptid = pid_to_ptid (pid);
4534 struct thread_info *thread;
4536 /* Get list of threads. */
4537 remote_threads_info (target);
4539 thread = first_thread_of_process (pid);
4541 inferior_ptid = thread->ptid;
4543 inferior_ptid = pid_to_ptid (pid);
4545 /* Invalidate our notion of the remote current thread. */
4546 record_currthread (minus_one_ptid);
4550 /* Now, if we have thread information, update inferior_ptid. */
4551 inferior_ptid = remote_current_thread (inferior_ptid);
4553 /* Add the main thread to the thread list. */
4554 add_thread_silent (inferior_ptid);
4557 /* Next, if the target can specify a description, read it. We do
4558 this before anything involving memory or registers. */
4559 target_find_description ();
4563 /* Use the previously fetched status. */
4564 gdb_assert (wait_status != NULL);
4566 if (target_can_async_p ())
4568 struct notif_event *reply
4569 = remote_notif_parse (¬if_client_stop, wait_status);
4571 push_stop_reply ((struct stop_reply *) reply);
4573 target_async (inferior_event_handler, 0);
4577 gdb_assert (wait_status != NULL);
4578 strcpy (rs->buf, wait_status);
4579 rs->cached_wait_status = 1;
4583 gdb_assert (wait_status == NULL);
4587 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4589 extended_remote_attach_1 (ops, args, from_tty);
4592 /* Convert hex digit A to a number. */
4597 if (a >= '0' && a <= '9')
4599 else if (a >= 'a' && a <= 'f')
4600 return a - 'a' + 10;
4601 else if (a >= 'A' && a <= 'F')
4602 return a - 'A' + 10;
4604 error (_("Reply contains invalid hex digit %d"), a);
4608 hex2bin (const char *hex, gdb_byte *bin, int count)
4612 for (i = 0; i < count; i++)
4614 if (hex[0] == 0 || hex[1] == 0)
4616 /* Hex string is short, or of uneven length.
4617 Return the count that has been converted so far. */
4620 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4626 /* Convert number NIB to a hex digit. */
4634 return 'a' + nib - 10;
4638 bin2hex (const gdb_byte *bin, char *hex, int count)
4642 /* May use a length, or a nul-terminated string as input. */
4644 count = strlen ((char *) bin);
4646 for (i = 0; i < count; i++)
4648 *hex++ = tohex ((*bin >> 4) & 0xf);
4649 *hex++ = tohex (*bin++ & 0xf);
4655 /* Check for the availability of vCont. This function should also check
4659 remote_vcont_probe (struct remote_state *rs)
4663 strcpy (rs->buf, "vCont?");
4665 getpkt (&rs->buf, &rs->buf_size, 0);
4668 /* Make sure that the features we assume are supported. */
4669 if (strncmp (buf, "vCont", 5) == 0)
4672 int support_s, support_S, support_c, support_C;
4678 rs->supports_vCont.t = 0;
4679 rs->supports_vCont.r = 0;
4680 while (p && *p == ';')
4683 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4685 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4687 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4689 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4691 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4692 rs->supports_vCont.t = 1;
4693 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4694 rs->supports_vCont.r = 1;
4696 p = strchr (p, ';');
4699 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4700 BUF will make packet_ok disable the packet. */
4701 if (!support_s || !support_S || !support_c || !support_C)
4705 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4708 /* Helper function for building "vCont" resumptions. Write a
4709 resumption to P. ENDP points to one-passed-the-end of the buffer
4710 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4711 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4712 resumed thread should be single-stepped and/or signalled. If PTID
4713 equals minus_one_ptid, then all threads are resumed; if PTID
4714 represents a process, then all threads of the process are resumed;
4715 the thread to be stepped and/or signalled is given in the global
4719 append_resumption (char *p, char *endp,
4720 ptid_t ptid, int step, enum gdb_signal siggnal)
4722 struct remote_state *rs = get_remote_state ();
4724 if (step && siggnal != GDB_SIGNAL_0)
4725 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4727 /* GDB is willing to range step. */
4728 && use_range_stepping
4729 /* Target supports range stepping. */
4730 && rs->supports_vCont.r
4731 /* We don't currently support range stepping multiple
4732 threads with a wildcard (though the protocol allows it,
4733 so stubs shouldn't make an active effort to forbid
4735 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4737 struct thread_info *tp;
4739 if (ptid_equal (ptid, minus_one_ptid))
4741 /* If we don't know about the target thread's tid, then
4742 we're resuming magic_null_ptid (see caller). */
4743 tp = find_thread_ptid (magic_null_ptid);
4746 tp = find_thread_ptid (ptid);
4747 gdb_assert (tp != NULL);
4749 if (tp->control.may_range_step)
4751 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4753 p += xsnprintf (p, endp - p, ";r%s,%s",
4754 phex_nz (tp->control.step_range_start,
4756 phex_nz (tp->control.step_range_end,
4760 p += xsnprintf (p, endp - p, ";s");
4763 p += xsnprintf (p, endp - p, ";s");
4764 else if (siggnal != GDB_SIGNAL_0)
4765 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4767 p += xsnprintf (p, endp - p, ";c");
4769 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4773 /* All (-1) threads of process. */
4774 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4776 p += xsnprintf (p, endp - p, ":");
4777 p = write_ptid (p, endp, nptid);
4779 else if (!ptid_equal (ptid, minus_one_ptid))
4781 p += xsnprintf (p, endp - p, ":");
4782 p = write_ptid (p, endp, ptid);
4788 /* Append a vCont continue-with-signal action for threads that have a
4789 non-zero stop signal. */
4792 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4794 struct thread_info *thread;
4796 ALL_THREADS (thread)
4797 if (ptid_match (thread->ptid, ptid)
4798 && !ptid_equal (inferior_ptid, thread->ptid)
4799 && thread->suspend.stop_signal != GDB_SIGNAL_0
4800 && signal_pass_state (thread->suspend.stop_signal))
4802 p = append_resumption (p, endp, thread->ptid,
4803 0, thread->suspend.stop_signal);
4804 thread->suspend.stop_signal = GDB_SIGNAL_0;
4810 /* Resume the remote inferior by using a "vCont" packet. The thread
4811 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4812 resumed thread should be single-stepped and/or signalled. If PTID
4813 equals minus_one_ptid, then all threads are resumed; the thread to
4814 be stepped and/or signalled is given in the global INFERIOR_PTID.
4815 This function returns non-zero iff it resumes the inferior.
4817 This function issues a strict subset of all possible vCont commands at the
4821 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4823 struct remote_state *rs = get_remote_state ();
4827 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4828 remote_vcont_probe (rs);
4830 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4834 endp = rs->buf + get_remote_packet_size ();
4836 /* If we could generate a wider range of packets, we'd have to worry
4837 about overflowing BUF. Should there be a generic
4838 "multi-part-packet" packet? */
4840 p += xsnprintf (p, endp - p, "vCont");
4842 if (ptid_equal (ptid, magic_null_ptid))
4844 /* MAGIC_NULL_PTID means that we don't have any active threads,
4845 so we don't have any TID numbers the inferior will
4846 understand. Make sure to only send forms that do not specify
4848 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4850 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4852 /* Resume all threads (of all processes, or of a single
4853 process), with preference for INFERIOR_PTID. This assumes
4854 inferior_ptid belongs to the set of all threads we are about
4856 if (step || siggnal != GDB_SIGNAL_0)
4858 /* Step inferior_ptid, with or without signal. */
4859 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4862 /* Also pass down any pending signaled resumption for other
4863 threads not the current. */
4864 p = append_pending_thread_resumptions (p, endp, ptid);
4866 /* And continue others without a signal. */
4867 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4871 /* Scheduler locking; resume only PTID. */
4872 append_resumption (p, endp, ptid, step, siggnal);
4875 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4880 /* In non-stop, the stub replies to vCont with "OK". The stop
4881 reply will be reported asynchronously by means of a `%Stop'
4883 getpkt (&rs->buf, &rs->buf_size, 0);
4884 if (strcmp (rs->buf, "OK") != 0)
4885 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4891 /* Tell the remote machine to resume. */
4893 static enum gdb_signal last_sent_signal = GDB_SIGNAL_0;
4895 static int last_sent_step;
4898 remote_resume (struct target_ops *ops,
4899 ptid_t ptid, int step, enum gdb_signal siggnal)
4901 struct remote_state *rs = get_remote_state ();
4904 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4905 (explained in remote-notif.c:handle_notification) so
4906 remote_notif_process is not called. We need find a place where
4907 it is safe to start a 'vNotif' sequence. It is good to do it
4908 before resuming inferior, because inferior was stopped and no RSP
4909 traffic at that moment. */
4911 remote_notif_process (¬if_client_stop);
4913 last_sent_signal = siggnal;
4914 last_sent_step = step;
4916 /* The vCont packet doesn't need to specify threads via Hc. */
4917 /* No reverse support (yet) for vCont. */
4918 if (execution_direction != EXEC_REVERSE)
4919 if (remote_vcont_resume (ptid, step, siggnal))
4922 /* All other supported resume packets do use Hc, so set the continue
4924 if (ptid_equal (ptid, minus_one_ptid))
4925 set_continue_thread (any_thread_ptid);
4927 set_continue_thread (ptid);
4930 if (execution_direction == EXEC_REVERSE)
4932 /* We don't pass signals to the target in reverse exec mode. */
4933 if (info_verbose && siggnal != GDB_SIGNAL_0)
4934 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4938 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4939 error (_("Remote reverse-step not supported."));
4941 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4942 error (_("Remote reverse-continue not supported."));
4944 strcpy (buf, step ? "bs" : "bc");
4946 else if (siggnal != GDB_SIGNAL_0)
4948 buf[0] = step ? 'S' : 'C';
4949 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4950 buf[2] = tohex (((int) siggnal) & 0xf);
4954 strcpy (buf, step ? "s" : "c");
4959 /* We are about to start executing the inferior, let's register it
4960 with the event loop. NOTE: this is the one place where all the
4961 execution commands end up. We could alternatively do this in each
4962 of the execution commands in infcmd.c. */
4963 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4964 into infcmd.c in order to allow inferior function calls to work
4965 NOT asynchronously. */
4966 if (target_can_async_p ())
4967 target_async (inferior_event_handler, 0);
4969 /* We've just told the target to resume. The remote server will
4970 wait for the inferior to stop, and then send a stop reply. In
4971 the mean time, we can't start another command/query ourselves
4972 because the stub wouldn't be ready to process it. This applies
4973 only to the base all-stop protocol, however. In non-stop (which
4974 only supports vCont), the stub replies with an "OK", and is
4975 immediate able to process further serial input. */
4977 rs->waiting_for_stop_reply = 1;
4981 /* Set up the signal handler for SIGINT, while the target is
4982 executing, ovewriting the 'regular' SIGINT signal handler. */
4984 async_initialize_sigint_signal_handler (void)
4986 signal (SIGINT, async_handle_remote_sigint);
4989 /* Signal handler for SIGINT, while the target is executing. */
4991 async_handle_remote_sigint (int sig)
4993 signal (sig, async_handle_remote_sigint_twice);
4994 mark_async_signal_handler (async_sigint_remote_token);
4997 /* Signal handler for SIGINT, installed after SIGINT has already been
4998 sent once. It will take effect the second time that the user sends
5001 async_handle_remote_sigint_twice (int sig)
5003 signal (sig, async_handle_remote_sigint);
5004 mark_async_signal_handler (async_sigint_remote_twice_token);
5007 /* Perform the real interruption of the target execution, in response
5010 async_remote_interrupt (gdb_client_data arg)
5013 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5015 target_stop (inferior_ptid);
5018 /* Perform interrupt, if the first attempt did not succeed. Just give
5019 up on the target alltogether. */
5021 async_remote_interrupt_twice (gdb_client_data arg)
5024 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5029 /* Reinstall the usual SIGINT handlers, after the target has
5032 async_cleanup_sigint_signal_handler (void *dummy)
5034 signal (SIGINT, handle_sigint);
5037 /* Send ^C to target to halt it. Target will respond, and send us a
5039 static void (*ofunc) (int);
5041 /* The command line interface's stop routine. This function is installed
5042 as a signal handler for SIGINT. The first time a user requests a
5043 stop, we call remote_stop to send a break or ^C. If there is no
5044 response from the target (it didn't stop when the user requested it),
5045 we ask the user if he'd like to detach from the target. */
5047 sync_remote_interrupt (int signo)
5049 /* If this doesn't work, try more severe steps. */
5050 signal (signo, sync_remote_interrupt_twice);
5052 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5055 /* The user typed ^C twice. */
5058 sync_remote_interrupt_twice (int signo)
5060 signal (signo, ofunc);
5061 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5062 signal (signo, sync_remote_interrupt);
5065 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5066 thread, all threads of a remote process, or all threads of all
5070 remote_stop_ns (ptid_t ptid)
5072 struct remote_state *rs = get_remote_state ();
5074 char *endp = rs->buf + get_remote_packet_size ();
5076 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
5077 remote_vcont_probe (rs);
5079 if (!rs->supports_vCont.t)
5080 error (_("Remote server does not support stopping threads"));
5082 if (ptid_equal (ptid, minus_one_ptid)
5083 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5084 p += xsnprintf (p, endp - p, "vCont;t");
5089 p += xsnprintf (p, endp - p, "vCont;t:");
5091 if (ptid_is_pid (ptid))
5092 /* All (-1) threads of process. */
5093 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
5096 /* Small optimization: if we already have a stop reply for
5097 this thread, no use in telling the stub we want this
5099 if (peek_stop_reply (ptid))
5105 write_ptid (p, endp, nptid);
5108 /* In non-stop, we get an immediate OK reply. The stop reply will
5109 come in asynchronously by notification. */
5111 getpkt (&rs->buf, &rs->buf_size, 0);
5112 if (strcmp (rs->buf, "OK") != 0)
5113 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5116 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5117 remote target. It is undefined which thread of which process
5118 reports the stop. */
5121 remote_stop_as (ptid_t ptid)
5123 struct remote_state *rs = get_remote_state ();
5125 rs->ctrlc_pending_p = 1;
5127 /* If the inferior is stopped already, but the core didn't know
5128 about it yet, just ignore the request. The cached wait status
5129 will be collected in remote_wait. */
5130 if (rs->cached_wait_status)
5133 /* Send interrupt_sequence to remote target. */
5134 send_interrupt_sequence ();
5137 /* This is the generic stop called via the target vector. When a target
5138 interrupt is requested, either by the command line or the GUI, we
5139 will eventually end up here. */
5142 remote_stop (ptid_t ptid)
5145 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5148 remote_stop_ns (ptid);
5150 remote_stop_as (ptid);
5153 /* Ask the user what to do when an interrupt is received. */
5156 interrupt_query (void)
5158 target_terminal_ours ();
5160 if (target_can_async_p ())
5162 signal (SIGINT, handle_sigint);
5167 if (query (_("Interrupted while waiting for the program.\n\
5168 Give up (and stop debugging it)? ")))
5170 remote_unpush_target ();
5175 target_terminal_inferior ();
5178 /* Enable/disable target terminal ownership. Most targets can use
5179 terminal groups to control terminal ownership. Remote targets are
5180 different in that explicit transfer of ownership to/from GDB/target
5184 remote_terminal_inferior (void)
5186 if (!target_async_permitted)
5187 /* Nothing to do. */
5190 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5191 idempotent. The event-loop GDB talking to an asynchronous target
5192 with a synchronous command calls this function from both
5193 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5194 transfer the terminal to the target when it shouldn't this guard
5196 if (!remote_async_terminal_ours_p)
5198 delete_file_handler (input_fd);
5199 remote_async_terminal_ours_p = 0;
5200 async_initialize_sigint_signal_handler ();
5201 /* NOTE: At this point we could also register our selves as the
5202 recipient of all input. Any characters typed could then be
5203 passed on down to the target. */
5207 remote_terminal_ours (void)
5209 if (!target_async_permitted)
5210 /* Nothing to do. */
5213 /* See FIXME in remote_terminal_inferior. */
5214 if (remote_async_terminal_ours_p)
5216 async_cleanup_sigint_signal_handler (NULL);
5217 add_file_handler (input_fd, stdin_event_handler, 0);
5218 remote_async_terminal_ours_p = 1;
5222 remote_console_output (char *msg)
5226 for (p = msg; p[0] && p[1]; p += 2)
5229 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5233 fputs_unfiltered (tb, gdb_stdtarg);
5235 gdb_flush (gdb_stdtarg);
5238 typedef struct cached_reg
5241 gdb_byte data[MAX_REGISTER_SIZE];
5244 DEF_VEC_O(cached_reg_t);
5246 typedef struct stop_reply
5248 struct notif_event base;
5250 /* The identifier of the thread about this event */
5253 struct target_waitstatus ws;
5255 /* Expedited registers. This makes remote debugging a bit more
5256 efficient for those targets that provide critical registers as
5257 part of their normal status mechanism (as another roundtrip to
5258 fetch them is avoided). */
5259 VEC(cached_reg_t) *regcache;
5261 int stopped_by_watchpoint_p;
5262 CORE_ADDR watch_data_address;
5270 DECLARE_QUEUE_P (stop_reply_p);
5271 DEFINE_QUEUE_P (stop_reply_p);
5272 /* The list of already fetched and acknowledged stop events. This
5273 queue is used for notification Stop, and other notifications
5274 don't need queue for their events, because the notification events
5275 of Stop can't be consumed immediately, so that events should be
5276 queued first, and be consumed by remote_wait_{ns,as} one per
5277 time. Other notifications can consume their events immediately,
5278 so queue is not needed for them. */
5279 static QUEUE (stop_reply_p) *stop_reply_queue;
5282 stop_reply_xfree (struct stop_reply *r)
5286 VEC_free (cached_reg_t, r->regcache);
5292 remote_notif_stop_parse (struct notif_client *self, char *buf,
5293 struct notif_event *event)
5295 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5299 remote_notif_stop_ack (struct notif_client *self, char *buf,
5300 struct notif_event *event)
5302 struct stop_reply *stop_reply = (struct stop_reply *) event;
5305 putpkt ((char *) self->ack_command);
5307 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5308 /* We got an unknown stop reply. */
5309 error (_("Unknown stop reply"));
5311 push_stop_reply (stop_reply);
5315 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5317 /* We can't get pending events in remote_notif_process for
5318 notification stop, and we have to do this in remote_wait_ns
5319 instead. If we fetch all queued events from stub, remote stub
5320 may exit and we have no chance to process them back in
5322 mark_async_event_handler (remote_async_inferior_event_token);
5327 stop_reply_dtr (struct notif_event *event)
5329 struct stop_reply *r = (struct stop_reply *) event;
5331 VEC_free (cached_reg_t, r->regcache);
5334 static struct notif_event *
5335 remote_notif_stop_alloc_reply (void)
5337 struct notif_event *r
5338 = (struct notif_event *) XMALLOC (struct stop_reply);
5340 r->dtr = stop_reply_dtr;
5345 /* A client of notification Stop. */
5347 struct notif_client notif_client_stop =
5351 remote_notif_stop_parse,
5352 remote_notif_stop_ack,
5353 remote_notif_stop_can_get_pending_events,
5354 remote_notif_stop_alloc_reply,
5358 /* A parameter to pass data in and out. */
5360 struct queue_iter_param
5363 struct stop_reply *output;
5366 /* Remove all queue elements meet the condition it checks. */
5369 remote_notif_remove_all (QUEUE (stop_reply_p) *q,
5370 QUEUE_ITER (stop_reply_p) *iter,
5374 struct queue_iter_param *param = data;
5375 struct inferior *inf = param->input;
5377 if (inf == NULL || ptid_get_pid (event->ptid) == inf->pid)
5379 stop_reply_xfree (event);
5380 QUEUE_remove_elem (stop_reply_p, q, iter);
5386 /* Discard all pending stop replies of inferior INF. If INF is NULL,
5387 discard everything. */
5390 discard_pending_stop_replies (struct inferior *inf)
5393 struct queue_iter_param param;
5394 struct stop_reply *reply
5395 = (struct stop_reply *) notif_client_stop.pending_event;
5397 /* Discard the in-flight notification. */
5400 || ptid_get_pid (reply->ptid) == inf->pid))
5402 stop_reply_xfree (reply);
5403 notif_client_stop.pending_event = NULL;
5407 param.output = NULL;
5408 /* Discard the stop replies we have already pulled with
5410 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5411 remote_notif_remove_all, ¶m);
5414 /* A parameter to pass data in and out. */
5417 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5418 QUEUE_ITER (stop_reply_p) *iter,
5422 struct queue_iter_param *param = data;
5423 ptid_t *ptid = param->input;
5425 if (ptid_match (event->ptid, *ptid))
5427 param->output = event;
5428 QUEUE_remove_elem (stop_reply_p, q, iter);
5435 /* Remove the first reply in 'stop_reply_queue' which matches
5438 static struct stop_reply *
5439 remote_notif_remove_queued_reply (ptid_t ptid)
5441 struct queue_iter_param param;
5443 param.input = &ptid;
5444 param.output = NULL;
5446 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5447 remote_notif_remove_once_on_match, ¶m);
5449 fprintf_unfiltered (gdb_stdlog,
5450 "notif: discard queued event: 'Stop' in %s\n",
5451 target_pid_to_str (ptid));
5453 return param.output;
5456 /* Look for a queued stop reply belonging to PTID. If one is found,
5457 remove it from the queue, and return it. Returns NULL if none is
5458 found. If there are still queued events left to process, tell the
5459 event loop to get back to target_wait soon. */
5461 static struct stop_reply *
5462 queued_stop_reply (ptid_t ptid)
5464 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5466 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5467 /* There's still at least an event left. */
5468 mark_async_event_handler (remote_async_inferior_event_token);
5473 /* Push a fully parsed stop reply in the stop reply queue. Since we
5474 know that we now have at least one queued event left to pass to the
5475 core side, tell the event loop to get back to target_wait soon. */
5478 push_stop_reply (struct stop_reply *new_event)
5480 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5483 fprintf_unfiltered (gdb_stdlog,
5484 "notif: push 'Stop' %s to queue %d\n",
5485 target_pid_to_str (new_event->ptid),
5486 QUEUE_length (stop_reply_p,
5489 mark_async_event_handler (remote_async_inferior_event_token);
5493 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5494 QUEUE_ITER (stop_reply_p) *iter,
5495 struct stop_reply *event,
5498 ptid_t *ptid = data;
5500 return !(ptid_equal (*ptid, event->ptid)
5501 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5504 /* Returns true if we have a stop reply for PTID. */
5507 peek_stop_reply (ptid_t ptid)
5509 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5510 stop_reply_match_ptid_and_ws, &ptid);
5513 /* Parse the stop reply in BUF. Either the function succeeds, and the
5514 result is stored in EVENT, or throws an error. */
5517 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5519 struct remote_arch_state *rsa = get_remote_arch_state ();
5523 event->ptid = null_ptid;
5524 event->ws.kind = TARGET_WAITKIND_IGNORE;
5525 event->ws.value.integer = 0;
5526 event->solibs_changed = 0;
5527 event->replay_event = 0;
5528 event->stopped_by_watchpoint_p = 0;
5529 event->regcache = NULL;
5534 case 'T': /* Status with PC, SP, FP, ... */
5535 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5536 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5538 n... = register number
5539 r... = register contents
5542 p = &buf[3]; /* after Txx */
5550 /* If the packet contains a register number, save it in
5551 pnum and set p1 to point to the character following it.
5552 Otherwise p1 points to p. */
5554 /* If this packet is an awatch packet, don't parse the 'a'
5555 as a register number. */
5557 if (strncmp (p, "awatch", strlen("awatch")) != 0
5558 && strncmp (p, "core", strlen ("core") != 0))
5560 /* Read the ``P'' register number. */
5561 pnum = strtol (p, &p_temp, 16);
5567 if (p1 == p) /* No register number present here. */
5569 p1 = strchr (p, ':');
5571 error (_("Malformed packet(a) (missing colon): %s\n\
5574 if (strncmp (p, "thread", p1 - p) == 0)
5575 event->ptid = read_ptid (++p1, &p);
5576 else if ((strncmp (p, "watch", p1 - p) == 0)
5577 || (strncmp (p, "rwatch", p1 - p) == 0)
5578 || (strncmp (p, "awatch", p1 - p) == 0))
5580 event->stopped_by_watchpoint_p = 1;
5581 p = unpack_varlen_hex (++p1, &addr);
5582 event->watch_data_address = (CORE_ADDR) addr;
5584 else if (strncmp (p, "library", p1 - p) == 0)
5588 while (*p_temp && *p_temp != ';')
5591 event->solibs_changed = 1;
5594 else if (strncmp (p, "replaylog", p1 - p) == 0)
5596 /* NO_HISTORY event.
5597 p1 will indicate "begin" or "end", but
5598 it makes no difference for now, so ignore it. */
5599 event->replay_event = 1;
5600 p_temp = strchr (p1 + 1, ';');
5604 else if (strncmp (p, "core", p1 - p) == 0)
5608 p = unpack_varlen_hex (++p1, &c);
5613 /* Silently skip unknown optional info. */
5614 p_temp = strchr (p1 + 1, ';');
5621 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5622 cached_reg_t cached_reg;
5627 error (_("Malformed packet(b) (missing colon): %s\n\
5633 error (_("Remote sent bad register number %s: %s\n\
5635 hex_string (pnum), p, buf);
5637 cached_reg.num = reg->regnum;
5639 fieldsize = hex2bin (p, cached_reg.data,
5640 register_size (target_gdbarch (),
5643 if (fieldsize < register_size (target_gdbarch (),
5645 warning (_("Remote reply is too short: %s"), buf);
5647 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5651 error (_("Remote register badly formatted: %s\nhere: %s"),
5656 case 'S': /* Old style status, just signal only. */
5657 if (event->solibs_changed)
5658 event->ws.kind = TARGET_WAITKIND_LOADED;
5659 else if (event->replay_event)
5660 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5663 event->ws.kind = TARGET_WAITKIND_STOPPED;
5664 event->ws.value.sig = (enum gdb_signal)
5665 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5668 case 'W': /* Target exited. */
5675 /* GDB used to accept only 2 hex chars here. Stubs should
5676 only send more if they detect GDB supports multi-process
5678 p = unpack_varlen_hex (&buf[1], &value);
5682 /* The remote process exited. */
5683 event->ws.kind = TARGET_WAITKIND_EXITED;
5684 event->ws.value.integer = value;
5688 /* The remote process exited with a signal. */
5689 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5690 event->ws.value.sig = (enum gdb_signal) value;
5693 /* If no process is specified, assume inferior_ptid. */
5694 pid = ptid_get_pid (inferior_ptid);
5703 else if (strncmp (p,
5704 "process:", sizeof ("process:") - 1) == 0)
5708 p += sizeof ("process:") - 1;
5709 unpack_varlen_hex (p, &upid);
5713 error (_("unknown stop reply packet: %s"), buf);
5716 error (_("unknown stop reply packet: %s"), buf);
5717 event->ptid = pid_to_ptid (pid);
5722 if (non_stop && ptid_equal (event->ptid, null_ptid))
5723 error (_("No process or thread specified in stop reply: %s"), buf);
5726 /* When the stub wants to tell GDB about a new notification reply, it
5727 sends a notification (%Stop, for example). Those can come it at
5728 any time, hence, we have to make sure that any pending
5729 putpkt/getpkt sequence we're making is finished, before querying
5730 the stub for more events with the corresponding ack command
5731 (vStopped, for example). E.g., if we started a vStopped sequence
5732 immediately upon receiving the notification, something like this
5740 1.6) <-- (registers reply to step #1.3)
5742 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5745 To solve this, whenever we parse a %Stop notification successfully,
5746 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5747 doing whatever we were doing:
5753 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5754 2.5) <-- (registers reply to step #2.3)
5756 Eventualy after step #2.5, we return to the event loop, which
5757 notices there's an event on the
5758 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5759 associated callback --- the function below. At this point, we're
5760 always safe to start a vStopped sequence. :
5763 2.7) <-- T05 thread:2
5769 remote_notif_get_pending_events (struct notif_client *nc)
5771 struct remote_state *rs = get_remote_state ();
5773 if (nc->pending_event)
5776 fprintf_unfiltered (gdb_stdlog,
5777 "notif: process: '%s' ack pending event\n",
5781 nc->ack (nc, rs->buf, nc->pending_event);
5782 nc->pending_event = NULL;
5786 getpkt (&rs->buf, &rs->buf_size, 0);
5787 if (strcmp (rs->buf, "OK") == 0)
5790 remote_notif_ack (nc, rs->buf);
5796 fprintf_unfiltered (gdb_stdlog,
5797 "notif: process: '%s' no pending reply\n",
5802 /* Called when it is decided that STOP_REPLY holds the info of the
5803 event that is to be returned to the core. This function always
5804 destroys STOP_REPLY. */
5807 process_stop_reply (struct stop_reply *stop_reply,
5808 struct target_waitstatus *status)
5812 *status = stop_reply->ws;
5813 ptid = stop_reply->ptid;
5815 /* If no thread/process was reported by the stub, assume the current
5817 if (ptid_equal (ptid, null_ptid))
5818 ptid = inferior_ptid;
5820 if (status->kind != TARGET_WAITKIND_EXITED
5821 && status->kind != TARGET_WAITKIND_SIGNALLED)
5823 /* Expedited registers. */
5824 if (stop_reply->regcache)
5826 struct regcache *regcache
5827 = get_thread_arch_regcache (ptid, target_gdbarch ());
5832 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5834 regcache_raw_supply (regcache, reg->num, reg->data);
5835 VEC_free (cached_reg_t, stop_reply->regcache);
5838 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5839 remote_watch_data_address = stop_reply->watch_data_address;
5841 remote_notice_new_inferior (ptid, 0);
5842 demand_private_info (ptid)->core = stop_reply->core;
5845 stop_reply_xfree (stop_reply);
5849 /* The non-stop mode version of target_wait. */
5852 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5854 struct remote_state *rs = get_remote_state ();
5855 struct stop_reply *stop_reply;
5859 /* If in non-stop mode, get out of getpkt even if a
5860 notification is received. */
5862 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5863 0 /* forever */, &is_notif);
5866 if (ret != -1 && !is_notif)
5869 case 'E': /* Error of some sort. */
5870 /* We're out of sync with the target now. Did it continue
5871 or not? We can't tell which thread it was in non-stop,
5872 so just ignore this. */
5873 warning (_("Remote failure reply: %s"), rs->buf);
5875 case 'O': /* Console output. */
5876 remote_console_output (rs->buf + 1);
5879 warning (_("Invalid remote reply: %s"), rs->buf);
5883 /* Acknowledge a pending stop reply that may have arrived in the
5885 if (notif_client_stop.pending_event != NULL)
5886 remote_notif_get_pending_events (¬if_client_stop);
5888 /* If indeed we noticed a stop reply, we're done. */
5889 stop_reply = queued_stop_reply (ptid);
5890 if (stop_reply != NULL)
5891 return process_stop_reply (stop_reply, status);
5893 /* Still no event. If we're just polling for an event, then
5894 return to the event loop. */
5895 if (options & TARGET_WNOHANG)
5897 status->kind = TARGET_WAITKIND_IGNORE;
5898 return minus_one_ptid;
5901 /* Otherwise do a blocking wait. */
5902 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5903 1 /* forever */, &is_notif);
5907 /* Wait until the remote machine stops, then return, storing status in
5908 STATUS just as `wait' would. */
5911 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5913 struct remote_state *rs = get_remote_state ();
5914 ptid_t event_ptid = null_ptid;
5916 struct stop_reply *stop_reply;
5920 status->kind = TARGET_WAITKIND_IGNORE;
5921 status->value.integer = 0;
5923 stop_reply = queued_stop_reply (ptid);
5924 if (stop_reply != NULL)
5925 return process_stop_reply (stop_reply, status);
5927 if (rs->cached_wait_status)
5928 /* Use the cached wait status, but only once. */
5929 rs->cached_wait_status = 0;
5935 if (!target_is_async_p ())
5937 ofunc = signal (SIGINT, sync_remote_interrupt);
5938 /* If the user hit C-c before this packet, or between packets,
5939 pretend that it was hit right here. */
5940 if (check_quit_flag ())
5943 sync_remote_interrupt (SIGINT);
5947 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5948 _never_ wait for ever -> test on target_is_async_p().
5949 However, before we do that we need to ensure that the caller
5950 knows how to take the target into/out of async mode. */
5951 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5952 wait_forever_enabled_p, &is_notif);
5954 if (!target_is_async_p ())
5955 signal (SIGINT, ofunc);
5957 /* GDB gets a notification. Return to core as this event is
5959 if (ret != -1 && is_notif)
5960 return minus_one_ptid;
5965 remote_stopped_by_watchpoint_p = 0;
5967 /* We got something. */
5968 rs->waiting_for_stop_reply = 0;
5970 /* Assume that the target has acknowledged Ctrl-C unless we receive
5971 an 'F' or 'O' packet. */
5972 if (buf[0] != 'F' && buf[0] != 'O')
5973 rs->ctrlc_pending_p = 0;
5977 case 'E': /* Error of some sort. */
5978 /* We're out of sync with the target now. Did it continue or
5979 not? Not is more likely, so report a stop. */
5980 warning (_("Remote failure reply: %s"), buf);
5981 status->kind = TARGET_WAITKIND_STOPPED;
5982 status->value.sig = GDB_SIGNAL_0;
5984 case 'F': /* File-I/O request. */
5985 remote_fileio_request (buf, rs->ctrlc_pending_p);
5986 rs->ctrlc_pending_p = 0;
5988 case 'T': case 'S': case 'X': case 'W':
5990 struct stop_reply *stop_reply
5991 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
5994 event_ptid = process_stop_reply (stop_reply, status);
5997 case 'O': /* Console output. */
5998 remote_console_output (buf + 1);
6000 /* The target didn't really stop; keep waiting. */
6001 rs->waiting_for_stop_reply = 1;
6005 if (last_sent_signal != GDB_SIGNAL_0)
6007 /* Zero length reply means that we tried 'S' or 'C' and the
6008 remote system doesn't support it. */
6009 target_terminal_ours_for_output ();
6011 ("Can't send signals to this remote system. %s not sent.\n",
6012 gdb_signal_to_name (last_sent_signal));
6013 last_sent_signal = GDB_SIGNAL_0;
6014 target_terminal_inferior ();
6016 strcpy ((char *) buf, last_sent_step ? "s" : "c");
6017 putpkt ((char *) buf);
6019 /* We just told the target to resume, so a stop reply is in
6021 rs->waiting_for_stop_reply = 1;
6024 /* else fallthrough */
6026 warning (_("Invalid remote reply: %s"), buf);
6028 rs->waiting_for_stop_reply = 1;
6032 if (status->kind == TARGET_WAITKIND_IGNORE)
6034 /* Nothing interesting happened. If we're doing a non-blocking
6035 poll, we're done. Otherwise, go back to waiting. */
6036 if (options & TARGET_WNOHANG)
6037 return minus_one_ptid;
6041 else if (status->kind != TARGET_WAITKIND_EXITED
6042 && status->kind != TARGET_WAITKIND_SIGNALLED)
6044 if (!ptid_equal (event_ptid, null_ptid))
6045 record_currthread (event_ptid);
6047 event_ptid = inferior_ptid;
6050 /* A process exit. Invalidate our notion of current thread. */
6051 record_currthread (minus_one_ptid);
6056 /* Wait until the remote machine stops, then return, storing status in
6057 STATUS just as `wait' would. */
6060 remote_wait (struct target_ops *ops,
6061 ptid_t ptid, struct target_waitstatus *status, int options)
6066 event_ptid = remote_wait_ns (ptid, status, options);
6068 event_ptid = remote_wait_as (ptid, status, options);
6070 if (target_can_async_p ())
6072 /* If there are are events left in the queue tell the event loop
6074 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6075 mark_async_event_handler (remote_async_inferior_event_token);
6081 /* Fetch a single register using a 'p' packet. */
6084 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6086 struct remote_state *rs = get_remote_state ();
6088 char regp[MAX_REGISTER_SIZE];
6091 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
6094 if (reg->pnum == -1)
6099 p += hexnumstr (p, reg->pnum);
6102 getpkt (&rs->buf, &rs->buf_size, 0);
6106 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6110 case PACKET_UNKNOWN:
6113 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6114 gdbarch_register_name (get_regcache_arch (regcache),
6119 /* If this register is unfetchable, tell the regcache. */
6122 regcache_raw_supply (regcache, reg->regnum, NULL);
6126 /* Otherwise, parse and supply the value. */
6132 error (_("fetch_register_using_p: early buf termination"));
6134 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6137 regcache_raw_supply (regcache, reg->regnum, regp);
6141 /* Fetch the registers included in the target's 'g' packet. */
6144 send_g_packet (void)
6146 struct remote_state *rs = get_remote_state ();
6149 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6150 remote_send (&rs->buf, &rs->buf_size);
6152 /* We can get out of synch in various cases. If the first character
6153 in the buffer is not a hex character, assume that has happened
6154 and try to fetch another packet to read. */
6155 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6156 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6157 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6158 && rs->buf[0] != 'x') /* New: unavailable register value. */
6161 fprintf_unfiltered (gdb_stdlog,
6162 "Bad register packet; fetching a new packet\n");
6163 getpkt (&rs->buf, &rs->buf_size, 0);
6166 buf_len = strlen (rs->buf);
6168 /* Sanity check the received packet. */
6169 if (buf_len % 2 != 0)
6170 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6176 process_g_packet (struct regcache *regcache)
6178 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6179 struct remote_state *rs = get_remote_state ();
6180 struct remote_arch_state *rsa = get_remote_arch_state ();
6185 buf_len = strlen (rs->buf);
6187 /* Further sanity checks, with knowledge of the architecture. */
6188 if (buf_len > 2 * rsa->sizeof_g_packet)
6189 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6191 /* Save the size of the packet sent to us by the target. It is used
6192 as a heuristic when determining the max size of packets that the
6193 target can safely receive. */
6194 if (rsa->actual_register_packet_size == 0)
6195 rsa->actual_register_packet_size = buf_len;
6197 /* If this is smaller than we guessed the 'g' packet would be,
6198 update our records. A 'g' reply that doesn't include a register's
6199 value implies either that the register is not available, or that
6200 the 'p' packet must be used. */
6201 if (buf_len < 2 * rsa->sizeof_g_packet)
6203 rsa->sizeof_g_packet = buf_len / 2;
6205 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6207 if (rsa->regs[i].pnum == -1)
6210 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6211 rsa->regs[i].in_g_packet = 0;
6213 rsa->regs[i].in_g_packet = 1;
6217 regs = alloca (rsa->sizeof_g_packet);
6219 /* Unimplemented registers read as all bits zero. */
6220 memset (regs, 0, rsa->sizeof_g_packet);
6222 /* Reply describes registers byte by byte, each byte encoded as two
6223 hex characters. Suck them all up, then supply them to the
6224 register cacheing/storage mechanism. */
6227 for (i = 0; i < rsa->sizeof_g_packet; i++)
6229 if (p[0] == 0 || p[1] == 0)
6230 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6231 internal_error (__FILE__, __LINE__,
6232 _("unexpected end of 'g' packet reply"));
6234 if (p[0] == 'x' && p[1] == 'x')
6235 regs[i] = 0; /* 'x' */
6237 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6241 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6243 struct packet_reg *r = &rsa->regs[i];
6247 if (r->offset * 2 >= strlen (rs->buf))
6248 /* This shouldn't happen - we adjusted in_g_packet above. */
6249 internal_error (__FILE__, __LINE__,
6250 _("unexpected end of 'g' packet reply"));
6251 else if (rs->buf[r->offset * 2] == 'x')
6253 gdb_assert (r->offset * 2 < strlen (rs->buf));
6254 /* The register isn't available, mark it as such (at
6255 the same time setting the value to zero). */
6256 regcache_raw_supply (regcache, r->regnum, NULL);
6259 regcache_raw_supply (regcache, r->regnum,
6266 fetch_registers_using_g (struct regcache *regcache)
6269 process_g_packet (regcache);
6272 /* Make the remote selected traceframe match GDB's selected
6276 set_remote_traceframe (void)
6280 if (remote_traceframe_number == get_traceframe_number ())
6283 /* Avoid recursion, remote_trace_find calls us again. */
6284 remote_traceframe_number = get_traceframe_number ();
6286 newnum = target_trace_find (tfind_number,
6287 get_traceframe_number (), 0, 0, NULL);
6289 /* Should not happen. If it does, all bets are off. */
6290 if (newnum != get_traceframe_number ())
6291 warning (_("could not set remote traceframe"));
6295 remote_fetch_registers (struct target_ops *ops,
6296 struct regcache *regcache, int regnum)
6298 struct remote_arch_state *rsa = get_remote_arch_state ();
6301 set_remote_traceframe ();
6302 set_general_thread (inferior_ptid);
6306 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6308 gdb_assert (reg != NULL);
6310 /* If this register might be in the 'g' packet, try that first -
6311 we are likely to read more than one register. If this is the
6312 first 'g' packet, we might be overly optimistic about its
6313 contents, so fall back to 'p'. */
6314 if (reg->in_g_packet)
6316 fetch_registers_using_g (regcache);
6317 if (reg->in_g_packet)
6321 if (fetch_register_using_p (regcache, reg))
6324 /* This register is not available. */
6325 regcache_raw_supply (regcache, reg->regnum, NULL);
6330 fetch_registers_using_g (regcache);
6332 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6333 if (!rsa->regs[i].in_g_packet)
6334 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6336 /* This register is not available. */
6337 regcache_raw_supply (regcache, i, NULL);
6341 /* Prepare to store registers. Since we may send them all (using a
6342 'G' request), we have to read out the ones we don't want to change
6346 remote_prepare_to_store (struct regcache *regcache)
6348 struct remote_arch_state *rsa = get_remote_arch_state ();
6350 gdb_byte buf[MAX_REGISTER_SIZE];
6352 /* Make sure the entire registers array is valid. */
6353 switch (remote_protocol_packets[PACKET_P].support)
6355 case PACKET_DISABLE:
6356 case PACKET_SUPPORT_UNKNOWN:
6357 /* Make sure all the necessary registers are cached. */
6358 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6359 if (rsa->regs[i].in_g_packet)
6360 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6367 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6368 packet was not recognized. */
6371 store_register_using_P (const struct regcache *regcache,
6372 struct packet_reg *reg)
6374 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6375 struct remote_state *rs = get_remote_state ();
6376 /* Try storing a single register. */
6377 char *buf = rs->buf;
6378 gdb_byte regp[MAX_REGISTER_SIZE];
6381 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
6384 if (reg->pnum == -1)
6387 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6388 p = buf + strlen (buf);
6389 regcache_raw_collect (regcache, reg->regnum, regp);
6390 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6392 getpkt (&rs->buf, &rs->buf_size, 0);
6394 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6399 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6400 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6401 case PACKET_UNKNOWN:
6404 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6408 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6409 contents of the register cache buffer. FIXME: ignores errors. */
6412 store_registers_using_G (const struct regcache *regcache)
6414 struct remote_state *rs = get_remote_state ();
6415 struct remote_arch_state *rsa = get_remote_arch_state ();
6419 /* Extract all the registers in the regcache copying them into a
6424 regs = alloca (rsa->sizeof_g_packet);
6425 memset (regs, 0, rsa->sizeof_g_packet);
6426 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6428 struct packet_reg *r = &rsa->regs[i];
6431 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6435 /* Command describes registers byte by byte,
6436 each byte encoded as two hex characters. */
6439 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6441 bin2hex (regs, p, rsa->sizeof_g_packet);
6443 getpkt (&rs->buf, &rs->buf_size, 0);
6444 if (packet_check_result (rs->buf) == PACKET_ERROR)
6445 error (_("Could not write registers; remote failure reply '%s'"),
6449 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6450 of the register cache buffer. FIXME: ignores errors. */
6453 remote_store_registers (struct target_ops *ops,
6454 struct regcache *regcache, int regnum)
6456 struct remote_arch_state *rsa = get_remote_arch_state ();
6459 set_remote_traceframe ();
6460 set_general_thread (inferior_ptid);
6464 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6466 gdb_assert (reg != NULL);
6468 /* Always prefer to store registers using the 'P' packet if
6469 possible; we often change only a small number of registers.
6470 Sometimes we change a larger number; we'd need help from a
6471 higher layer to know to use 'G'. */
6472 if (store_register_using_P (regcache, reg))
6475 /* For now, don't complain if we have no way to write the
6476 register. GDB loses track of unavailable registers too
6477 easily. Some day, this may be an error. We don't have
6478 any way to read the register, either... */
6479 if (!reg->in_g_packet)
6482 store_registers_using_G (regcache);
6486 store_registers_using_G (regcache);
6488 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6489 if (!rsa->regs[i].in_g_packet)
6490 if (!store_register_using_P (regcache, &rsa->regs[i]))
6491 /* See above for why we do not issue an error here. */
6496 /* Return the number of hex digits in num. */
6499 hexnumlen (ULONGEST num)
6503 for (i = 0; num != 0; i++)
6509 /* Set BUF to the minimum number of hex digits representing NUM. */
6512 hexnumstr (char *buf, ULONGEST num)
6514 int len = hexnumlen (num);
6516 return hexnumnstr (buf, num, len);
6520 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6523 hexnumnstr (char *buf, ULONGEST num, int width)
6529 for (i = width - 1; i >= 0; i--)
6531 buf[i] = "0123456789abcdef"[(num & 0xf)];
6538 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6541 remote_address_masked (CORE_ADDR addr)
6543 unsigned int address_size = remote_address_size;
6545 /* If "remoteaddresssize" was not set, default to target address size. */
6547 address_size = gdbarch_addr_bit (target_gdbarch ());
6549 if (address_size > 0
6550 && address_size < (sizeof (ULONGEST) * 8))
6552 /* Only create a mask when that mask can safely be constructed
6553 in a ULONGEST variable. */
6556 mask = (mask << address_size) - 1;
6562 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
6563 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6564 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6565 (which may be more than *OUT_LEN due to escape characters). The
6566 total number of bytes in the output buffer will be at most
6570 remote_escape_output (const gdb_byte *buffer, int len,
6571 gdb_byte *out_buf, int *out_len,
6574 int input_index, output_index;
6577 for (input_index = 0; input_index < len; input_index++)
6579 gdb_byte b = buffer[input_index];
6581 if (b == '$' || b == '#' || b == '}')
6583 /* These must be escaped. */
6584 if (output_index + 2 > out_maxlen)
6586 out_buf[output_index++] = '}';
6587 out_buf[output_index++] = b ^ 0x20;
6591 if (output_index + 1 > out_maxlen)
6593 out_buf[output_index++] = b;
6597 *out_len = input_index;
6598 return output_index;
6601 /* Convert BUFFER, escaped data LEN bytes long, into binary data
6602 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6603 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6605 This function reverses remote_escape_output. It allows more
6606 escaped characters than that function does, in particular because
6607 '*' must be escaped to avoid the run-length encoding processing
6608 in reading packets. */
6611 remote_unescape_input (const gdb_byte *buffer, int len,
6612 gdb_byte *out_buf, int out_maxlen)
6614 int input_index, output_index;
6619 for (input_index = 0; input_index < len; input_index++)
6621 gdb_byte b = buffer[input_index];
6623 if (output_index + 1 > out_maxlen)
6625 warning (_("Received too much data from remote target;"
6626 " ignoring overflow."));
6627 return output_index;
6632 out_buf[output_index++] = b ^ 0x20;
6638 out_buf[output_index++] = b;
6642 error (_("Unmatched escape character in target response."));
6644 return output_index;
6647 /* Determine whether the remote target supports binary downloading.
6648 This is accomplished by sending a no-op memory write of zero length
6649 to the target at the specified address. It does not suffice to send
6650 the whole packet, since many stubs strip the eighth bit and
6651 subsequently compute a wrong checksum, which causes real havoc with
6654 NOTE: This can still lose if the serial line is not eight-bit
6655 clean. In cases like this, the user should clear "remote
6659 check_binary_download (CORE_ADDR addr)
6661 struct remote_state *rs = get_remote_state ();
6663 switch (remote_protocol_packets[PACKET_X].support)
6665 case PACKET_DISABLE:
6669 case PACKET_SUPPORT_UNKNOWN:
6675 p += hexnumstr (p, (ULONGEST) addr);
6677 p += hexnumstr (p, (ULONGEST) 0);
6681 putpkt_binary (rs->buf, (int) (p - rs->buf));
6682 getpkt (&rs->buf, &rs->buf_size, 0);
6684 if (rs->buf[0] == '\0')
6687 fprintf_unfiltered (gdb_stdlog,
6688 "binary downloading NOT "
6689 "supported by target\n");
6690 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6695 fprintf_unfiltered (gdb_stdlog,
6696 "binary downloading supported by target\n");
6697 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6704 /* Write memory data directly to the remote machine.
6705 This does not inform the data cache; the data cache uses this.
6706 HEADER is the starting part of the packet.
6707 MEMADDR is the address in the remote memory space.
6708 MYADDR is the address of the buffer in our space.
6709 LEN is the number of bytes.
6710 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6711 should send data as binary ('X'), or hex-encoded ('M').
6713 The function creates packet of the form
6714 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6716 where encoding of <DATA> is termined by PACKET_FORMAT.
6718 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6721 Returns the number of bytes transferred, or 0 (setting errno) for
6722 error. Only transfer a single packet. */
6725 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6726 const gdb_byte *myaddr, ssize_t len,
6727 char packet_format, int use_length)
6729 struct remote_state *rs = get_remote_state ();
6739 if (packet_format != 'X' && packet_format != 'M')
6740 internal_error (__FILE__, __LINE__,
6741 _("remote_write_bytes_aux: bad packet format"));
6746 payload_size = get_memory_write_packet_size ();
6748 /* The packet buffer will be large enough for the payload;
6749 get_memory_packet_size ensures this. */
6752 /* Compute the size of the actual payload by subtracting out the
6753 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6755 payload_size -= strlen ("$,:#NN");
6757 /* The comma won't be used. */
6759 header_length = strlen (header);
6760 payload_size -= header_length;
6761 payload_size -= hexnumlen (memaddr);
6763 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6765 strcat (rs->buf, header);
6766 p = rs->buf + strlen (header);
6768 /* Compute a best guess of the number of bytes actually transfered. */
6769 if (packet_format == 'X')
6771 /* Best guess at number of bytes that will fit. */
6772 todo = min (len, payload_size);
6774 payload_size -= hexnumlen (todo);
6775 todo = min (todo, payload_size);
6779 /* Num bytes that will fit. */
6780 todo = min (len, payload_size / 2);
6782 payload_size -= hexnumlen (todo);
6783 todo = min (todo, payload_size / 2);
6787 internal_error (__FILE__, __LINE__,
6788 _("minimum packet size too small to write data"));
6790 /* If we already need another packet, then try to align the end
6791 of this packet to a useful boundary. */
6792 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6793 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6795 /* Append "<memaddr>". */
6796 memaddr = remote_address_masked (memaddr);
6797 p += hexnumstr (p, (ULONGEST) memaddr);
6804 /* Append <len>. Retain the location/size of <len>. It may need to
6805 be adjusted once the packet body has been created. */
6807 plenlen = hexnumstr (p, (ULONGEST) todo);
6815 /* Append the packet body. */
6816 if (packet_format == 'X')
6818 /* Binary mode. Send target system values byte by byte, in
6819 increasing byte addresses. Only escape certain critical
6821 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6822 &nr_bytes, payload_size);
6824 /* If not all TODO bytes fit, then we'll need another packet. Make
6825 a second try to keep the end of the packet aligned. Don't do
6826 this if the packet is tiny. */
6827 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6831 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6833 if (new_nr_bytes != nr_bytes)
6834 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6835 (gdb_byte *) p, &nr_bytes,
6839 p += payload_length;
6840 if (use_length && nr_bytes < todo)
6842 /* Escape chars have filled up the buffer prematurely,
6843 and we have actually sent fewer bytes than planned.
6844 Fix-up the length field of the packet. Use the same
6845 number of characters as before. */
6846 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6847 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6852 /* Normal mode: Send target system values byte by byte, in
6853 increasing byte addresses. Each byte is encoded as a two hex
6855 nr_bytes = bin2hex (myaddr, p, todo);
6859 putpkt_binary (rs->buf, (int) (p - rs->buf));
6860 getpkt (&rs->buf, &rs->buf_size, 0);
6862 if (rs->buf[0] == 'E')
6864 /* There is no correspondance between what the remote protocol
6865 uses for errors and errno codes. We would like a cleaner way
6866 of representing errors (big enough to include errno codes,
6867 bfd_error codes, and others). But for now just return EIO. */
6872 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6873 fewer bytes than we'd planned. */
6877 /* Write memory data directly to the remote machine.
6878 This does not inform the data cache; the data cache uses this.
6879 MEMADDR is the address in the remote memory space.
6880 MYADDR is the address of the buffer in our space.
6881 LEN is the number of bytes.
6883 Returns number of bytes transferred, or 0 (setting errno) for
6884 error. Only transfer a single packet. */
6887 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
6889 char *packet_format = 0;
6891 /* Check whether the target supports binary download. */
6892 check_binary_download (memaddr);
6894 switch (remote_protocol_packets[PACKET_X].support)
6897 packet_format = "X";
6899 case PACKET_DISABLE:
6900 packet_format = "M";
6902 case PACKET_SUPPORT_UNKNOWN:
6903 internal_error (__FILE__, __LINE__,
6904 _("remote_write_bytes: bad internal state"));
6906 internal_error (__FILE__, __LINE__, _("bad switch"));
6909 return remote_write_bytes_aux (packet_format,
6910 memaddr, myaddr, len, packet_format[0], 1);
6913 /* Read memory data directly from the remote machine.
6914 This does not use the data cache; the data cache uses this.
6915 MEMADDR is the address in the remote memory space.
6916 MYADDR is the address of the buffer in our space.
6917 LEN is the number of bytes.
6919 Returns number of bytes transferred, or 0 for error. */
6922 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6924 struct remote_state *rs = get_remote_state ();
6925 int max_buf_size; /* Max size of packet output buffer. */
6933 max_buf_size = get_memory_read_packet_size ();
6934 /* The packet buffer will be large enough for the payload;
6935 get_memory_packet_size ensures this. */
6937 /* Number if bytes that will fit. */
6938 todo = min (len, max_buf_size / 2);
6940 /* Construct "m"<memaddr>","<len>". */
6941 memaddr = remote_address_masked (memaddr);
6944 p += hexnumstr (p, (ULONGEST) memaddr);
6946 p += hexnumstr (p, (ULONGEST) todo);
6949 getpkt (&rs->buf, &rs->buf_size, 0);
6950 if (rs->buf[0] == 'E'
6951 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6952 && rs->buf[3] == '\0')
6954 /* There is no correspondance between what the remote protocol
6955 uses for errors and errno codes. We would like a cleaner way
6956 of representing errors (big enough to include errno codes,
6957 bfd_error codes, and others). But for now just return
6962 /* Reply describes memory byte by byte, each byte encoded as two hex
6965 i = hex2bin (p, myaddr, todo);
6966 /* Return what we have. Let higher layers handle partial reads. */
6971 /* Read or write LEN bytes from inferior memory at MEMADDR,
6972 transferring to or from debugger address BUFFER. Write to inferior
6973 if SHOULD_WRITE is nonzero. Returns length of data written or
6974 read; 0 for error. TARGET is unused. */
6977 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
6978 int should_write, struct mem_attrib *attrib,
6979 struct target_ops *target)
6983 set_remote_traceframe ();
6984 set_general_thread (inferior_ptid);
6987 res = remote_write_bytes (mem_addr, buffer, mem_len);
6989 res = remote_read_bytes (mem_addr, buffer, mem_len);
6994 /* Sends a packet with content determined by the printf format string
6995 FORMAT and the remaining arguments, then gets the reply. Returns
6996 whether the packet was a success, a failure, or unknown. */
6998 static enum packet_result
6999 remote_send_printf (const char *format, ...)
7001 struct remote_state *rs = get_remote_state ();
7002 int max_size = get_remote_packet_size ();
7005 va_start (ap, format);
7008 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7009 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7011 if (putpkt (rs->buf) < 0)
7012 error (_("Communication problem with target."));
7015 getpkt (&rs->buf, &rs->buf_size, 0);
7017 return packet_check_result (rs->buf);
7021 restore_remote_timeout (void *p)
7023 int value = *(int *)p;
7025 remote_timeout = value;
7028 /* Flash writing can take quite some time. We'll set
7029 effectively infinite timeout for flash operations.
7030 In future, we'll need to decide on a better approach. */
7031 static const int remote_flash_timeout = 1000;
7034 remote_flash_erase (struct target_ops *ops,
7035 ULONGEST address, LONGEST length)
7037 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7038 int saved_remote_timeout = remote_timeout;
7039 enum packet_result ret;
7040 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7041 &saved_remote_timeout);
7043 remote_timeout = remote_flash_timeout;
7045 ret = remote_send_printf ("vFlashErase:%s,%s",
7046 phex (address, addr_size),
7050 case PACKET_UNKNOWN:
7051 error (_("Remote target does not support flash erase"));
7053 error (_("Error erasing flash with vFlashErase packet"));
7058 do_cleanups (back_to);
7062 remote_flash_write (struct target_ops *ops,
7063 ULONGEST address, LONGEST length,
7064 const gdb_byte *data)
7066 int saved_remote_timeout = remote_timeout;
7068 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7069 &saved_remote_timeout);
7071 remote_timeout = remote_flash_timeout;
7072 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
7073 do_cleanups (back_to);
7079 remote_flash_done (struct target_ops *ops)
7081 int saved_remote_timeout = remote_timeout;
7083 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7084 &saved_remote_timeout);
7086 remote_timeout = remote_flash_timeout;
7087 ret = remote_send_printf ("vFlashDone");
7088 do_cleanups (back_to);
7092 case PACKET_UNKNOWN:
7093 error (_("Remote target does not support vFlashDone"));
7095 error (_("Error finishing flash operation"));
7102 remote_files_info (struct target_ops *ignore)
7104 puts_filtered ("Debugging a target over a serial line.\n");
7107 /* Stuff for dealing with the packets which are part of this protocol.
7108 See comment at top of file for details. */
7110 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7111 error to higher layers. Called when a serial error is detected.
7112 The exception message is STRING, followed by a colon and a blank,
7113 the system error message for errno at function entry and final dot
7114 for output compatibility with throw_perror_with_name. */
7117 unpush_and_perror (const char *string)
7119 int saved_errno = errno;
7121 remote_unpush_target ();
7122 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7123 safe_strerror (saved_errno));
7126 /* Read a single character from the remote end. */
7129 readchar (int timeout)
7133 ch = serial_readchar (remote_desc, timeout);
7138 switch ((enum serial_rc) ch)
7141 remote_unpush_target ();
7142 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7145 unpush_and_perror (_("Remote communication error. "
7146 "Target disconnected."));
7148 case SERIAL_TIMEOUT:
7154 /* Wrapper for serial_write that closes the target and throws if
7158 remote_serial_write (const char *str, int len)
7160 if (serial_write (remote_desc, str, len))
7162 unpush_and_perror (_("Remote communication error. "
7163 "Target disconnected."));
7167 /* Send the command in *BUF to the remote machine, and read the reply
7168 into *BUF. Report an error if we get an error reply. Resize
7169 *BUF using xrealloc if necessary to hold the result, and update
7173 remote_send (char **buf,
7177 getpkt (buf, sizeof_buf, 0);
7179 if ((*buf)[0] == 'E')
7180 error (_("Remote failure reply: %s"), *buf);
7183 /* Return a pointer to an xmalloc'ed string representing an escaped
7184 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7185 etc. The caller is responsible for releasing the returned
7189 escape_buffer (const char *buf, int n)
7191 struct cleanup *old_chain;
7192 struct ui_file *stb;
7195 stb = mem_fileopen ();
7196 old_chain = make_cleanup_ui_file_delete (stb);
7198 fputstrn_unfiltered (buf, n, 0, stb);
7199 str = ui_file_xstrdup (stb, NULL);
7200 do_cleanups (old_chain);
7204 /* Display a null-terminated packet on stdout, for debugging, using C
7208 print_packet (char *buf)
7210 puts_filtered ("\"");
7211 fputstr_filtered (buf, '"', gdb_stdout);
7212 puts_filtered ("\"");
7218 return putpkt_binary (buf, strlen (buf));
7221 /* Send a packet to the remote machine, with error checking. The data
7222 of the packet is in BUF. The string in BUF can be at most
7223 get_remote_packet_size () - 5 to account for the $, # and checksum,
7224 and for a possible /0 if we are debugging (remote_debug) and want
7225 to print the sent packet as a string. */
7228 putpkt_binary (char *buf, int cnt)
7230 struct remote_state *rs = get_remote_state ();
7232 unsigned char csum = 0;
7233 char *buf2 = alloca (cnt + 6);
7240 /* Catch cases like trying to read memory or listing threads while
7241 we're waiting for a stop reply. The remote server wouldn't be
7242 ready to handle this request, so we'd hang and timeout. We don't
7243 have to worry about this in synchronous mode, because in that
7244 case it's not possible to issue a command while the target is
7245 running. This is not a problem in non-stop mode, because in that
7246 case, the stub is always ready to process serial input. */
7247 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
7248 error (_("Cannot execute this command while the target is running."));
7250 /* We're sending out a new packet. Make sure we don't look at a
7251 stale cached response. */
7252 rs->cached_wait_status = 0;
7254 /* Copy the packet into buffer BUF2, encapsulating it
7255 and giving it a checksum. */
7260 for (i = 0; i < cnt; i++)
7266 *p++ = tohex ((csum >> 4) & 0xf);
7267 *p++ = tohex (csum & 0xf);
7269 /* Send it over and over until we get a positive ack. */
7273 int started_error_output = 0;
7277 struct cleanup *old_chain;
7281 str = escape_buffer (buf2, p - buf2);
7282 old_chain = make_cleanup (xfree, str);
7283 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7284 gdb_flush (gdb_stdlog);
7285 do_cleanups (old_chain);
7287 remote_serial_write (buf2, p - buf2);
7289 /* If this is a no acks version of the remote protocol, send the
7290 packet and move on. */
7294 /* Read until either a timeout occurs (-2) or '+' is read.
7295 Handle any notification that arrives in the mean time. */
7298 ch = readchar (remote_timeout);
7306 case SERIAL_TIMEOUT:
7309 if (started_error_output)
7311 putchar_unfiltered ('\n');
7312 started_error_output = 0;
7321 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7325 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7327 case SERIAL_TIMEOUT:
7331 break; /* Retransmit buffer. */
7335 fprintf_unfiltered (gdb_stdlog,
7336 "Packet instead of Ack, ignoring it\n");
7337 /* It's probably an old response sent because an ACK
7338 was lost. Gobble up the packet and ack it so it
7339 doesn't get retransmitted when we resend this
7342 remote_serial_write ("+", 1);
7343 continue; /* Now, go look for +. */
7350 /* If we got a notification, handle it, and go back to looking
7352 /* We've found the start of a notification. Now
7353 collect the data. */
7354 val = read_frame (&rs->buf, &rs->buf_size);
7359 struct cleanup *old_chain;
7362 str = escape_buffer (rs->buf, val);
7363 old_chain = make_cleanup (xfree, str);
7364 fprintf_unfiltered (gdb_stdlog,
7365 " Notification received: %s\n",
7367 do_cleanups (old_chain);
7369 handle_notification (rs->buf);
7370 /* We're in sync now, rewait for the ack. */
7377 if (!started_error_output)
7379 started_error_output = 1;
7380 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7382 fputc_unfiltered (ch & 0177, gdb_stdlog);
7383 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7392 if (!started_error_output)
7394 started_error_output = 1;
7395 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7397 fputc_unfiltered (ch & 0177, gdb_stdlog);
7401 break; /* Here to retransmit. */
7405 /* This is wrong. If doing a long backtrace, the user should be
7406 able to get out next time we call QUIT, without anything as
7407 violent as interrupt_query. If we want to provide a way out of
7408 here without getting to the next QUIT, it should be based on
7409 hitting ^C twice as in remote_wait. */
7420 /* Come here after finding the start of a frame when we expected an
7421 ack. Do our best to discard the rest of this packet. */
7430 c = readchar (remote_timeout);
7433 case SERIAL_TIMEOUT:
7434 /* Nothing we can do. */
7437 /* Discard the two bytes of checksum and stop. */
7438 c = readchar (remote_timeout);
7440 c = readchar (remote_timeout);
7443 case '*': /* Run length encoding. */
7444 /* Discard the repeat count. */
7445 c = readchar (remote_timeout);
7450 /* A regular character. */
7456 /* Come here after finding the start of the frame. Collect the rest
7457 into *BUF, verifying the checksum, length, and handling run-length
7458 compression. NUL terminate the buffer. If there is not enough room,
7459 expand *BUF using xrealloc.
7461 Returns -1 on error, number of characters in buffer (ignoring the
7462 trailing NULL) on success. (could be extended to return one of the
7463 SERIAL status indications). */
7466 read_frame (char **buf_p,
7473 struct remote_state *rs = get_remote_state ();
7480 c = readchar (remote_timeout);
7483 case SERIAL_TIMEOUT:
7485 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7489 fputs_filtered ("Saw new packet start in middle of old one\n",
7491 return -1; /* Start a new packet, count retries. */
7494 unsigned char pktcsum;
7500 check_0 = readchar (remote_timeout);
7502 check_1 = readchar (remote_timeout);
7504 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7507 fputs_filtered ("Timeout in checksum, retrying\n",
7511 else if (check_0 < 0 || check_1 < 0)
7514 fputs_filtered ("Communication error in checksum\n",
7519 /* Don't recompute the checksum; with no ack packets we
7520 don't have any way to indicate a packet retransmission
7525 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7526 if (csum == pktcsum)
7531 struct cleanup *old_chain;
7534 str = escape_buffer (buf, bc);
7535 old_chain = make_cleanup (xfree, str);
7536 fprintf_unfiltered (gdb_stdlog,
7537 "Bad checksum, sentsum=0x%x, "
7538 "csum=0x%x, buf=%s\n",
7539 pktcsum, csum, str);
7540 do_cleanups (old_chain);
7542 /* Number of characters in buffer ignoring trailing
7546 case '*': /* Run length encoding. */
7551 c = readchar (remote_timeout);
7553 repeat = c - ' ' + 3; /* Compute repeat count. */
7555 /* The character before ``*'' is repeated. */
7557 if (repeat > 0 && repeat <= 255 && bc > 0)
7559 if (bc + repeat - 1 >= *sizeof_buf - 1)
7561 /* Make some more room in the buffer. */
7562 *sizeof_buf += repeat;
7563 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7567 memset (&buf[bc], buf[bc - 1], repeat);
7573 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7577 if (bc >= *sizeof_buf - 1)
7579 /* Make some more room in the buffer. */
7581 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7592 /* Read a packet from the remote machine, with error checking, and
7593 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7594 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7595 rather than timing out; this is used (in synchronous mode) to wait
7596 for a target that is is executing user code to stop. */
7597 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7598 don't have to change all the calls to getpkt to deal with the
7599 return value, because at the moment I don't know what the right
7600 thing to do it for those. */
7608 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7612 /* Read a packet from the remote machine, with error checking, and
7613 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7614 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7615 rather than timing out; this is used (in synchronous mode) to wait
7616 for a target that is is executing user code to stop. If FOREVER ==
7617 0, this function is allowed to time out gracefully and return an
7618 indication of this to the caller. Otherwise return the number of
7619 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7620 enough reason to return to the caller. *IS_NOTIF is an output
7621 boolean that indicates whether *BUF holds a notification or not
7622 (a regular packet). */
7625 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7626 int expecting_notif, int *is_notif)
7628 struct remote_state *rs = get_remote_state ();
7634 /* We're reading a new response. Make sure we don't look at a
7635 previously cached response. */
7636 rs->cached_wait_status = 0;
7638 strcpy (*buf, "timeout");
7641 timeout = watchdog > 0 ? watchdog : -1;
7642 else if (expecting_notif)
7643 timeout = 0; /* There should already be a char in the buffer. If
7646 timeout = remote_timeout;
7650 /* Process any number of notifications, and then return when
7654 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7656 for (tries = 1; tries <= MAX_TRIES; tries++)
7658 /* This can loop forever if the remote side sends us
7659 characters continuously, but if it pauses, we'll get
7660 SERIAL_TIMEOUT from readchar because of timeout. Then
7661 we'll count that as a retry.
7663 Note that even when forever is set, we will only wait
7664 forever prior to the start of a packet. After that, we
7665 expect characters to arrive at a brisk pace. They should
7666 show up within remote_timeout intervals. */
7668 c = readchar (timeout);
7669 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7671 if (c == SERIAL_TIMEOUT)
7673 if (expecting_notif)
7674 return -1; /* Don't complain, it's normal to not get
7675 anything in this case. */
7677 if (forever) /* Watchdog went off? Kill the target. */
7680 remote_unpush_target ();
7681 throw_error (TARGET_CLOSE_ERROR,
7682 _("Watchdog timeout has expired. "
7683 "Target detached."));
7686 fputs_filtered ("Timed out.\n", gdb_stdlog);
7690 /* We've found the start of a packet or notification.
7691 Now collect the data. */
7692 val = read_frame (buf, sizeof_buf);
7697 remote_serial_write ("-", 1);
7700 if (tries > MAX_TRIES)
7702 /* We have tried hard enough, and just can't receive the
7703 packet/notification. Give up. */
7704 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7706 /* Skip the ack char if we're in no-ack mode. */
7707 if (!rs->noack_mode)
7708 remote_serial_write ("+", 1);
7712 /* If we got an ordinary packet, return that to our caller. */
7717 struct cleanup *old_chain;
7720 str = escape_buffer (*buf, val);
7721 old_chain = make_cleanup (xfree, str);
7722 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7723 do_cleanups (old_chain);
7726 /* Skip the ack char if we're in no-ack mode. */
7727 if (!rs->noack_mode)
7728 remote_serial_write ("+", 1);
7729 if (is_notif != NULL)
7734 /* If we got a notification, handle it, and go back to looking
7738 gdb_assert (c == '%');
7742 struct cleanup *old_chain;
7745 str = escape_buffer (*buf, val);
7746 old_chain = make_cleanup (xfree, str);
7747 fprintf_unfiltered (gdb_stdlog,
7748 " Notification received: %s\n",
7750 do_cleanups (old_chain);
7752 if (is_notif != NULL)
7755 handle_notification (*buf);
7757 /* Notifications require no acknowledgement. */
7759 if (expecting_notif)
7766 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7768 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7772 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7775 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7780 /* A helper function that just calls putpkt; for type correctness. */
7783 putpkt_for_catch_errors (void *arg)
7785 return putpkt (arg);
7789 remote_kill (struct target_ops *ops)
7791 /* Use catch_errors so the user can quit from gdb even when we
7792 aren't on speaking terms with the remote system. */
7793 catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
7795 /* Don't wait for it to die. I'm not really sure it matters whether
7796 we do or not. For the existing stubs, kill is a noop. */
7797 target_mourn_inferior ();
7801 remote_vkill (int pid, struct remote_state *rs)
7803 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7806 /* Tell the remote target to detach. */
7807 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7809 getpkt (&rs->buf, &rs->buf_size, 0);
7811 if (packet_ok (rs->buf,
7812 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7814 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7821 extended_remote_kill (struct target_ops *ops)
7824 int pid = ptid_get_pid (inferior_ptid);
7825 struct remote_state *rs = get_remote_state ();
7827 res = remote_vkill (pid, rs);
7828 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7830 /* Don't try 'k' on a multi-process aware stub -- it has no way
7831 to specify the pid. */
7835 getpkt (&rs->buf, &rs->buf_size, 0);
7836 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7839 /* Don't wait for it to die. I'm not really sure it matters whether
7840 we do or not. For the existing stubs, kill is a noop. */
7846 error (_("Can't kill process"));
7848 target_mourn_inferior ();
7852 remote_mourn (struct target_ops *ops)
7854 remote_mourn_1 (ops);
7857 /* Worker function for remote_mourn. */
7859 remote_mourn_1 (struct target_ops *target)
7861 unpush_target (target);
7863 /* remote_close takes care of doing most of the clean up. */
7864 generic_mourn_inferior ();
7868 extended_remote_mourn_1 (struct target_ops *target)
7870 struct remote_state *rs = get_remote_state ();
7872 /* In case we got here due to an error, but we're going to stay
7874 rs->waiting_for_stop_reply = 0;
7876 /* If the current general thread belonged to the process we just
7877 detached from or has exited, the remote side current general
7878 thread becomes undefined. Considering a case like this:
7880 - We just got here due to a detach.
7881 - The process that we're detaching from happens to immediately
7882 report a global breakpoint being hit in non-stop mode, in the
7883 same thread we had selected before.
7884 - GDB attaches to this process again.
7885 - This event happens to be the next event we handle.
7887 GDB would consider that the current general thread didn't need to
7888 be set on the stub side (with Hg), since for all it knew,
7889 GENERAL_THREAD hadn't changed.
7891 Notice that although in all-stop mode, the remote server always
7892 sets the current thread to the thread reporting the stop event,
7893 that doesn't happen in non-stop mode; in non-stop, the stub *must
7894 not* change the current thread when reporting a breakpoint hit,
7895 due to the decoupling of event reporting and event handling.
7897 To keep things simple, we always invalidate our notion of the
7899 record_currthread (minus_one_ptid);
7901 /* Unlike "target remote", we do not want to unpush the target; then
7902 the next time the user says "run", we won't be connected. */
7904 /* Call common code to mark the inferior as not running. */
7905 generic_mourn_inferior ();
7907 if (!have_inferiors ())
7909 if (!remote_multi_process_p (rs))
7911 /* Check whether the target is running now - some remote stubs
7912 automatically restart after kill. */
7914 getpkt (&rs->buf, &rs->buf_size, 0);
7916 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7918 /* Assume that the target has been restarted. Set
7919 inferior_ptid so that bits of core GDB realizes
7920 there's something here, e.g., so that the user can
7921 say "kill" again. */
7922 inferior_ptid = magic_null_ptid;
7929 extended_remote_mourn (struct target_ops *ops)
7931 extended_remote_mourn_1 (ops);
7935 extended_remote_supports_disable_randomization (void)
7937 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7942 extended_remote_disable_randomization (int val)
7944 struct remote_state *rs = get_remote_state ();
7947 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7950 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7952 error (_("Target does not support QDisableRandomization."));
7953 if (strcmp (reply, "OK") != 0)
7954 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7958 extended_remote_run (char *args)
7960 struct remote_state *rs = get_remote_state ();
7963 /* If the user has disabled vRun support, or we have detected that
7964 support is not available, do not try it. */
7965 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7968 strcpy (rs->buf, "vRun;");
7969 len = strlen (rs->buf);
7971 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7972 error (_("Remote file name too long for run packet"));
7973 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7975 gdb_assert (args != NULL);
7978 struct cleanup *back_to;
7982 argv = gdb_buildargv (args);
7983 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7984 for (i = 0; argv[i] != NULL; i++)
7986 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7987 error (_("Argument list too long for run packet"));
7988 rs->buf[len++] = ';';
7989 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7991 do_cleanups (back_to);
7994 rs->buf[len++] = '\0';
7997 getpkt (&rs->buf, &rs->buf_size, 0);
7999 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
8001 /* We have a wait response. All is well. */
8004 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
8005 /* It wasn't disabled before, but it is now. */
8009 if (remote_exec_file[0] == '\0')
8010 error (_("Running the default executable on the remote target failed; "
8011 "try \"set remote exec-file\"?"));
8013 error (_("Running \"%s\" on the remote target failed"),
8018 /* In the extended protocol we want to be able to do things like
8019 "run" and have them basically work as expected. So we need
8020 a special create_inferior function. We support changing the
8021 executable file and the command line arguments, but not the
8025 extended_remote_create_inferior_1 (char *exec_file, char *args,
8026 char **env, int from_tty)
8030 struct remote_state *rs = get_remote_state ();
8032 /* If running asynchronously, register the target file descriptor
8033 with the event loop. */
8034 if (target_can_async_p ())
8035 target_async (inferior_event_handler, 0);
8037 /* Disable address space randomization if requested (and supported). */
8038 if (extended_remote_supports_disable_randomization ())
8039 extended_remote_disable_randomization (disable_randomization);
8041 /* Now restart the remote server. */
8042 run_worked = extended_remote_run (args) != -1;
8045 /* vRun was not supported. Fail if we need it to do what the
8047 if (remote_exec_file[0])
8048 error (_("Remote target does not support \"set remote exec-file\""));
8050 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8052 /* Fall back to "R". */
8053 extended_remote_restart ();
8056 if (!have_inferiors ())
8058 /* Clean up from the last time we ran, before we mark the target
8059 running again. This will mark breakpoints uninserted, and
8060 get_offsets may insert breakpoints. */
8061 init_thread_list ();
8062 init_wait_for_inferior ();
8065 /* vRun's success return is a stop reply. */
8066 stop_reply = run_worked ? rs->buf : NULL;
8067 add_current_inferior_and_thread (stop_reply);
8069 /* Get updated offsets, if the stub uses qOffsets. */
8074 extended_remote_create_inferior (struct target_ops *ops,
8075 char *exec_file, char *args,
8076 char **env, int from_tty)
8078 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
8082 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8083 the list of conditions (in agent expression bytecode format), if any, the
8084 target needs to evaluate. The output is placed into the packet buffer
8085 started from BUF and ended at BUF_END. */
8088 remote_add_target_side_condition (struct gdbarch *gdbarch,
8089 struct bp_target_info *bp_tgt, char *buf,
8092 struct agent_expr *aexpr = NULL;
8095 char *buf_start = buf;
8097 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8100 buf += strlen (buf);
8101 xsnprintf (buf, buf_end - buf, "%s", ";");
8104 /* Send conditions to the target and free the vector. */
8106 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8109 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8110 buf += strlen (buf);
8111 for (i = 0; i < aexpr->len; ++i)
8112 buf = pack_hex_byte (buf, aexpr->buf[i]);
8116 VEC_free (agent_expr_p, bp_tgt->conditions);
8121 remote_add_target_side_commands (struct gdbarch *gdbarch,
8122 struct bp_target_info *bp_tgt, char *buf)
8124 struct agent_expr *aexpr = NULL;
8127 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8130 buf += strlen (buf);
8132 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8133 buf += strlen (buf);
8135 /* Concatenate all the agent expressions that are commands into the
8138 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8141 sprintf (buf, "X%x,", aexpr->len);
8142 buf += strlen (buf);
8143 for (i = 0; i < aexpr->len; ++i)
8144 buf = pack_hex_byte (buf, aexpr->buf[i]);
8148 VEC_free (agent_expr_p, bp_tgt->tcommands);
8151 /* Insert a breakpoint. On targets that have software breakpoint
8152 support, we ask the remote target to do the work; on targets
8153 which don't, we insert a traditional memory breakpoint. */
8156 remote_insert_breakpoint (struct gdbarch *gdbarch,
8157 struct bp_target_info *bp_tgt)
8159 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8160 If it succeeds, then set the support to PACKET_ENABLE. If it
8161 fails, and the user has explicitly requested the Z support then
8162 report an error, otherwise, mark it disabled and go on. */
8164 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8166 CORE_ADDR addr = bp_tgt->placed_address;
8167 struct remote_state *rs;
8170 struct condition_list *cond = NULL;
8172 /* Make sure the remote is pointing at the right process, if
8174 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8175 set_general_process ();
8177 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8179 rs = get_remote_state ();
8181 endbuf = rs->buf + get_remote_packet_size ();
8186 addr = (ULONGEST) remote_address_masked (addr);
8187 p += hexnumstr (p, addr);
8188 xsnprintf (p, endbuf - p, ",%d", bpsize);
8190 if (remote_supports_cond_breakpoints ())
8191 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8193 if (remote_can_run_breakpoint_commands ())
8194 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8197 getpkt (&rs->buf, &rs->buf_size, 0);
8199 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8204 bp_tgt->placed_address = addr;
8205 bp_tgt->placed_size = bpsize;
8207 case PACKET_UNKNOWN:
8212 return memory_insert_breakpoint (gdbarch, bp_tgt);
8216 remote_remove_breakpoint (struct gdbarch *gdbarch,
8217 struct bp_target_info *bp_tgt)
8219 CORE_ADDR addr = bp_tgt->placed_address;
8220 struct remote_state *rs = get_remote_state ();
8222 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8225 char *endbuf = rs->buf + get_remote_packet_size ();
8227 /* Make sure the remote is pointing at the right process, if
8229 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8230 set_general_process ();
8236 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8237 p += hexnumstr (p, addr);
8238 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8241 getpkt (&rs->buf, &rs->buf_size, 0);
8243 return (rs->buf[0] == 'E');
8246 return memory_remove_breakpoint (gdbarch, bp_tgt);
8250 watchpoint_to_Z_packet (int type)
8255 return Z_PACKET_WRITE_WP;
8258 return Z_PACKET_READ_WP;
8261 return Z_PACKET_ACCESS_WP;
8264 internal_error (__FILE__, __LINE__,
8265 _("hw_bp_to_z: bad watchpoint type %d"), type);
8270 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
8271 struct expression *cond)
8273 struct remote_state *rs = get_remote_state ();
8274 char *endbuf = rs->buf + get_remote_packet_size ();
8276 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8278 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8281 /* Make sure the remote is pointing at the right process, if
8283 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8284 set_general_process ();
8286 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8287 p = strchr (rs->buf, '\0');
8288 addr = remote_address_masked (addr);
8289 p += hexnumstr (p, (ULONGEST) addr);
8290 xsnprintf (p, endbuf - p, ",%x", len);
8293 getpkt (&rs->buf, &rs->buf_size, 0);
8295 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8299 case PACKET_UNKNOWN:
8304 internal_error (__FILE__, __LINE__,
8305 _("remote_insert_watchpoint: reached end of function"));
8309 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8310 CORE_ADDR start, int length)
8312 CORE_ADDR diff = remote_address_masked (addr - start);
8314 return diff < length;
8319 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
8320 struct expression *cond)
8322 struct remote_state *rs = get_remote_state ();
8323 char *endbuf = rs->buf + get_remote_packet_size ();
8325 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8327 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8330 /* Make sure the remote is pointing at the right process, if
8332 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8333 set_general_process ();
8335 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8336 p = strchr (rs->buf, '\0');
8337 addr = remote_address_masked (addr);
8338 p += hexnumstr (p, (ULONGEST) addr);
8339 xsnprintf (p, endbuf - p, ",%x", len);
8341 getpkt (&rs->buf, &rs->buf_size, 0);
8343 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8346 case PACKET_UNKNOWN:
8351 internal_error (__FILE__, __LINE__,
8352 _("remote_remove_watchpoint: reached end of function"));
8356 int remote_hw_watchpoint_limit = -1;
8357 int remote_hw_watchpoint_length_limit = -1;
8358 int remote_hw_breakpoint_limit = -1;
8361 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
8363 if (remote_hw_watchpoint_length_limit == 0)
8365 else if (remote_hw_watchpoint_length_limit < 0)
8367 else if (len <= remote_hw_watchpoint_length_limit)
8374 remote_check_watch_resources (int type, int cnt, int ot)
8376 if (type == bp_hardware_breakpoint)
8378 if (remote_hw_breakpoint_limit == 0)
8380 else if (remote_hw_breakpoint_limit < 0)
8382 else if (cnt <= remote_hw_breakpoint_limit)
8387 if (remote_hw_watchpoint_limit == 0)
8389 else if (remote_hw_watchpoint_limit < 0)
8393 else if (cnt <= remote_hw_watchpoint_limit)
8400 remote_stopped_by_watchpoint (void)
8402 return remote_stopped_by_watchpoint_p;
8406 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8410 if (remote_stopped_by_watchpoint ())
8412 *addr_p = remote_watch_data_address;
8421 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
8422 struct bp_target_info *bp_tgt)
8425 struct remote_state *rs;
8429 /* The length field should be set to the size of a breakpoint
8430 instruction, even though we aren't inserting one ourselves. */
8432 gdbarch_remote_breakpoint_from_pc
8433 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
8435 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8438 /* Make sure the remote is pointing at the right process, if
8440 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8441 set_general_process ();
8443 rs = get_remote_state ();
8445 endbuf = rs->buf + get_remote_packet_size ();
8451 addr = remote_address_masked (bp_tgt->placed_address);
8452 p += hexnumstr (p, (ULONGEST) addr);
8453 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8455 if (remote_supports_cond_breakpoints ())
8456 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8458 if (remote_can_run_breakpoint_commands ())
8459 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8462 getpkt (&rs->buf, &rs->buf_size, 0);
8464 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8467 if (rs->buf[1] == '.')
8469 message = strchr (rs->buf + 2, '.');
8471 error (_("Remote failure reply: %s"), message + 1);
8474 case PACKET_UNKNOWN:
8479 internal_error (__FILE__, __LINE__,
8480 _("remote_insert_hw_breakpoint: reached end of function"));
8485 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
8486 struct bp_target_info *bp_tgt)
8489 struct remote_state *rs = get_remote_state ();
8491 char *endbuf = rs->buf + get_remote_packet_size ();
8493 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8496 /* Make sure the remote is pointing at the right process, if
8498 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8499 set_general_process ();
8505 addr = remote_address_masked (bp_tgt->placed_address);
8506 p += hexnumstr (p, (ULONGEST) addr);
8507 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8510 getpkt (&rs->buf, &rs->buf_size, 0);
8512 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8515 case PACKET_UNKNOWN:
8520 internal_error (__FILE__, __LINE__,
8521 _("remote_remove_hw_breakpoint: reached end of function"));
8524 /* Verify memory using the "qCRC:" request. */
8527 remote_verify_memory (struct target_ops *ops,
8528 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8530 struct remote_state *rs = get_remote_state ();
8531 unsigned long host_crc, target_crc;
8534 /* Make sure the remote is pointing at the right process. */
8535 set_general_process ();
8537 /* FIXME: assumes lma can fit into long. */
8538 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8539 (long) lma, (long) size);
8542 /* Be clever; compute the host_crc before waiting for target
8544 host_crc = xcrc32 (data, size, 0xffffffff);
8546 getpkt (&rs->buf, &rs->buf_size, 0);
8547 if (rs->buf[0] == 'E')
8550 if (rs->buf[0] != 'C')
8551 error (_("remote target does not support this operation"));
8553 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8554 target_crc = target_crc * 16 + fromhex (*tmp);
8556 return (host_crc == target_crc);
8559 /* compare-sections command
8561 With no arguments, compares each loadable section in the exec bfd
8562 with the same memory range on the target, and reports mismatches.
8563 Useful for verifying the image on the target against the exec file. */
8566 compare_sections_command (char *args, int from_tty)
8569 struct cleanup *old_chain;
8571 const char *sectname;
8579 error (_("command cannot be used without an exec file"));
8581 /* Make sure the remote is pointing at the right process. */
8582 set_general_process ();
8584 for (s = exec_bfd->sections; s; s = s->next)
8586 if (!(s->flags & SEC_LOAD))
8587 continue; /* Skip non-loadable section. */
8589 size = bfd_get_section_size (s);
8591 continue; /* Skip zero-length section. */
8593 sectname = bfd_get_section_name (exec_bfd, s);
8594 if (args && strcmp (args, sectname) != 0)
8595 continue; /* Not the section selected by user. */
8597 matched = 1; /* Do this section. */
8600 sectdata = xmalloc (size);
8601 old_chain = make_cleanup (xfree, sectdata);
8602 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8604 res = target_verify_memory (sectdata, lma, size);
8607 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8608 paddress (target_gdbarch (), lma),
8609 paddress (target_gdbarch (), lma + size));
8611 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8612 paddress (target_gdbarch (), lma),
8613 paddress (target_gdbarch (), lma + size));
8615 printf_filtered ("matched.\n");
8618 printf_filtered ("MIS-MATCHED!\n");
8622 do_cleanups (old_chain);
8625 warning (_("One or more sections of the remote executable does not match\n\
8626 the loaded file\n"));
8627 if (args && !matched)
8628 printf_filtered (_("No loaded section named '%s'.\n"), args);
8631 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8632 into remote target. The number of bytes written to the remote
8633 target is returned, or -1 for error. */
8636 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8637 const char *annex, const gdb_byte *writebuf,
8638 ULONGEST offset, LONGEST len,
8639 struct packet_config *packet)
8643 struct remote_state *rs = get_remote_state ();
8644 int max_size = get_memory_write_packet_size ();
8646 if (packet->support == PACKET_DISABLE)
8649 /* Insert header. */
8650 i = snprintf (rs->buf, max_size,
8651 "qXfer:%s:write:%s:%s:",
8652 object_name, annex ? annex : "",
8653 phex_nz (offset, sizeof offset));
8654 max_size -= (i + 1);
8656 /* Escape as much data as fits into rs->buf. */
8657 buf_len = remote_escape_output
8658 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8660 if (putpkt_binary (rs->buf, i + buf_len) < 0
8661 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8662 || packet_ok (rs->buf, packet) != PACKET_OK)
8665 unpack_varlen_hex (rs->buf, &n);
8669 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8670 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8671 number of bytes read is returned, or 0 for EOF, or -1 for error.
8672 The number of bytes read may be less than LEN without indicating an
8673 EOF. PACKET is checked and updated to indicate whether the remote
8674 target supports this object. */
8677 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8679 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8680 struct packet_config *packet)
8682 static char *finished_object;
8683 static char *finished_annex;
8684 static ULONGEST finished_offset;
8686 struct remote_state *rs = get_remote_state ();
8687 LONGEST i, n, packet_len;
8689 if (packet->support == PACKET_DISABLE)
8692 /* Check whether we've cached an end-of-object packet that matches
8694 if (finished_object)
8696 if (strcmp (object_name, finished_object) == 0
8697 && strcmp (annex ? annex : "", finished_annex) == 0
8698 && offset == finished_offset)
8701 /* Otherwise, we're now reading something different. Discard
8703 xfree (finished_object);
8704 xfree (finished_annex);
8705 finished_object = NULL;
8706 finished_annex = NULL;
8709 /* Request only enough to fit in a single packet. The actual data
8710 may not, since we don't know how much of it will need to be escaped;
8711 the target is free to respond with slightly less data. We subtract
8712 five to account for the response type and the protocol frame. */
8713 n = min (get_remote_packet_size () - 5, len);
8714 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8715 object_name, annex ? annex : "",
8716 phex_nz (offset, sizeof offset),
8717 phex_nz (n, sizeof n));
8718 i = putpkt (rs->buf);
8723 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8724 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8727 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8728 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8730 /* 'm' means there is (or at least might be) more data after this
8731 batch. That does not make sense unless there's at least one byte
8732 of data in this reply. */
8733 if (rs->buf[0] == 'm' && packet_len == 1)
8734 error (_("Remote qXfer reply contained no data."));
8736 /* Got some data. */
8737 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8738 packet_len - 1, readbuf, n);
8740 /* 'l' is an EOF marker, possibly including a final block of data,
8741 or possibly empty. If we have the final block of a non-empty
8742 object, record this fact to bypass a subsequent partial read. */
8743 if (rs->buf[0] == 'l' && offset + i > 0)
8745 finished_object = xstrdup (object_name);
8746 finished_annex = xstrdup (annex ? annex : "");
8747 finished_offset = offset + i;
8754 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8755 const char *annex, gdb_byte *readbuf,
8756 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
8758 struct remote_state *rs;
8763 set_remote_traceframe ();
8764 set_general_thread (inferior_ptid);
8766 rs = get_remote_state ();
8768 /* Handle memory using the standard memory routines. */
8769 if (object == TARGET_OBJECT_MEMORY)
8775 /* If the remote target is connected but not running, we should
8776 pass this request down to a lower stratum (e.g. the executable
8778 if (!target_has_execution)
8781 if (writebuf != NULL)
8782 xfered = remote_write_bytes (offset, writebuf, len);
8784 xfered = remote_read_bytes (offset, readbuf, len);
8788 else if (xfered == 0 && errno == 0)
8794 /* Handle SPU memory using qxfer packets. */
8795 if (object == TARGET_OBJECT_SPU)
8798 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8799 &remote_protocol_packets
8800 [PACKET_qXfer_spu_read]);
8802 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8803 &remote_protocol_packets
8804 [PACKET_qXfer_spu_write]);
8807 /* Handle extra signal info using qxfer packets. */
8808 if (object == TARGET_OBJECT_SIGNAL_INFO)
8811 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8812 &remote_protocol_packets
8813 [PACKET_qXfer_siginfo_read]);
8815 return remote_write_qxfer (ops, "siginfo", annex,
8816 writebuf, offset, len,
8817 &remote_protocol_packets
8818 [PACKET_qXfer_siginfo_write]);
8821 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8824 return remote_read_qxfer (ops, "statictrace", annex,
8825 readbuf, offset, len,
8826 &remote_protocol_packets
8827 [PACKET_qXfer_statictrace_read]);
8832 /* Only handle flash writes. */
8833 if (writebuf != NULL)
8839 case TARGET_OBJECT_FLASH:
8840 xfered = remote_flash_write (ops, offset, len, writebuf);
8844 else if (xfered == 0 && errno == 0)
8854 /* Map pre-existing objects onto letters. DO NOT do this for new
8855 objects!!! Instead specify new query packets. */
8858 case TARGET_OBJECT_AVR:
8862 case TARGET_OBJECT_AUXV:
8863 gdb_assert (annex == NULL);
8864 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8865 &remote_protocol_packets[PACKET_qXfer_auxv]);
8867 case TARGET_OBJECT_AVAILABLE_FEATURES:
8868 return remote_read_qxfer
8869 (ops, "features", annex, readbuf, offset, len,
8870 &remote_protocol_packets[PACKET_qXfer_features]);
8872 case TARGET_OBJECT_LIBRARIES:
8873 return remote_read_qxfer
8874 (ops, "libraries", annex, readbuf, offset, len,
8875 &remote_protocol_packets[PACKET_qXfer_libraries]);
8877 case TARGET_OBJECT_LIBRARIES_SVR4:
8878 return remote_read_qxfer
8879 (ops, "libraries-svr4", annex, readbuf, offset, len,
8880 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8882 case TARGET_OBJECT_MEMORY_MAP:
8883 gdb_assert (annex == NULL);
8884 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8885 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8887 case TARGET_OBJECT_OSDATA:
8888 /* Should only get here if we're connected. */
8889 gdb_assert (remote_desc);
8890 return remote_read_qxfer
8891 (ops, "osdata", annex, readbuf, offset, len,
8892 &remote_protocol_packets[PACKET_qXfer_osdata]);
8894 case TARGET_OBJECT_THREADS:
8895 gdb_assert (annex == NULL);
8896 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8897 &remote_protocol_packets[PACKET_qXfer_threads]);
8899 case TARGET_OBJECT_TRACEFRAME_INFO:
8900 gdb_assert (annex == NULL);
8901 return remote_read_qxfer
8902 (ops, "traceframe-info", annex, readbuf, offset, len,
8903 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8905 case TARGET_OBJECT_FDPIC:
8906 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8907 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8909 case TARGET_OBJECT_OPENVMS_UIB:
8910 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
8911 &remote_protocol_packets[PACKET_qXfer_uib]);
8913 case TARGET_OBJECT_BTRACE:
8914 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
8915 &remote_protocol_packets[PACKET_qXfer_btrace]);
8921 /* Note: a zero OFFSET and LEN can be used to query the minimum
8923 if (offset == 0 && len == 0)
8924 return (get_remote_packet_size ());
8925 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8926 large enough let the caller deal with it. */
8927 if (len < get_remote_packet_size ())
8929 len = get_remote_packet_size ();
8931 /* Except for querying the minimum buffer size, target must be open. */
8933 error (_("remote query is only available after target open"));
8935 gdb_assert (annex != NULL);
8936 gdb_assert (readbuf != NULL);
8942 /* We used one buffer char for the remote protocol q command and
8943 another for the query type. As the remote protocol encapsulation
8944 uses 4 chars plus one extra in case we are debugging
8945 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8948 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8950 /* Bad caller may have sent forbidden characters. */
8951 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8956 gdb_assert (annex[i] == '\0');
8958 i = putpkt (rs->buf);
8962 getpkt (&rs->buf, &rs->buf_size, 0);
8963 strcpy ((char *) readbuf, rs->buf);
8965 return strlen ((char *) readbuf);
8969 remote_search_memory (struct target_ops* ops,
8970 CORE_ADDR start_addr, ULONGEST search_space_len,
8971 const gdb_byte *pattern, ULONGEST pattern_len,
8972 CORE_ADDR *found_addrp)
8974 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8975 struct remote_state *rs = get_remote_state ();
8976 int max_size = get_memory_write_packet_size ();
8977 struct packet_config *packet =
8978 &remote_protocol_packets[PACKET_qSearch_memory];
8979 /* Number of packet bytes used to encode the pattern;
8980 this could be more than PATTERN_LEN due to escape characters. */
8981 int escaped_pattern_len;
8982 /* Amount of pattern that was encodable in the packet. */
8983 int used_pattern_len;
8986 ULONGEST found_addr;
8988 /* Don't go to the target if we don't have to.
8989 This is done before checking packet->support to avoid the possibility that
8990 a success for this edge case means the facility works in general. */
8991 if (pattern_len > search_space_len)
8993 if (pattern_len == 0)
8995 *found_addrp = start_addr;
8999 /* If we already know the packet isn't supported, fall back to the simple
9000 way of searching memory. */
9002 if (packet->support == PACKET_DISABLE)
9004 /* Target doesn't provided special support, fall back and use the
9005 standard support (copy memory and do the search here). */
9006 return simple_search_memory (ops, start_addr, search_space_len,
9007 pattern, pattern_len, found_addrp);
9010 /* Make sure the remote is pointing at the right process. */
9011 set_general_process ();
9013 /* Insert header. */
9014 i = snprintf (rs->buf, max_size,
9015 "qSearch:memory:%s;%s;",
9016 phex_nz (start_addr, addr_size),
9017 phex_nz (search_space_len, sizeof (search_space_len)));
9018 max_size -= (i + 1);
9020 /* Escape as much data as fits into rs->buf. */
9021 escaped_pattern_len =
9022 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9023 &used_pattern_len, max_size);
9025 /* Bail if the pattern is too large. */
9026 if (used_pattern_len != pattern_len)
9027 error (_("Pattern is too large to transmit to remote target."));
9029 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9030 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9031 || packet_ok (rs->buf, packet) != PACKET_OK)
9033 /* The request may not have worked because the command is not
9034 supported. If so, fall back to the simple way. */
9035 if (packet->support == PACKET_DISABLE)
9037 return simple_search_memory (ops, start_addr, search_space_len,
9038 pattern, pattern_len, found_addrp);
9043 if (rs->buf[0] == '0')
9045 else if (rs->buf[0] == '1')
9048 if (rs->buf[1] != ',')
9049 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9050 unpack_varlen_hex (rs->buf + 2, &found_addr);
9051 *found_addrp = found_addr;
9054 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9060 remote_rcmd (char *command,
9061 struct ui_file *outbuf)
9063 struct remote_state *rs = get_remote_state ();
9067 error (_("remote rcmd is only available after target open"));
9069 /* Send a NULL command across as an empty command. */
9070 if (command == NULL)
9073 /* The query prefix. */
9074 strcpy (rs->buf, "qRcmd,");
9075 p = strchr (rs->buf, '\0');
9077 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9078 > get_remote_packet_size ())
9079 error (_("\"monitor\" command ``%s'' is too long."), command);
9081 /* Encode the actual command. */
9082 bin2hex ((gdb_byte *) command, p, 0);
9084 if (putpkt (rs->buf) < 0)
9085 error (_("Communication problem with target."));
9087 /* get/display the response */
9092 /* XXX - see also remote_get_noisy_reply(). */
9093 QUIT; /* Allow user to bail out with ^C. */
9095 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9097 /* Timeout. Continue to (try to) read responses.
9098 This is better than stopping with an error, assuming the stub
9099 is still executing the (long) monitor command.
9100 If needed, the user can interrupt gdb using C-c, obtaining
9101 an effect similar to stop on timeout. */
9106 error (_("Target does not support this command."));
9107 if (buf[0] == 'O' && buf[1] != 'K')
9109 remote_console_output (buf + 1); /* 'O' message from stub. */
9112 if (strcmp (buf, "OK") == 0)
9114 if (strlen (buf) == 3 && buf[0] == 'E'
9115 && isdigit (buf[1]) && isdigit (buf[2]))
9117 error (_("Protocol error with Rcmd"));
9119 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9121 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9123 fputc_unfiltered (c, outbuf);
9129 static VEC(mem_region_s) *
9130 remote_memory_map (struct target_ops *ops)
9132 VEC(mem_region_s) *result = NULL;
9133 char *text = target_read_stralloc (¤t_target,
9134 TARGET_OBJECT_MEMORY_MAP, NULL);
9138 struct cleanup *back_to = make_cleanup (xfree, text);
9140 result = parse_memory_map (text);
9141 do_cleanups (back_to);
9148 packet_command (char *args, int from_tty)
9150 struct remote_state *rs = get_remote_state ();
9153 error (_("command can only be used with remote target"));
9156 error (_("remote-packet command requires packet text as argument"));
9158 puts_filtered ("sending: ");
9159 print_packet (args);
9160 puts_filtered ("\n");
9163 getpkt (&rs->buf, &rs->buf_size, 0);
9164 puts_filtered ("received: ");
9165 print_packet (rs->buf);
9166 puts_filtered ("\n");
9170 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9172 static void display_thread_info (struct gdb_ext_thread_info *info);
9174 static void threadset_test_cmd (char *cmd, int tty);
9176 static void threadalive_test (char *cmd, int tty);
9178 static void threadlist_test_cmd (char *cmd, int tty);
9180 int get_and_display_threadinfo (threadref *ref);
9182 static void threadinfo_test_cmd (char *cmd, int tty);
9184 static int thread_display_step (threadref *ref, void *context);
9186 static void threadlist_update_test_cmd (char *cmd, int tty);
9188 static void init_remote_threadtests (void);
9190 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9193 threadset_test_cmd (char *cmd, int tty)
9195 int sample_thread = SAMPLE_THREAD;
9197 printf_filtered (_("Remote threadset test\n"));
9198 set_general_thread (sample_thread);
9203 threadalive_test (char *cmd, int tty)
9205 int sample_thread = SAMPLE_THREAD;
9206 int pid = ptid_get_pid (inferior_ptid);
9207 ptid_t ptid = ptid_build (pid, 0, sample_thread);
9209 if (remote_thread_alive (ptid))
9210 printf_filtered ("PASS: Thread alive test\n");
9212 printf_filtered ("FAIL: Thread alive test\n");
9215 void output_threadid (char *title, threadref *ref);
9218 output_threadid (char *title, threadref *ref)
9222 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9224 printf_filtered ("%s %s\n", title, (&hexid[0]));
9228 threadlist_test_cmd (char *cmd, int tty)
9231 threadref nextthread;
9232 int done, result_count;
9233 threadref threadlist[3];
9235 printf_filtered ("Remote Threadlist test\n");
9236 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9237 &result_count, &threadlist[0]))
9238 printf_filtered ("FAIL: threadlist test\n");
9241 threadref *scan = threadlist;
9242 threadref *limit = scan + result_count;
9244 while (scan < limit)
9245 output_threadid (" thread ", scan++);
9250 display_thread_info (struct gdb_ext_thread_info *info)
9252 output_threadid ("Threadid: ", &info->threadid);
9253 printf_filtered ("Name: %s\n ", info->shortname);
9254 printf_filtered ("State: %s\n", info->display);
9255 printf_filtered ("other: %s\n\n", info->more_display);
9259 get_and_display_threadinfo (threadref *ref)
9263 struct gdb_ext_thread_info threadinfo;
9265 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9266 | TAG_MOREDISPLAY | TAG_DISPLAY;
9267 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9268 display_thread_info (&threadinfo);
9273 threadinfo_test_cmd (char *cmd, int tty)
9275 int athread = SAMPLE_THREAD;
9279 int_to_threadref (&thread, athread);
9280 printf_filtered ("Remote Threadinfo test\n");
9281 if (!get_and_display_threadinfo (&thread))
9282 printf_filtered ("FAIL cannot get thread info\n");
9286 thread_display_step (threadref *ref, void *context)
9288 /* output_threadid(" threadstep ",ref); *//* simple test */
9289 return get_and_display_threadinfo (ref);
9293 threadlist_update_test_cmd (char *cmd, int tty)
9295 printf_filtered ("Remote Threadlist update test\n");
9296 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9300 init_remote_threadtests (void)
9302 add_com ("tlist", class_obscure, threadlist_test_cmd,
9303 _("Fetch and print the remote list of "
9304 "thread identifiers, one pkt only"));
9305 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9306 _("Fetch and display info about one thread"));
9307 add_com ("tset", class_obscure, threadset_test_cmd,
9308 _("Test setting to a different thread"));
9309 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9310 _("Iterate through updating all remote thread info"));
9311 add_com ("talive", class_obscure, threadalive_test,
9312 _(" Remote thread alive test "));
9317 /* Convert a thread ID to a string. Returns the string in a static
9321 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9323 static char buf[64];
9324 struct remote_state *rs = get_remote_state ();
9326 if (ptid_equal (ptid, null_ptid))
9327 return normal_pid_to_str (ptid);
9328 else if (ptid_is_pid (ptid))
9330 /* Printing an inferior target id. */
9332 /* When multi-process extensions are off, there's no way in the
9333 remote protocol to know the remote process id, if there's any
9334 at all. There's one exception --- when we're connected with
9335 target extended-remote, and we manually attached to a process
9336 with "attach PID". We don't record anywhere a flag that
9337 allows us to distinguish that case from the case of
9338 connecting with extended-remote and the stub already being
9339 attached to a process, and reporting yes to qAttached, hence
9340 no smart special casing here. */
9341 if (!remote_multi_process_p (rs))
9343 xsnprintf (buf, sizeof buf, "Remote target");
9347 return normal_pid_to_str (ptid);
9351 if (ptid_equal (magic_null_ptid, ptid))
9352 xsnprintf (buf, sizeof buf, "Thread <main>");
9353 else if (rs->extended && remote_multi_process_p (rs))
9354 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9355 ptid_get_pid (ptid), ptid_get_tid (ptid));
9357 xsnprintf (buf, sizeof buf, "Thread %ld",
9358 ptid_get_tid (ptid));
9363 /* Get the address of the thread local variable in OBJFILE which is
9364 stored at OFFSET within the thread local storage for thread PTID. */
9367 remote_get_thread_local_address (struct target_ops *ops,
9368 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9370 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
9372 struct remote_state *rs = get_remote_state ();
9374 char *endp = rs->buf + get_remote_packet_size ();
9375 enum packet_result result;
9377 strcpy (p, "qGetTLSAddr:");
9379 p = write_ptid (p, endp, ptid);
9381 p += hexnumstr (p, offset);
9383 p += hexnumstr (p, lm);
9387 getpkt (&rs->buf, &rs->buf_size, 0);
9388 result = packet_ok (rs->buf,
9389 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9390 if (result == PACKET_OK)
9394 unpack_varlen_hex (rs->buf, &result);
9397 else if (result == PACKET_UNKNOWN)
9398 throw_error (TLS_GENERIC_ERROR,
9399 _("Remote target doesn't support qGetTLSAddr packet"));
9401 throw_error (TLS_GENERIC_ERROR,
9402 _("Remote target failed to process qGetTLSAddr request"));
9405 throw_error (TLS_GENERIC_ERROR,
9406 _("TLS not supported or disabled on this target"));
9411 /* Provide thread local base, i.e. Thread Information Block address.
9412 Returns 1 if ptid is found and thread_local_base is non zero. */
9415 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
9417 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9419 struct remote_state *rs = get_remote_state ();
9421 char *endp = rs->buf + get_remote_packet_size ();
9422 enum packet_result result;
9424 strcpy (p, "qGetTIBAddr:");
9426 p = write_ptid (p, endp, ptid);
9430 getpkt (&rs->buf, &rs->buf_size, 0);
9431 result = packet_ok (rs->buf,
9432 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9433 if (result == PACKET_OK)
9437 unpack_varlen_hex (rs->buf, &result);
9439 *addr = (CORE_ADDR) result;
9442 else if (result == PACKET_UNKNOWN)
9443 error (_("Remote target doesn't support qGetTIBAddr packet"));
9445 error (_("Remote target failed to process qGetTIBAddr request"));
9448 error (_("qGetTIBAddr not supported or disabled on this target"));
9453 /* Support for inferring a target description based on the current
9454 architecture and the size of a 'g' packet. While the 'g' packet
9455 can have any size (since optional registers can be left off the
9456 end), some sizes are easily recognizable given knowledge of the
9457 approximate architecture. */
9459 struct remote_g_packet_guess
9462 const struct target_desc *tdesc;
9464 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9465 DEF_VEC_O(remote_g_packet_guess_s);
9467 struct remote_g_packet_data
9469 VEC(remote_g_packet_guess_s) *guesses;
9472 static struct gdbarch_data *remote_g_packet_data_handle;
9475 remote_g_packet_data_init (struct obstack *obstack)
9477 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9481 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9482 const struct target_desc *tdesc)
9484 struct remote_g_packet_data *data
9485 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9486 struct remote_g_packet_guess new_guess, *guess;
9489 gdb_assert (tdesc != NULL);
9492 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9494 if (guess->bytes == bytes)
9495 internal_error (__FILE__, __LINE__,
9496 _("Duplicate g packet description added for size %d"),
9499 new_guess.bytes = bytes;
9500 new_guess.tdesc = tdesc;
9501 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9504 /* Return 1 if remote_read_description would do anything on this target
9505 and architecture, 0 otherwise. */
9508 remote_read_description_p (struct target_ops *target)
9510 struct remote_g_packet_data *data
9511 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9513 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9519 static const struct target_desc *
9520 remote_read_description (struct target_ops *target)
9522 struct remote_g_packet_data *data
9523 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9525 /* Do not try this during initial connection, when we do not know
9526 whether there is a running but stopped thread. */
9527 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9530 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9532 struct remote_g_packet_guess *guess;
9534 int bytes = send_g_packet ();
9537 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9539 if (guess->bytes == bytes)
9540 return guess->tdesc;
9542 /* We discard the g packet. A minor optimization would be to
9543 hold on to it, and fill the register cache once we have selected
9544 an architecture, but it's too tricky to do safely. */
9550 /* Remote file transfer support. This is host-initiated I/O, not
9551 target-initiated; for target-initiated, see remote-fileio.c. */
9553 /* If *LEFT is at least the length of STRING, copy STRING to
9554 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9555 decrease *LEFT. Otherwise raise an error. */
9558 remote_buffer_add_string (char **buffer, int *left, char *string)
9560 int len = strlen (string);
9563 error (_("Packet too long for target."));
9565 memcpy (*buffer, string, len);
9569 /* NUL-terminate the buffer as a convenience, if there is
9575 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9576 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9577 decrease *LEFT. Otherwise raise an error. */
9580 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9583 if (2 * len > *left)
9584 error (_("Packet too long for target."));
9586 bin2hex (bytes, *buffer, len);
9590 /* NUL-terminate the buffer as a convenience, if there is
9596 /* If *LEFT is large enough, convert VALUE to hex and add it to
9597 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9598 decrease *LEFT. Otherwise raise an error. */
9601 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9603 int len = hexnumlen (value);
9606 error (_("Packet too long for target."));
9608 hexnumstr (*buffer, value);
9612 /* NUL-terminate the buffer as a convenience, if there is
9618 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9619 value, *REMOTE_ERRNO to the remote error number or zero if none
9620 was included, and *ATTACHMENT to point to the start of the annex
9621 if any. The length of the packet isn't needed here; there may
9622 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9624 Return 0 if the packet could be parsed, -1 if it could not. If
9625 -1 is returned, the other variables may not be initialized. */
9628 remote_hostio_parse_result (char *buffer, int *retcode,
9629 int *remote_errno, char **attachment)
9636 if (buffer[0] != 'F')
9640 *retcode = strtol (&buffer[1], &p, 16);
9641 if (errno != 0 || p == &buffer[1])
9644 /* Check for ",errno". */
9648 *remote_errno = strtol (p + 1, &p2, 16);
9649 if (errno != 0 || p + 1 == p2)
9654 /* Check for ";attachment". If there is no attachment, the
9655 packet should end here. */
9658 *attachment = p + 1;
9661 else if (*p == '\0')
9667 /* Send a prepared I/O packet to the target and read its response.
9668 The prepared packet is in the global RS->BUF before this function
9669 is called, and the answer is there when we return.
9671 COMMAND_BYTES is the length of the request to send, which may include
9672 binary data. WHICH_PACKET is the packet configuration to check
9673 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9674 is set to the error number and -1 is returned. Otherwise the value
9675 returned by the function is returned.
9677 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9678 attachment is expected; an error will be reported if there's a
9679 mismatch. If one is found, *ATTACHMENT will be set to point into
9680 the packet buffer and *ATTACHMENT_LEN will be set to the
9681 attachment's length. */
9684 remote_hostio_send_command (int command_bytes, int which_packet,
9685 int *remote_errno, char **attachment,
9686 int *attachment_len)
9688 struct remote_state *rs = get_remote_state ();
9689 int ret, bytes_read;
9690 char *attachment_tmp;
9693 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
9695 *remote_errno = FILEIO_ENOSYS;
9699 putpkt_binary (rs->buf, command_bytes);
9700 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9702 /* If it timed out, something is wrong. Don't try to parse the
9706 *remote_errno = FILEIO_EINVAL;
9710 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9713 *remote_errno = FILEIO_EINVAL;
9715 case PACKET_UNKNOWN:
9716 *remote_errno = FILEIO_ENOSYS;
9722 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9725 *remote_errno = FILEIO_EINVAL;
9729 /* Make sure we saw an attachment if and only if we expected one. */
9730 if ((attachment_tmp == NULL && attachment != NULL)
9731 || (attachment_tmp != NULL && attachment == NULL))
9733 *remote_errno = FILEIO_EINVAL;
9737 /* If an attachment was found, it must point into the packet buffer;
9738 work out how many bytes there were. */
9739 if (attachment_tmp != NULL)
9741 *attachment = attachment_tmp;
9742 *attachment_len = bytes_read - (*attachment - rs->buf);
9748 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9749 remote file descriptor, or -1 if an error occurs (and set
9753 remote_hostio_open (const char *filename, int flags, int mode,
9756 struct remote_state *rs = get_remote_state ();
9758 int left = get_remote_packet_size () - 1;
9760 remote_buffer_add_string (&p, &left, "vFile:open:");
9762 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9764 remote_buffer_add_string (&p, &left, ",");
9766 remote_buffer_add_int (&p, &left, flags);
9767 remote_buffer_add_string (&p, &left, ",");
9769 remote_buffer_add_int (&p, &left, mode);
9771 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9772 remote_errno, NULL, NULL);
9775 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9776 Return the number of bytes written, or -1 if an error occurs (and
9777 set *REMOTE_ERRNO). */
9780 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9781 ULONGEST offset, int *remote_errno)
9783 struct remote_state *rs = get_remote_state ();
9785 int left = get_remote_packet_size ();
9788 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9790 remote_buffer_add_int (&p, &left, fd);
9791 remote_buffer_add_string (&p, &left, ",");
9793 remote_buffer_add_int (&p, &left, offset);
9794 remote_buffer_add_string (&p, &left, ",");
9796 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9797 get_remote_packet_size () - (p - rs->buf));
9799 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9800 remote_errno, NULL, NULL);
9803 /* Read up to LEN bytes FD on the remote target into READ_BUF
9804 Return the number of bytes read, or -1 if an error occurs (and
9805 set *REMOTE_ERRNO). */
9808 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9809 ULONGEST offset, int *remote_errno)
9811 struct remote_state *rs = get_remote_state ();
9814 int left = get_remote_packet_size ();
9815 int ret, attachment_len;
9818 remote_buffer_add_string (&p, &left, "vFile:pread:");
9820 remote_buffer_add_int (&p, &left, fd);
9821 remote_buffer_add_string (&p, &left, ",");
9823 remote_buffer_add_int (&p, &left, len);
9824 remote_buffer_add_string (&p, &left, ",");
9826 remote_buffer_add_int (&p, &left, offset);
9828 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9829 remote_errno, &attachment,
9835 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9837 if (read_len != ret)
9838 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9843 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9844 (and set *REMOTE_ERRNO). */
9847 remote_hostio_close (int fd, int *remote_errno)
9849 struct remote_state *rs = get_remote_state ();
9851 int left = get_remote_packet_size () - 1;
9853 remote_buffer_add_string (&p, &left, "vFile:close:");
9855 remote_buffer_add_int (&p, &left, fd);
9857 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9858 remote_errno, NULL, NULL);
9861 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9862 occurs (and set *REMOTE_ERRNO). */
9865 remote_hostio_unlink (const char *filename, int *remote_errno)
9867 struct remote_state *rs = get_remote_state ();
9869 int left = get_remote_packet_size () - 1;
9871 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9873 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9876 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9877 remote_errno, NULL, NULL);
9880 /* Read value of symbolic link FILENAME on the remote target. Return
9881 a null-terminated string allocated via xmalloc, or NULL if an error
9882 occurs (and set *REMOTE_ERRNO). */
9885 remote_hostio_readlink (const char *filename, int *remote_errno)
9887 struct remote_state *rs = get_remote_state ();
9890 int left = get_remote_packet_size ();
9891 int len, attachment_len;
9895 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9897 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9900 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9901 remote_errno, &attachment,
9907 ret = xmalloc (len + 1);
9909 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9910 (gdb_byte *) ret, len);
9911 if (read_len != len)
9912 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9919 remote_fileio_errno_to_host (int errnum)
9943 case FILEIO_ENOTDIR:
9963 case FILEIO_ENAMETOOLONG:
9964 return ENAMETOOLONG;
9970 remote_hostio_error (int errnum)
9972 int host_error = remote_fileio_errno_to_host (errnum);
9974 if (host_error == -1)
9975 error (_("Unknown remote I/O error %d"), errnum);
9977 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9981 remote_hostio_close_cleanup (void *opaque)
9983 int fd = *(int *) opaque;
9986 remote_hostio_close (fd, &remote_errno);
9991 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9993 const char *filename = bfd_get_filename (abfd);
9994 int fd, remote_errno;
9997 gdb_assert (remote_filename_p (filename));
9999 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10002 errno = remote_fileio_errno_to_host (remote_errno);
10003 bfd_set_error (bfd_error_system_call);
10007 stream = xmalloc (sizeof (int));
10013 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10015 int fd = *(int *)stream;
10020 /* Ignore errors on close; these may happen if the remote
10021 connection was already torn down. */
10022 remote_hostio_close (fd, &remote_errno);
10024 /* Zero means success. */
10029 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10030 file_ptr nbytes, file_ptr offset)
10032 int fd = *(int *)stream;
10034 file_ptr pos, bytes;
10037 while (nbytes > pos)
10039 bytes = remote_hostio_pread (fd, (gdb_byte *) buf + pos, nbytes - pos,
10040 offset + pos, &remote_errno);
10042 /* Success, but no bytes, means end-of-file. */
10046 errno = remote_fileio_errno_to_host (remote_errno);
10047 bfd_set_error (bfd_error_system_call);
10058 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10060 /* FIXME: We should probably implement remote_hostio_stat. */
10061 sb->st_size = INT_MAX;
10066 remote_filename_p (const char *filename)
10068 return strncmp (filename, "remote:", 7) == 0;
10072 remote_bfd_open (const char *remote_file, const char *target)
10074 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10075 remote_bfd_iovec_open, NULL,
10076 remote_bfd_iovec_pread,
10077 remote_bfd_iovec_close,
10078 remote_bfd_iovec_stat);
10084 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10086 struct cleanup *back_to, *close_cleanup;
10087 int retcode, fd, remote_errno, bytes, io_size;
10090 int bytes_in_buffer;
10095 error (_("command can only be used with remote target"));
10097 file = gdb_fopen_cloexec (local_file, "rb");
10099 perror_with_name (local_file);
10100 back_to = make_cleanup_fclose (file);
10102 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10104 0700, &remote_errno);
10106 remote_hostio_error (remote_errno);
10108 /* Send up to this many bytes at once. They won't all fit in the
10109 remote packet limit, so we'll transfer slightly fewer. */
10110 io_size = get_remote_packet_size ();
10111 buffer = xmalloc (io_size);
10112 make_cleanup (xfree, buffer);
10114 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10116 bytes_in_buffer = 0;
10119 while (bytes_in_buffer || !saw_eof)
10123 bytes = fread (buffer + bytes_in_buffer, 1,
10124 io_size - bytes_in_buffer,
10129 error (_("Error reading %s."), local_file);
10132 /* EOF. Unless there is something still in the
10133 buffer from the last iteration, we are done. */
10135 if (bytes_in_buffer == 0)
10143 bytes += bytes_in_buffer;
10144 bytes_in_buffer = 0;
10146 retcode = remote_hostio_pwrite (fd, buffer, bytes,
10147 offset, &remote_errno);
10150 remote_hostio_error (remote_errno);
10151 else if (retcode == 0)
10152 error (_("Remote write of %d bytes returned 0!"), bytes);
10153 else if (retcode < bytes)
10155 /* Short write. Save the rest of the read data for the next
10157 bytes_in_buffer = bytes - retcode;
10158 memmove (buffer, buffer + retcode, bytes_in_buffer);
10164 discard_cleanups (close_cleanup);
10165 if (remote_hostio_close (fd, &remote_errno))
10166 remote_hostio_error (remote_errno);
10169 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10170 do_cleanups (back_to);
10174 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10176 struct cleanup *back_to, *close_cleanup;
10177 int fd, remote_errno, bytes, io_size;
10183 error (_("command can only be used with remote target"));
10185 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10187 remote_hostio_error (remote_errno);
10189 file = gdb_fopen_cloexec (local_file, "wb");
10191 perror_with_name (local_file);
10192 back_to = make_cleanup_fclose (file);
10194 /* Send up to this many bytes at once. They won't all fit in the
10195 remote packet limit, so we'll transfer slightly fewer. */
10196 io_size = get_remote_packet_size ();
10197 buffer = xmalloc (io_size);
10198 make_cleanup (xfree, buffer);
10200 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10205 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
10207 /* Success, but no bytes, means end-of-file. */
10210 remote_hostio_error (remote_errno);
10214 bytes = fwrite (buffer, 1, bytes, file);
10216 perror_with_name (local_file);
10219 discard_cleanups (close_cleanup);
10220 if (remote_hostio_close (fd, &remote_errno))
10221 remote_hostio_error (remote_errno);
10224 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10225 do_cleanups (back_to);
10229 remote_file_delete (const char *remote_file, int from_tty)
10231 int retcode, remote_errno;
10234 error (_("command can only be used with remote target"));
10236 retcode = remote_hostio_unlink (remote_file, &remote_errno);
10238 remote_hostio_error (remote_errno);
10241 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10245 remote_put_command (char *args, int from_tty)
10247 struct cleanup *back_to;
10251 error_no_arg (_("file to put"));
10253 argv = gdb_buildargv (args);
10254 back_to = make_cleanup_freeargv (argv);
10255 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10256 error (_("Invalid parameters to remote put"));
10258 remote_file_put (argv[0], argv[1], from_tty);
10260 do_cleanups (back_to);
10264 remote_get_command (char *args, int from_tty)
10266 struct cleanup *back_to;
10270 error_no_arg (_("file to get"));
10272 argv = gdb_buildargv (args);
10273 back_to = make_cleanup_freeargv (argv);
10274 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10275 error (_("Invalid parameters to remote get"));
10277 remote_file_get (argv[0], argv[1], from_tty);
10279 do_cleanups (back_to);
10283 remote_delete_command (char *args, int from_tty)
10285 struct cleanup *back_to;
10289 error_no_arg (_("file to delete"));
10291 argv = gdb_buildargv (args);
10292 back_to = make_cleanup_freeargv (argv);
10293 if (argv[0] == NULL || argv[1] != NULL)
10294 error (_("Invalid parameters to remote delete"));
10296 remote_file_delete (argv[0], from_tty);
10298 do_cleanups (back_to);
10302 remote_command (char *args, int from_tty)
10304 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10308 remote_can_execute_reverse (void)
10310 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10311 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10318 remote_supports_non_stop (void)
10324 remote_supports_disable_randomization (void)
10326 /* Only supported in extended mode. */
10331 remote_supports_multi_process (void)
10333 struct remote_state *rs = get_remote_state ();
10335 /* Only extended-remote handles being attached to multiple
10336 processes, even though plain remote can use the multi-process
10337 thread id extensions, so that GDB knows the target process's
10339 return rs->extended && remote_multi_process_p (rs);
10343 remote_supports_cond_tracepoints (void)
10345 struct remote_state *rs = get_remote_state ();
10347 return rs->cond_tracepoints;
10351 remote_supports_cond_breakpoints (void)
10353 struct remote_state *rs = get_remote_state ();
10355 return rs->cond_breakpoints;
10359 remote_supports_fast_tracepoints (void)
10361 struct remote_state *rs = get_remote_state ();
10363 return rs->fast_tracepoints;
10367 remote_supports_static_tracepoints (void)
10369 struct remote_state *rs = get_remote_state ();
10371 return rs->static_tracepoints;
10375 remote_supports_install_in_trace (void)
10377 struct remote_state *rs = get_remote_state ();
10379 return rs->install_in_trace;
10383 remote_supports_enable_disable_tracepoint (void)
10385 struct remote_state *rs = get_remote_state ();
10387 return rs->enable_disable_tracepoints;
10391 remote_supports_string_tracing (void)
10393 struct remote_state *rs = get_remote_state ();
10395 return rs->string_tracing;
10399 remote_can_run_breakpoint_commands (void)
10401 struct remote_state *rs = get_remote_state ();
10403 return rs->breakpoint_commands;
10407 remote_trace_init (void)
10410 remote_get_noisy_reply (&target_buf, &target_buf_size);
10411 if (strcmp (target_buf, "OK") != 0)
10412 error (_("Target does not support this command."));
10415 static void free_actions_list (char **actions_list);
10416 static void free_actions_list_cleanup_wrapper (void *);
10418 free_actions_list_cleanup_wrapper (void *al)
10420 free_actions_list (al);
10424 free_actions_list (char **actions_list)
10428 if (actions_list == 0)
10431 for (ndx = 0; actions_list[ndx]; ndx++)
10432 xfree (actions_list[ndx]);
10434 xfree (actions_list);
10437 /* Recursive routine to walk through command list including loops, and
10438 download packets for each command. */
10441 remote_download_command_source (int num, ULONGEST addr,
10442 struct command_line *cmds)
10444 struct remote_state *rs = get_remote_state ();
10445 struct command_line *cmd;
10447 for (cmd = cmds; cmd; cmd = cmd->next)
10449 QUIT; /* Allow user to bail out with ^C. */
10450 strcpy (rs->buf, "QTDPsrc:");
10451 encode_source_string (num, addr, "cmd", cmd->line,
10452 rs->buf + strlen (rs->buf),
10453 rs->buf_size - strlen (rs->buf));
10455 remote_get_noisy_reply (&target_buf, &target_buf_size);
10456 if (strcmp (target_buf, "OK"))
10457 warning (_("Target does not support source download."));
10459 if (cmd->control_type == while_control
10460 || cmd->control_type == while_stepping_control)
10462 remote_download_command_source (num, addr, *cmd->body_list);
10464 QUIT; /* Allow user to bail out with ^C. */
10465 strcpy (rs->buf, "QTDPsrc:");
10466 encode_source_string (num, addr, "cmd", "end",
10467 rs->buf + strlen (rs->buf),
10468 rs->buf_size - strlen (rs->buf));
10470 remote_get_noisy_reply (&target_buf, &target_buf_size);
10471 if (strcmp (target_buf, "OK"))
10472 warning (_("Target does not support source download."));
10478 remote_download_tracepoint (struct bp_location *loc)
10480 #define BUF_SIZE 2048
10484 char buf[BUF_SIZE];
10485 char **tdp_actions;
10486 char **stepping_actions;
10488 struct cleanup *old_chain = NULL;
10489 struct agent_expr *aexpr;
10490 struct cleanup *aexpr_chain = NULL;
10492 struct breakpoint *b = loc->owner;
10493 struct tracepoint *t = (struct tracepoint *) b;
10495 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10496 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10498 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10501 tpaddr = loc->address;
10502 sprintf_vma (addrbuf, tpaddr);
10503 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10504 addrbuf, /* address */
10505 (b->enable_state == bp_enabled ? 'E' : 'D'),
10506 t->step_count, t->pass_count);
10507 /* Fast tracepoints are mostly handled by the target, but we can
10508 tell the target how big of an instruction block should be moved
10510 if (b->type == bp_fast_tracepoint)
10512 /* Only test for support at download time; we may not know
10513 target capabilities at definition time. */
10514 if (remote_supports_fast_tracepoints ())
10518 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10519 tpaddr, &isize, NULL))
10520 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10523 /* If it passed validation at definition but fails now,
10524 something is very wrong. */
10525 internal_error (__FILE__, __LINE__,
10526 _("Fast tracepoint not "
10527 "valid during download"));
10530 /* Fast tracepoints are functionally identical to regular
10531 tracepoints, so don't take lack of support as a reason to
10532 give up on the trace run. */
10533 warning (_("Target does not support fast tracepoints, "
10534 "downloading %d as regular tracepoint"), b->number);
10536 else if (b->type == bp_static_tracepoint)
10538 /* Only test for support at download time; we may not know
10539 target capabilities at definition time. */
10540 if (remote_supports_static_tracepoints ())
10542 struct static_tracepoint_marker marker;
10544 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10545 strcat (buf, ":S");
10547 error (_("Static tracepoint not valid during download"));
10550 /* Fast tracepoints are functionally identical to regular
10551 tracepoints, so don't take lack of support as a reason
10552 to give up on the trace run. */
10553 error (_("Target does not support static tracepoints"));
10555 /* If the tracepoint has a conditional, make it into an agent
10556 expression and append to the definition. */
10559 /* Only test support at download time, we may not know target
10560 capabilities at definition time. */
10561 if (remote_supports_cond_tracepoints ())
10563 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10564 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10565 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10567 pkt = buf + strlen (buf);
10568 for (ndx = 0; ndx < aexpr->len; ++ndx)
10569 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10571 do_cleanups (aexpr_chain);
10574 warning (_("Target does not support conditional tracepoints, "
10575 "ignoring tp %d cond"), b->number);
10578 if (b->commands || *default_collect)
10581 remote_get_noisy_reply (&target_buf, &target_buf_size);
10582 if (strcmp (target_buf, "OK"))
10583 error (_("Target does not support tracepoints."));
10585 /* do_single_steps (t); */
10588 for (ndx = 0; tdp_actions[ndx]; ndx++)
10590 QUIT; /* Allow user to bail out with ^C. */
10591 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10592 b->number, addrbuf, /* address */
10594 ((tdp_actions[ndx + 1] || stepping_actions)
10597 remote_get_noisy_reply (&target_buf,
10599 if (strcmp (target_buf, "OK"))
10600 error (_("Error on target while setting tracepoints."));
10603 if (stepping_actions)
10605 for (ndx = 0; stepping_actions[ndx]; ndx++)
10607 QUIT; /* Allow user to bail out with ^C. */
10608 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10609 b->number, addrbuf, /* address */
10610 ((ndx == 0) ? "S" : ""),
10611 stepping_actions[ndx],
10612 (stepping_actions[ndx + 1] ? "-" : ""));
10614 remote_get_noisy_reply (&target_buf,
10616 if (strcmp (target_buf, "OK"))
10617 error (_("Error on target while setting tracepoints."));
10621 if (remote_protocol_packets[PACKET_TracepointSource].support
10624 if (b->addr_string)
10626 strcpy (buf, "QTDPsrc:");
10627 encode_source_string (b->number, loc->address,
10628 "at", b->addr_string, buf + strlen (buf),
10629 2048 - strlen (buf));
10632 remote_get_noisy_reply (&target_buf, &target_buf_size);
10633 if (strcmp (target_buf, "OK"))
10634 warning (_("Target does not support source download."));
10636 if (b->cond_string)
10638 strcpy (buf, "QTDPsrc:");
10639 encode_source_string (b->number, loc->address,
10640 "cond", b->cond_string, buf + strlen (buf),
10641 2048 - strlen (buf));
10643 remote_get_noisy_reply (&target_buf, &target_buf_size);
10644 if (strcmp (target_buf, "OK"))
10645 warning (_("Target does not support source download."));
10647 remote_download_command_source (b->number, loc->address,
10648 breakpoint_commands (b));
10651 do_cleanups (old_chain);
10655 remote_can_download_tracepoint (void)
10657 struct remote_state *rs = get_remote_state ();
10658 struct trace_status *ts;
10661 /* Don't try to install tracepoints until we've relocated our
10662 symbols, and fetched and merged the target's tracepoint list with
10664 if (rs->starting_up)
10667 ts = current_trace_status ();
10668 status = remote_get_trace_status (ts);
10670 if (status == -1 || !ts->running_known || !ts->running)
10673 /* If we are in a tracing experiment, but remote stub doesn't support
10674 installing tracepoint in trace, we have to return. */
10675 if (!remote_supports_install_in_trace ())
10683 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10685 struct remote_state *rs = get_remote_state ();
10688 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10689 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10691 p = rs->buf + strlen (rs->buf);
10692 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10693 error (_("Trace state variable name too long for tsv definition packet"));
10694 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10697 remote_get_noisy_reply (&target_buf, &target_buf_size);
10698 if (*target_buf == '\0')
10699 error (_("Target does not support this command."));
10700 if (strcmp (target_buf, "OK") != 0)
10701 error (_("Error on target while downloading trace state variable."));
10705 remote_enable_tracepoint (struct bp_location *location)
10707 struct remote_state *rs = get_remote_state ();
10710 sprintf_vma (addr_buf, location->address);
10711 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10712 location->owner->number, addr_buf);
10714 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10715 if (*rs->buf == '\0')
10716 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10717 if (strcmp (rs->buf, "OK") != 0)
10718 error (_("Error on target while enabling tracepoint."));
10722 remote_disable_tracepoint (struct bp_location *location)
10724 struct remote_state *rs = get_remote_state ();
10727 sprintf_vma (addr_buf, location->address);
10728 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10729 location->owner->number, addr_buf);
10731 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10732 if (*rs->buf == '\0')
10733 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10734 if (strcmp (rs->buf, "OK") != 0)
10735 error (_("Error on target while disabling tracepoint."));
10739 remote_trace_set_readonly_regions (void)
10743 bfd_size_type size;
10749 return; /* No information to give. */
10751 strcpy (target_buf, "QTro");
10752 offset = strlen (target_buf);
10753 for (s = exec_bfd->sections; s; s = s->next)
10755 char tmp1[40], tmp2[40];
10758 if ((s->flags & SEC_LOAD) == 0 ||
10759 /* (s->flags & SEC_CODE) == 0 || */
10760 (s->flags & SEC_READONLY) == 0)
10764 vma = bfd_get_section_vma (abfd, s);
10765 size = bfd_get_section_size (s);
10766 sprintf_vma (tmp1, vma);
10767 sprintf_vma (tmp2, vma + size);
10768 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10769 if (offset + sec_length + 1 > target_buf_size)
10771 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10774 Too many sections for read-only sections definition packet."));
10777 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10779 offset += sec_length;
10783 putpkt (target_buf);
10784 getpkt (&target_buf, &target_buf_size, 0);
10789 remote_trace_start (void)
10791 putpkt ("QTStart");
10792 remote_get_noisy_reply (&target_buf, &target_buf_size);
10793 if (*target_buf == '\0')
10794 error (_("Target does not support this command."));
10795 if (strcmp (target_buf, "OK") != 0)
10796 error (_("Bogus reply from target: %s"), target_buf);
10800 remote_get_trace_status (struct trace_status *ts)
10802 /* Initialize it just to avoid a GCC false warning. */
10804 /* FIXME we need to get register block size some other way. */
10805 extern int trace_regblock_size;
10806 volatile struct gdb_exception ex;
10807 enum packet_result result;
10809 if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
10812 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10814 putpkt ("qTStatus");
10816 TRY_CATCH (ex, RETURN_MASK_ERROR)
10818 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10822 if (ex.error != TARGET_CLOSE_ERROR)
10824 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10827 throw_exception (ex);
10830 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10832 /* If the remote target doesn't do tracing, flag it. */
10833 if (result == PACKET_UNKNOWN)
10836 /* We're working with a live target. */
10837 ts->filename = NULL;
10840 error (_("Bogus trace status reply from target: %s"), target_buf);
10842 /* Function 'parse_trace_status' sets default value of each field of
10843 'ts' at first, so we don't have to do it here. */
10844 parse_trace_status (p, ts);
10846 return ts->running;
10850 remote_get_tracepoint_status (struct breakpoint *bp,
10851 struct uploaded_tp *utp)
10853 struct remote_state *rs = get_remote_state ();
10855 struct bp_location *loc;
10856 struct tracepoint *tp = (struct tracepoint *) bp;
10857 size_t size = get_remote_packet_size ();
10861 tp->base.hit_count = 0;
10862 tp->traceframe_usage = 0;
10863 for (loc = tp->base.loc; loc; loc = loc->next)
10865 /* If the tracepoint was never downloaded, don't go asking for
10867 if (tp->number_on_target == 0)
10869 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10870 phex_nz (loc->address, 0));
10872 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10873 if (reply && *reply)
10876 parse_tracepoint_status (reply + 1, bp, utp);
10882 utp->hit_count = 0;
10883 utp->traceframe_usage = 0;
10884 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10885 phex_nz (utp->addr, 0));
10887 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10888 if (reply && *reply)
10891 parse_tracepoint_status (reply + 1, bp, utp);
10897 remote_trace_stop (void)
10900 remote_get_noisy_reply (&target_buf, &target_buf_size);
10901 if (*target_buf == '\0')
10902 error (_("Target does not support this command."));
10903 if (strcmp (target_buf, "OK") != 0)
10904 error (_("Bogus reply from target: %s"), target_buf);
10908 remote_trace_find (enum trace_find_type type, int num,
10909 CORE_ADDR addr1, CORE_ADDR addr2,
10912 struct remote_state *rs = get_remote_state ();
10913 char *endbuf = rs->buf + get_remote_packet_size ();
10915 int target_frameno = -1, target_tracept = -1;
10917 /* Lookups other than by absolute frame number depend on the current
10918 trace selected, so make sure it is correct on the remote end
10920 if (type != tfind_number)
10921 set_remote_traceframe ();
10924 strcpy (p, "QTFrame:");
10925 p = strchr (p, '\0');
10929 xsnprintf (p, endbuf - p, "%x", num);
10932 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
10935 xsnprintf (p, endbuf - p, "tdp:%x", num);
10938 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10939 phex_nz (addr2, 0));
10941 case tfind_outside:
10942 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10943 phex_nz (addr2, 0));
10946 error (_("Unknown trace find type %d"), type);
10950 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
10951 if (*reply == '\0')
10952 error (_("Target does not support this command."));
10954 while (reply && *reply)
10959 target_frameno = (int) strtol (p, &reply, 16);
10961 error (_("Unable to parse trace frame number"));
10962 /* Don't update our remote traceframe number cache on failure
10963 to select a remote traceframe. */
10964 if (target_frameno == -1)
10969 target_tracept = (int) strtol (p, &reply, 16);
10971 error (_("Unable to parse tracepoint number"));
10973 case 'O': /* "OK"? */
10974 if (reply[1] == 'K' && reply[2] == '\0')
10977 error (_("Bogus reply from target: %s"), reply);
10980 error (_("Bogus reply from target: %s"), reply);
10983 *tpp = target_tracept;
10985 remote_traceframe_number = target_frameno;
10986 return target_frameno;
10990 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
10992 struct remote_state *rs = get_remote_state ();
10996 set_remote_traceframe ();
10998 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11000 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11001 if (reply && *reply)
11005 unpack_varlen_hex (reply + 1, &uval);
11006 *val = (LONGEST) uval;
11014 remote_save_trace_data (const char *filename)
11016 struct remote_state *rs = get_remote_state ();
11020 strcpy (p, "QTSave:");
11022 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11023 error (_("Remote file name too long for trace save packet"));
11024 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
11027 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11028 if (*reply == '\0')
11029 error (_("Target does not support this command."));
11030 if (strcmp (reply, "OK") != 0)
11031 error (_("Bogus reply from target: %s"), reply);
11035 /* This is basically a memory transfer, but needs to be its own packet
11036 because we don't know how the target actually organizes its trace
11037 memory, plus we want to be able to ask for as much as possible, but
11038 not be unhappy if we don't get as much as we ask for. */
11041 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
11043 struct remote_state *rs = get_remote_state ();
11049 strcpy (p, "qTBuffer:");
11051 p += hexnumstr (p, offset);
11053 p += hexnumstr (p, len);
11057 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11058 if (reply && *reply)
11060 /* 'l' by itself means we're at the end of the buffer and
11061 there is nothing more to get. */
11065 /* Convert the reply into binary. Limit the number of bytes to
11066 convert according to our passed-in buffer size, rather than
11067 what was returned in the packet; if the target is
11068 unexpectedly generous and gives us a bigger reply than we
11069 asked for, we don't want to crash. */
11070 rslt = hex2bin (target_buf, buf, len);
11074 /* Something went wrong, flag as an error. */
11079 remote_set_disconnected_tracing (int val)
11081 struct remote_state *rs = get_remote_state ();
11083 if (rs->disconnected_tracing)
11087 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11089 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11090 if (*reply == '\0')
11091 error (_("Target does not support this command."));
11092 if (strcmp (reply, "OK") != 0)
11093 error (_("Bogus reply from target: %s"), reply);
11096 warning (_("Target does not support disconnected tracing."));
11100 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11102 struct thread_info *info = find_thread_ptid (ptid);
11104 if (info && info->private)
11105 return info->private->core;
11110 remote_set_circular_trace_buffer (int val)
11112 struct remote_state *rs = get_remote_state ();
11115 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11117 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11118 if (*reply == '\0')
11119 error (_("Target does not support this command."));
11120 if (strcmp (reply, "OK") != 0)
11121 error (_("Bogus reply from target: %s"), reply);
11124 static struct traceframe_info *
11125 remote_traceframe_info (void)
11129 text = target_read_stralloc (¤t_target,
11130 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11133 struct traceframe_info *info;
11134 struct cleanup *back_to = make_cleanup (xfree, text);
11136 info = parse_traceframe_info (text);
11137 do_cleanups (back_to);
11144 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11145 instruction on which a fast tracepoint may be placed. Returns -1
11146 if the packet is not supported, and 0 if the minimum instruction
11147 length is unknown. */
11150 remote_get_min_fast_tracepoint_insn_len (void)
11152 struct remote_state *rs = get_remote_state ();
11155 /* If we're not debugging a process yet, the IPA can't be
11157 if (!target_has_execution)
11160 /* Make sure the remote is pointing at the right process. */
11161 set_general_process ();
11163 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11165 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11166 if (*reply == '\0')
11170 ULONGEST min_insn_len;
11172 unpack_varlen_hex (reply, &min_insn_len);
11174 return (int) min_insn_len;
11179 remote_set_trace_buffer_size (LONGEST val)
11181 if (remote_protocol_packets[PACKET_QTBuffer_size].support
11184 struct remote_state *rs = get_remote_state ();
11185 char *buf = rs->buf;
11186 char *endbuf = rs->buf + get_remote_packet_size ();
11187 enum packet_result result;
11189 gdb_assert (val >= 0 || val == -1);
11190 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11191 /* Send -1 as literal "-1" to avoid host size dependency. */
11195 buf += hexnumstr (buf, (ULONGEST) -val);
11198 buf += hexnumstr (buf, (ULONGEST) val);
11201 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11202 result = packet_ok (rs->buf,
11203 &remote_protocol_packets[PACKET_QTBuffer_size]);
11205 if (result != PACKET_OK)
11206 warning (_("Bogus reply from target: %s"), rs->buf);
11211 remote_set_trace_notes (const char *user, const char *notes,
11212 const char *stop_notes)
11214 struct remote_state *rs = get_remote_state ();
11216 char *buf = rs->buf;
11217 char *endbuf = rs->buf + get_remote_packet_size ();
11220 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11223 buf += xsnprintf (buf, endbuf - buf, "user:");
11224 nbytes = bin2hex ((gdb_byte *) user, buf, 0);
11230 buf += xsnprintf (buf, endbuf - buf, "notes:");
11231 nbytes = bin2hex ((gdb_byte *) notes, buf, 0);
11237 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11238 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, 0);
11242 /* Ensure the buffer is terminated. */
11246 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11247 if (*reply == '\0')
11250 if (strcmp (reply, "OK") != 0)
11251 error (_("Bogus reply from target: %s"), reply);
11257 remote_use_agent (int use)
11259 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11261 struct remote_state *rs = get_remote_state ();
11263 /* If the stub supports QAgent. */
11264 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11266 getpkt (&rs->buf, &rs->buf_size, 0);
11268 if (strcmp (rs->buf, "OK") == 0)
11279 remote_can_use_agent (void)
11281 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11284 struct btrace_target_info
11286 /* The ptid of the traced thread. */
11290 /* Check whether the target supports branch tracing. */
11293 remote_supports_btrace (void)
11295 if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11297 if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11299 if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11305 /* Enable branch tracing. */
11307 static struct btrace_target_info *
11308 remote_enable_btrace (ptid_t ptid)
11310 struct btrace_target_info *tinfo = NULL;
11311 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11312 struct remote_state *rs = get_remote_state ();
11313 char *buf = rs->buf;
11314 char *endbuf = rs->buf + get_remote_packet_size ();
11316 if (packet->support != PACKET_ENABLE)
11317 error (_("Target does not support branch tracing."));
11319 set_general_thread (ptid);
11321 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11323 getpkt (&rs->buf, &rs->buf_size, 0);
11325 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11327 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11328 error (_("Could not enable branch tracing for %s: %s"),
11329 target_pid_to_str (ptid), rs->buf + 2);
11331 error (_("Could not enable branch tracing for %s."),
11332 target_pid_to_str (ptid));
11335 tinfo = xzalloc (sizeof (*tinfo));
11336 tinfo->ptid = ptid;
11341 /* Disable branch tracing. */
11344 remote_disable_btrace (struct btrace_target_info *tinfo)
11346 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
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 (tinfo->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 disable branch tracing for %s: %s"),
11364 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11366 error (_("Could not disable branch tracing for %s."),
11367 target_pid_to_str (tinfo->ptid));
11373 /* Teardown branch tracing. */
11376 remote_teardown_btrace (struct btrace_target_info *tinfo)
11378 /* We must not talk to the target during teardown. */
11382 /* Read the branch trace. */
11384 static VEC (btrace_block_s) *
11385 remote_read_btrace (struct btrace_target_info *tinfo,
11386 enum btrace_read_type type)
11388 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11389 struct remote_state *rs = get_remote_state ();
11390 VEC (btrace_block_s) *btrace = NULL;
11394 if (packet->support != PACKET_ENABLE)
11395 error (_("Target does not support branch tracing."));
11397 #if !defined(HAVE_LIBEXPAT)
11398 error (_("Cannot process branch tracing result. XML parsing not supported."));
11403 case btrace_read_all:
11406 case btrace_read_new:
11410 internal_error (__FILE__, __LINE__,
11411 _("Bad branch tracing read type: %u."),
11412 (unsigned int) type);
11415 xml = target_read_stralloc (¤t_target,
11416 TARGET_OBJECT_BTRACE, annex);
11419 struct cleanup *cleanup = make_cleanup (xfree, xml);
11421 btrace = parse_xml_btrace (xml);
11422 do_cleanups (cleanup);
11429 remote_augmented_libraries_svr4_read (void)
11431 struct remote_state *rs = get_remote_state ();
11433 return rs->augmented_libraries_svr4_read;
11437 init_remote_ops (void)
11439 remote_ops.to_shortname = "remote";
11440 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11441 remote_ops.to_doc =
11442 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11443 Specify the serial device it is connected to\n\
11444 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11445 remote_ops.to_open = remote_open;
11446 remote_ops.to_close = remote_close;
11447 remote_ops.to_detach = remote_detach;
11448 remote_ops.to_disconnect = remote_disconnect;
11449 remote_ops.to_resume = remote_resume;
11450 remote_ops.to_wait = remote_wait;
11451 remote_ops.to_fetch_registers = remote_fetch_registers;
11452 remote_ops.to_store_registers = remote_store_registers;
11453 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11454 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
11455 remote_ops.to_files_info = remote_files_info;
11456 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11457 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11458 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11459 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11460 remote_ops.to_watchpoint_addr_within_range =
11461 remote_watchpoint_addr_within_range;
11462 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11463 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11464 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11465 remote_ops.to_region_ok_for_hw_watchpoint
11466 = remote_region_ok_for_hw_watchpoint;
11467 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11468 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11469 remote_ops.to_kill = remote_kill;
11470 remote_ops.to_load = generic_load;
11471 remote_ops.to_mourn_inferior = remote_mourn;
11472 remote_ops.to_pass_signals = remote_pass_signals;
11473 remote_ops.to_program_signals = remote_program_signals;
11474 remote_ops.to_thread_alive = remote_thread_alive;
11475 remote_ops.to_find_new_threads = remote_threads_info;
11476 remote_ops.to_pid_to_str = remote_pid_to_str;
11477 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11478 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11479 remote_ops.to_stop = remote_stop;
11480 remote_ops.to_xfer_partial = remote_xfer_partial;
11481 remote_ops.to_rcmd = remote_rcmd;
11482 remote_ops.to_log_command = serial_log_command;
11483 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11484 remote_ops.to_stratum = process_stratum;
11485 remote_ops.to_has_all_memory = default_child_has_all_memory;
11486 remote_ops.to_has_memory = default_child_has_memory;
11487 remote_ops.to_has_stack = default_child_has_stack;
11488 remote_ops.to_has_registers = default_child_has_registers;
11489 remote_ops.to_has_execution = default_child_has_execution;
11490 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11491 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11492 remote_ops.to_magic = OPS_MAGIC;
11493 remote_ops.to_memory_map = remote_memory_map;
11494 remote_ops.to_flash_erase = remote_flash_erase;
11495 remote_ops.to_flash_done = remote_flash_done;
11496 remote_ops.to_read_description = remote_read_description;
11497 remote_ops.to_search_memory = remote_search_memory;
11498 remote_ops.to_can_async_p = remote_can_async_p;
11499 remote_ops.to_is_async_p = remote_is_async_p;
11500 remote_ops.to_async = remote_async;
11501 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11502 remote_ops.to_terminal_ours = remote_terminal_ours;
11503 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11504 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11505 remote_ops.to_supports_disable_randomization
11506 = remote_supports_disable_randomization;
11507 remote_ops.to_fileio_open = remote_hostio_open;
11508 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11509 remote_ops.to_fileio_pread = remote_hostio_pread;
11510 remote_ops.to_fileio_close = remote_hostio_close;
11511 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11512 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11513 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11514 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11515 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11516 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11517 remote_ops.to_trace_init = remote_trace_init;
11518 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11519 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11520 remote_ops.to_download_trace_state_variable
11521 = remote_download_trace_state_variable;
11522 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11523 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11524 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11525 remote_ops.to_trace_start = remote_trace_start;
11526 remote_ops.to_get_trace_status = remote_get_trace_status;
11527 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11528 remote_ops.to_trace_stop = remote_trace_stop;
11529 remote_ops.to_trace_find = remote_trace_find;
11530 remote_ops.to_get_trace_state_variable_value
11531 = remote_get_trace_state_variable_value;
11532 remote_ops.to_save_trace_data = remote_save_trace_data;
11533 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11534 remote_ops.to_upload_trace_state_variables
11535 = remote_upload_trace_state_variables;
11536 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11537 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11538 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11539 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11540 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11541 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11542 remote_ops.to_core_of_thread = remote_core_of_thread;
11543 remote_ops.to_verify_memory = remote_verify_memory;
11544 remote_ops.to_get_tib_address = remote_get_tib_address;
11545 remote_ops.to_set_permissions = remote_set_permissions;
11546 remote_ops.to_static_tracepoint_marker_at
11547 = remote_static_tracepoint_marker_at;
11548 remote_ops.to_static_tracepoint_markers_by_strid
11549 = remote_static_tracepoint_markers_by_strid;
11550 remote_ops.to_traceframe_info = remote_traceframe_info;
11551 remote_ops.to_use_agent = remote_use_agent;
11552 remote_ops.to_can_use_agent = remote_can_use_agent;
11553 remote_ops.to_supports_btrace = remote_supports_btrace;
11554 remote_ops.to_enable_btrace = remote_enable_btrace;
11555 remote_ops.to_disable_btrace = remote_disable_btrace;
11556 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11557 remote_ops.to_read_btrace = remote_read_btrace;
11558 remote_ops.to_augmented_libraries_svr4_read =
11559 remote_augmented_libraries_svr4_read;
11562 /* Set up the extended remote vector by making a copy of the standard
11563 remote vector and adding to it. */
11566 init_extended_remote_ops (void)
11568 extended_remote_ops = remote_ops;
11570 extended_remote_ops.to_shortname = "extended-remote";
11571 extended_remote_ops.to_longname =
11572 "Extended remote serial target in gdb-specific protocol";
11573 extended_remote_ops.to_doc =
11574 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11575 Specify the serial device it is connected to (e.g. /dev/ttya).";
11576 extended_remote_ops.to_open = extended_remote_open;
11577 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11578 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11579 extended_remote_ops.to_detach = extended_remote_detach;
11580 extended_remote_ops.to_attach = extended_remote_attach;
11581 extended_remote_ops.to_kill = extended_remote_kill;
11582 extended_remote_ops.to_supports_disable_randomization
11583 = extended_remote_supports_disable_randomization;
11587 remote_can_async_p (void)
11589 if (!target_async_permitted)
11590 /* We only enable async when the user specifically asks for it. */
11593 /* We're async whenever the serial device is. */
11594 return serial_can_async_p (remote_desc);
11598 remote_is_async_p (void)
11600 if (!target_async_permitted)
11601 /* We only enable async when the user specifically asks for it. */
11604 /* We're async whenever the serial device is. */
11605 return serial_is_async_p (remote_desc);
11608 /* Pass the SERIAL event on and up to the client. One day this code
11609 will be able to delay notifying the client of an event until the
11610 point where an entire packet has been received. */
11612 static void (*async_client_callback) (enum inferior_event_type event_type,
11614 static void *async_client_context;
11615 static serial_event_ftype remote_async_serial_handler;
11618 remote_async_serial_handler (struct serial *scb, void *context)
11620 /* Don't propogate error information up to the client. Instead let
11621 the client find out about the error by querying the target. */
11622 async_client_callback (INF_REG_EVENT, async_client_context);
11626 remote_async_inferior_event_handler (gdb_client_data data)
11628 inferior_event_handler (INF_REG_EVENT, NULL);
11632 remote_async (void (*callback) (enum inferior_event_type event_type,
11633 void *context), void *context)
11635 if (callback != NULL)
11637 serial_async (remote_desc, remote_async_serial_handler, NULL);
11638 async_client_callback = callback;
11639 async_client_context = context;
11642 serial_async (remote_desc, NULL, NULL);
11646 set_remote_cmd (char *args, int from_tty)
11648 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
11652 show_remote_cmd (char *args, int from_tty)
11654 /* We can't just use cmd_show_list here, because we want to skip
11655 the redundant "show remote Z-packet" and the legacy aliases. */
11656 struct cleanup *showlist_chain;
11657 struct cmd_list_element *list = remote_show_cmdlist;
11658 struct ui_out *uiout = current_uiout;
11660 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11661 for (; list != NULL; list = list->next)
11662 if (strcmp (list->name, "Z-packet") == 0)
11664 else if (list->type == not_set_cmd)
11665 /* Alias commands are exactly like the original, except they
11666 don't have the normal type. */
11670 struct cleanup *option_chain
11671 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11673 ui_out_field_string (uiout, "name", list->name);
11674 ui_out_text (uiout, ": ");
11675 if (list->type == show_cmd)
11676 do_show_command ((char *) NULL, from_tty, list);
11678 cmd_func (list, NULL, from_tty);
11679 /* Close the tuple. */
11680 do_cleanups (option_chain);
11683 /* Close the tuple. */
11684 do_cleanups (showlist_chain);
11688 /* Function to be called whenever a new objfile (shlib) is detected. */
11690 remote_new_objfile (struct objfile *objfile)
11692 if (remote_desc != 0) /* Have a remote connection. */
11693 remote_check_symbols ();
11696 /* Pull all the tracepoints defined on the target and create local
11697 data structures representing them. We don't want to create real
11698 tracepoints yet, we don't want to mess up the user's existing
11702 remote_upload_tracepoints (struct uploaded_tp **utpp)
11704 struct remote_state *rs = get_remote_state ();
11707 /* Ask for a first packet of tracepoint definition. */
11709 getpkt (&rs->buf, &rs->buf_size, 0);
11711 while (*p && *p != 'l')
11713 parse_tracepoint_definition (p, utpp);
11714 /* Ask for another packet of tracepoint definition. */
11716 getpkt (&rs->buf, &rs->buf_size, 0);
11723 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
11725 struct remote_state *rs = get_remote_state ();
11728 /* Ask for a first packet of variable definition. */
11730 getpkt (&rs->buf, &rs->buf_size, 0);
11732 while (*p && *p != 'l')
11734 parse_tsv_definition (p, utsvp);
11735 /* Ask for another packet of variable definition. */
11737 getpkt (&rs->buf, &rs->buf_size, 0);
11743 /* The "set/show range-stepping" show hook. */
11746 show_range_stepping (struct ui_file *file, int from_tty,
11747 struct cmd_list_element *c,
11750 fprintf_filtered (file,
11751 _("Debugger's willingness to use range stepping "
11752 "is %s.\n"), value);
11755 /* The "set/show range-stepping" set hook. */
11758 set_range_stepping (char *ignore_args, int from_tty,
11759 struct cmd_list_element *c)
11761 /* Whene enabling, check whether range stepping is actually
11762 supported by the target, and warn if not. */
11763 if (use_range_stepping)
11765 if (remote_desc != NULL)
11767 struct remote_state *rs = get_remote_state ();
11769 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
11770 remote_vcont_probe (rs);
11772 if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
11773 && rs->supports_vCont.r)
11777 warning (_("Range stepping is not supported by the current target"));
11782 _initialize_remote (void)
11784 struct remote_state *rs;
11785 struct cmd_list_element *cmd;
11786 const char *cmd_name;
11788 /* architecture specific data */
11789 remote_gdbarch_data_handle =
11790 gdbarch_data_register_post_init (init_remote_state);
11791 remote_g_packet_data_handle =
11792 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11794 /* Initialize the per-target state. At the moment there is only one
11795 of these, not one per target. Only one target is active at a
11796 time. The default buffer size is unimportant; it will be expanded
11797 whenever a larger buffer is needed. */
11798 rs = get_remote_state_raw ();
11799 rs->buf_size = 400;
11800 rs->buf = xmalloc (rs->buf_size);
11802 init_remote_ops ();
11803 add_target (&remote_ops);
11805 init_extended_remote_ops ();
11806 add_target (&extended_remote_ops);
11808 /* Hook into new objfile notification. */
11809 observer_attach_new_objfile (remote_new_objfile);
11810 /* We're no longer interested in notification events of an inferior
11812 observer_attach_inferior_exit (discard_pending_stop_replies);
11814 /* Set up signal handlers. */
11815 async_sigint_remote_token =
11816 create_async_signal_handler (async_remote_interrupt, NULL);
11817 async_sigint_remote_twice_token =
11818 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11821 init_remote_threadtests ();
11824 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11825 /* set/show remote ... */
11827 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11828 Remote protocol specific variables\n\
11829 Configure various remote-protocol specific variables such as\n\
11830 the packets being used"),
11831 &remote_set_cmdlist, "set remote ",
11832 0 /* allow-unknown */, &setlist);
11833 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11834 Remote protocol specific variables\n\
11835 Configure various remote-protocol specific variables such as\n\
11836 the packets being used"),
11837 &remote_show_cmdlist, "show remote ",
11838 0 /* allow-unknown */, &showlist);
11840 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11841 Compare section data on target to the exec file.\n\
11842 Argument is a single section name (default: all loaded sections)."),
11845 add_cmd ("packet", class_maintenance, packet_command, _("\
11846 Send an arbitrary packet to a remote target.\n\
11847 maintenance packet TEXT\n\
11848 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11849 this command sends the string TEXT to the inferior, and displays the\n\
11850 response packet. GDB supplies the initial `$' character, and the\n\
11851 terminating `#' character and checksum."),
11854 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11855 Set whether to send break if interrupted."), _("\
11856 Show whether to send break if interrupted."), _("\
11857 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11858 set_remotebreak, show_remotebreak,
11859 &setlist, &showlist);
11860 cmd_name = "remotebreak";
11861 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11862 deprecate_cmd (cmd, "set remote interrupt-sequence");
11863 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11864 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11865 deprecate_cmd (cmd, "show remote interrupt-sequence");
11867 add_setshow_enum_cmd ("interrupt-sequence", class_support,
11868 interrupt_sequence_modes, &interrupt_sequence_mode,
11870 Set interrupt sequence to remote target."), _("\
11871 Show interrupt sequence to remote target."), _("\
11872 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11873 NULL, show_interrupt_sequence,
11874 &remote_set_cmdlist,
11875 &remote_show_cmdlist);
11877 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11878 &interrupt_on_connect, _("\
11879 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11880 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11881 If set, interrupt sequence is sent to remote target."),
11883 &remote_set_cmdlist, &remote_show_cmdlist);
11885 /* Install commands for configuring memory read/write packets. */
11887 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11888 Set the maximum number of bytes per memory write packet (deprecated)."),
11890 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11891 Show the maximum number of bytes per memory write packet (deprecated)."),
11893 add_cmd ("memory-write-packet-size", no_class,
11894 set_memory_write_packet_size, _("\
11895 Set the maximum number of bytes per memory-write packet.\n\
11896 Specify the number of bytes in a packet or 0 (zero) for the\n\
11897 default packet size. The actual limit is further reduced\n\
11898 dependent on the target. Specify ``fixed'' to disable the\n\
11899 further restriction and ``limit'' to enable that restriction."),
11900 &remote_set_cmdlist);
11901 add_cmd ("memory-read-packet-size", no_class,
11902 set_memory_read_packet_size, _("\
11903 Set the maximum number of bytes per memory-read packet.\n\
11904 Specify the number of bytes in a packet or 0 (zero) for the\n\
11905 default packet size. The actual limit is further reduced\n\
11906 dependent on the target. Specify ``fixed'' to disable the\n\
11907 further restriction and ``limit'' to enable that restriction."),
11908 &remote_set_cmdlist);
11909 add_cmd ("memory-write-packet-size", no_class,
11910 show_memory_write_packet_size,
11911 _("Show the maximum number of bytes per memory-write packet."),
11912 &remote_show_cmdlist);
11913 add_cmd ("memory-read-packet-size", no_class,
11914 show_memory_read_packet_size,
11915 _("Show the maximum number of bytes per memory-read packet."),
11916 &remote_show_cmdlist);
11918 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11919 &remote_hw_watchpoint_limit, _("\
11920 Set the maximum number of target hardware watchpoints."), _("\
11921 Show the maximum number of target hardware watchpoints."), _("\
11922 Specify a negative limit for unlimited."),
11923 NULL, NULL, /* FIXME: i18n: The maximum
11924 number of target hardware
11925 watchpoints is %s. */
11926 &remote_set_cmdlist, &remote_show_cmdlist);
11927 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11928 &remote_hw_watchpoint_length_limit, _("\
11929 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11930 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11931 Specify a negative limit for unlimited."),
11932 NULL, NULL, /* FIXME: i18n: The maximum
11933 length (in bytes) of a target
11934 hardware watchpoint is %s. */
11935 &remote_set_cmdlist, &remote_show_cmdlist);
11936 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11937 &remote_hw_breakpoint_limit, _("\
11938 Set the maximum number of target hardware breakpoints."), _("\
11939 Show the maximum number of target hardware breakpoints."), _("\
11940 Specify a negative limit for unlimited."),
11941 NULL, NULL, /* FIXME: i18n: The maximum
11942 number of target hardware
11943 breakpoints is %s. */
11944 &remote_set_cmdlist, &remote_show_cmdlist);
11946 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
11947 &remote_address_size, _("\
11948 Set the maximum size of the address (in bits) in a memory packet."), _("\
11949 Show the maximum size of the address (in bits) in a memory packet."), NULL,
11951 NULL, /* FIXME: i18n: */
11952 &setlist, &showlist);
11954 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
11955 "X", "binary-download", 1);
11957 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
11958 "vCont", "verbose-resume", 0);
11960 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11961 "QPassSignals", "pass-signals", 0);
11963 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
11964 "QProgramSignals", "program-signals", 0);
11966 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
11967 "qSymbol", "symbol-lookup", 0);
11969 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
11970 "P", "set-register", 1);
11972 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
11973 "p", "fetch-register", 1);
11975 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
11976 "Z0", "software-breakpoint", 0);
11978 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
11979 "Z1", "hardware-breakpoint", 0);
11981 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
11982 "Z2", "write-watchpoint", 0);
11984 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
11985 "Z3", "read-watchpoint", 0);
11987 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
11988 "Z4", "access-watchpoint", 0);
11990 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11991 "qXfer:auxv:read", "read-aux-vector", 0);
11993 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11994 "qXfer:features:read", "target-features", 0);
11996 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
11997 "qXfer:libraries:read", "library-info", 0);
11999 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12000 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12002 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12003 "qXfer:memory-map:read", "memory-map", 0);
12005 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12006 "qXfer:spu:read", "read-spu-object", 0);
12008 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12009 "qXfer:spu:write", "write-spu-object", 0);
12011 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12012 "qXfer:osdata:read", "osdata", 0);
12014 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12015 "qXfer:threads:read", "threads", 0);
12017 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12018 "qXfer:siginfo:read", "read-siginfo-object", 0);
12020 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12021 "qXfer:siginfo:write", "write-siginfo-object", 0);
12023 add_packet_config_cmd
12024 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12025 "qXfer:traceframe-info:read", "traceframe-info", 0);
12027 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12028 "qXfer:uib:read", "unwind-info-block", 0);
12030 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12031 "qGetTLSAddr", "get-thread-local-storage-address",
12034 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12035 "qGetTIBAddr", "get-thread-information-block-address",
12038 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12039 "bc", "reverse-continue", 0);
12041 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12042 "bs", "reverse-step", 0);
12044 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12045 "qSupported", "supported-packets", 0);
12047 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12048 "qSearch:memory", "search-memory", 0);
12050 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12051 "qTStatus", "trace-status", 0);
12053 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12054 "vFile:open", "hostio-open", 0);
12056 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12057 "vFile:pread", "hostio-pread", 0);
12059 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12060 "vFile:pwrite", "hostio-pwrite", 0);
12062 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12063 "vFile:close", "hostio-close", 0);
12065 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12066 "vFile:unlink", "hostio-unlink", 0);
12068 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12069 "vFile:readlink", "hostio-readlink", 0);
12071 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12072 "vAttach", "attach", 0);
12074 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12077 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12078 "QStartNoAckMode", "noack", 0);
12080 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12081 "vKill", "kill", 0);
12083 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12084 "qAttached", "query-attached", 0);
12086 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12087 "ConditionalTracepoints",
12088 "conditional-tracepoints", 0);
12090 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12091 "ConditionalBreakpoints",
12092 "conditional-breakpoints", 0);
12094 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12095 "BreakpointCommands",
12096 "breakpoint-commands", 0);
12098 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12099 "FastTracepoints", "fast-tracepoints", 0);
12101 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12102 "TracepointSource", "TracepointSource", 0);
12104 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12105 "QAllow", "allow", 0);
12107 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12108 "StaticTracepoints", "static-tracepoints", 0);
12110 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12111 "InstallInTrace", "install-in-trace", 0);
12113 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12114 "qXfer:statictrace:read", "read-sdata-object", 0);
12116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12117 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12119 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12120 "QDisableRandomization", "disable-randomization", 0);
12122 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12123 "QAgent", "agent", 0);
12125 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12126 "QTBuffer:size", "trace-buffer-size", 0);
12128 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12129 "Qbtrace:off", "disable-btrace", 0);
12131 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12132 "Qbtrace:bts", "enable-btrace", 0);
12134 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12135 "qXfer:btrace", "read-btrace", 0);
12137 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12138 Z sub-packet has its own set and show commands, but users may
12139 have sets to this variable in their .gdbinit files (or in their
12141 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12142 &remote_Z_packet_detect, _("\
12143 Set use of remote protocol `Z' packets"), _("\
12144 Show use of remote protocol `Z' packets "), _("\
12145 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12147 set_remote_protocol_Z_packet_cmd,
12148 show_remote_protocol_Z_packet_cmd,
12149 /* FIXME: i18n: Use of remote protocol
12150 `Z' packets is %s. */
12151 &remote_set_cmdlist, &remote_show_cmdlist);
12153 add_prefix_cmd ("remote", class_files, remote_command, _("\
12154 Manipulate files on the remote system\n\
12155 Transfer files to and from the remote target system."),
12156 &remote_cmdlist, "remote ",
12157 0 /* allow-unknown */, &cmdlist);
12159 add_cmd ("put", class_files, remote_put_command,
12160 _("Copy a local file to the remote system."),
12163 add_cmd ("get", class_files, remote_get_command,
12164 _("Copy a remote file to the local system."),
12167 add_cmd ("delete", class_files, remote_delete_command,
12168 _("Delete a remote file."),
12171 remote_exec_file = xstrdup ("");
12172 add_setshow_string_noescape_cmd ("exec-file", class_files,
12173 &remote_exec_file, _("\
12174 Set the remote pathname for \"run\""), _("\
12175 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12176 &remote_set_cmdlist, &remote_show_cmdlist);
12178 add_setshow_boolean_cmd ("range-stepping", class_run,
12179 &use_range_stepping, _("\
12180 Enable or disable range stepping."), _("\
12181 Show whether target-assisted range stepping is enabled."), _("\
12182 If on, and the target supports it, when stepping a source line, GDB\n\
12183 tells the target to step the corresponding range of addresses itself instead\n\
12184 of issuing multiple single-steps. This speeds up source level\n\
12185 stepping. If off, GDB always issues single-steps, even if range\n\
12186 stepping is supported by the target. The default is on."),
12187 set_range_stepping,
12188 show_range_stepping,
12192 /* Eventually initialize fileio. See fileio.c */
12193 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12195 /* Take advantage of the fact that the LWP field is not used, to tag
12196 special ptids with it set to != 0. */
12197 magic_null_ptid = ptid_build (42000, 1, -1);
12198 not_sent_ptid = ptid_build (42000, 1, -2);
12199 any_thread_ptid = ptid_build (42000, 1, 0);
12201 target_buf_size = 2048;
12202 target_buf = xmalloc (target_buf_size);