1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
30 /*#include "terminal.h" */
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
36 #include "remote-notif.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
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 target_ops *self,
102 struct regcache *regcache);
104 static void remote_open_1 (const char *, int, struct target_ops *,
107 static void remote_close (struct target_ops *self);
111 static int remote_vkill (int pid, struct remote_state *rs);
113 static void remote_mourn (struct target_ops *ops);
115 static void extended_remote_restart (void);
117 static void extended_remote_mourn (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 remote_can_async_p (struct target_ops *);
129 static int remote_is_async_p (struct target_ops *);
131 static void remote_async (struct target_ops *ops, int enable);
133 static void sync_remote_interrupt_twice (int signo);
135 static void interrupt_query (void);
137 static void set_general_thread (struct ptid ptid);
138 static void set_continue_thread (struct ptid ptid);
140 static void get_offsets (void);
142 static void skip_frame (void);
144 static long read_frame (char **buf_p, long *sizeof_buf);
146 static int hexnumlen (ULONGEST num);
148 static void init_remote_ops (void);
150 static void init_extended_remote_ops (void);
152 static void remote_stop (struct target_ops *self, ptid_t);
154 static int stubhex (int ch);
156 static int hexnumstr (char *, ULONGEST);
158 static int hexnumnstr (char *, ULONGEST, int);
160 static CORE_ADDR remote_address_masked (CORE_ADDR);
162 static void print_packet (const char *);
164 static void compare_sections_command (char *, int);
166 static void packet_command (char *, int);
168 static int stub_unpack_int (char *buff, int fieldlength);
170 static ptid_t remote_current_thread (ptid_t oldptid);
172 static int putpkt_binary (const char *buf, int cnt);
174 static void check_binary_download (CORE_ADDR addr);
176 struct packet_config;
178 static void show_packet_config_cmd (struct packet_config *config);
180 static void show_remote_protocol_packet_cmd (struct ui_file *file,
182 struct cmd_list_element *c,
185 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
186 static ptid_t read_ptid (char *buf, char **obuf);
188 static void remote_set_permissions (struct target_ops *self);
190 static int remote_get_trace_status (struct target_ops *self,
191 struct trace_status *ts);
193 static int remote_upload_tracepoints (struct target_ops *self,
194 struct uploaded_tp **utpp);
196 static int remote_upload_trace_state_variables (struct target_ops *self,
197 struct uploaded_tsv **utsvp);
199 static void remote_query_supported (void);
201 static void remote_check_symbols (void);
203 void _initialize_remote (void);
206 static void stop_reply_xfree (struct stop_reply *);
207 static void remote_parse_stop_reply (char *, struct stop_reply *);
208 static void push_stop_reply (struct stop_reply *);
209 static void discard_pending_stop_replies_in_queue (struct remote_state *);
210 static int peek_stop_reply (ptid_t ptid);
212 struct threads_listing_context;
213 static void remove_new_fork_children (struct threads_listing_context *);
215 static void remote_async_inferior_event_handler (gdb_client_data);
217 static void remote_terminal_ours (struct target_ops *self);
219 static int remote_read_description_p (struct target_ops *target);
221 static void remote_console_output (char *msg);
223 static int remote_supports_cond_breakpoints (struct target_ops *self);
225 static int remote_can_run_breakpoint_commands (struct target_ops *self);
227 static void remote_btrace_reset (void);
229 static int stop_reply_queue_length (void);
233 static struct cmd_list_element *remote_cmdlist;
235 /* For "set remote" and "show remote". */
237 static struct cmd_list_element *remote_set_cmdlist;
238 static struct cmd_list_element *remote_show_cmdlist;
240 /* Stub vCont actions support.
242 Each field is a boolean flag indicating whether the stub reports
243 support for the corresponding action. */
245 struct vCont_action_support
254 /* Controls whether GDB is willing to use range stepping. */
256 static int use_range_stepping = 1;
258 #define OPAQUETHREADBYTES 8
260 /* a 64 bit opaque identifier */
261 typedef unsigned char threadref[OPAQUETHREADBYTES];
263 /* About this many threadisds fit in a packet. */
265 #define MAXTHREADLISTRESULTS 32
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 we resumed the target and we're waiting for the target to
310 stop. In the mean time, we can't start another command/query.
311 The remote server wouldn't be ready to process it, so we'd
312 timeout waiting for a reply that would never come and eventually
313 we'd close the connection. This can happen in asynchronous mode
314 because we allow GDB commands while the target is running. */
315 int waiting_for_stop_reply;
317 /* The status of the stub support for the various vCont actions. */
318 struct vCont_action_support supports_vCont;
320 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
321 responded to that. */
324 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
325 remote_open knows that we don't have a file open when the program
327 struct serial *remote_desc;
329 /* These are the threads which we last sent to the remote system. The
330 TID member will be -1 for all or -2 for not sent yet. */
331 ptid_t general_thread;
332 ptid_t continue_thread;
334 /* This is the traceframe which we last selected on the remote system.
335 It will be -1 if no traceframe is selected. */
336 int remote_traceframe_number;
338 char *last_pass_packet;
340 /* The last QProgramSignals packet sent to the target. We bypass
341 sending a new program signals list down to the target if the new
342 packet is exactly the same as the last we sent. IOW, we only let
343 the target know about program signals list changes. */
344 char *last_program_signals_packet;
346 enum gdb_signal last_sent_signal;
350 char *finished_object;
351 char *finished_annex;
352 ULONGEST finished_offset;
354 /* Should we try the 'ThreadInfo' query packet?
356 This variable (NOT available to the user: auto-detect only!)
357 determines whether GDB will use the new, simpler "ThreadInfo"
358 query or the older, more complex syntax for thread queries.
359 This is an auto-detect variable (set to true at each connect,
360 and set to false when the target fails to recognize it). */
361 int use_threadinfo_query;
362 int use_threadextra_query;
364 /* This is set to the data address of the access causing the target
365 to stop for a watchpoint. */
366 CORE_ADDR remote_watch_data_address;
368 /* Whether the target stopped for a breakpoint/watchpoint. */
369 enum target_stop_reason stop_reason;
371 threadref echo_nextthread;
372 threadref nextthread;
373 threadref resultthreadlist[MAXTHREADLISTRESULTS];
375 /* The state of remote notification. */
376 struct remote_notif_state *notif_state;
378 /* The branch trace configuration. */
379 struct btrace_config btrace_config;
381 /* The argument to the last "vFile:setfs:" packet we sent, used
382 to avoid sending repeated unnecessary "vFile:setfs:" packets.
383 Initialized to -1 to indicate that no "vFile:setfs:" packet
384 has yet been sent. */
388 /* Private data that we'll store in (struct thread_info)->private. */
389 struct private_thread_info
396 free_private_thread_info (struct private_thread_info *info)
402 /* This data could be associated with a target, but we do not always
403 have access to the current target when we need it, so for now it is
404 static. This will be fine for as long as only one target is in use
406 static struct remote_state *remote_state;
408 static struct remote_state *
409 get_remote_state_raw (void)
414 /* Allocate a new struct remote_state with xmalloc, initialize it, and
417 static struct remote_state *
418 new_remote_state (void)
420 struct remote_state *result = XCNEW (struct remote_state);
422 /* The default buffer size is unimportant; it will be expanded
423 whenever a larger buffer is needed. */
424 result->buf_size = 400;
425 result->buf = xmalloc (result->buf_size);
426 result->remote_traceframe_number = -1;
427 result->last_sent_signal = GDB_SIGNAL_0;
433 /* Description of the remote protocol for a given architecture. */
437 long offset; /* Offset into G packet. */
438 long regnum; /* GDB's internal register number. */
439 LONGEST pnum; /* Remote protocol register number. */
440 int in_g_packet; /* Always part of G packet. */
441 /* long size in bytes; == register_size (target_gdbarch (), regnum);
443 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
447 struct remote_arch_state
449 /* Description of the remote protocol registers. */
450 long sizeof_g_packet;
452 /* Description of the remote protocol registers indexed by REGNUM
453 (making an array gdbarch_num_regs in size). */
454 struct packet_reg *regs;
456 /* This is the size (in chars) of the first response to the ``g''
457 packet. It is used as a heuristic when determining the maximum
458 size of memory-read and memory-write packets. A target will
459 typically only reserve a buffer large enough to hold the ``g''
460 packet. The size does not include packet overhead (headers and
462 long actual_register_packet_size;
464 /* This is the maximum size (in chars) of a non read/write packet.
465 It is also used as a cap on the size of read/write packets. */
466 long remote_packet_size;
469 /* Utility: generate error from an incoming stub packet. */
471 trace_error (char *buf)
474 return; /* not an error msg */
477 case '1': /* malformed packet error */
478 if (*++buf == '0') /* general case: */
479 error (_("remote.c: error in outgoing packet."));
481 error (_("remote.c: error in outgoing packet at field #%ld."),
482 strtol (buf, NULL, 16));
484 error (_("Target returns error code '%s'."), buf);
488 /* Utility: wait for reply from stub, while accepting "O" packets. */
490 remote_get_noisy_reply (char **buf_p,
493 do /* Loop on reply from remote stub. */
497 QUIT; /* Allow user to bail out with ^C. */
498 getpkt (buf_p, sizeof_buf, 0);
502 else if (startswith (buf, "qRelocInsn:"))
505 CORE_ADDR from, to, org_to;
507 int adjusted_size = 0;
510 p = buf + strlen ("qRelocInsn:");
511 pp = unpack_varlen_hex (p, &ul);
513 error (_("invalid qRelocInsn packet: %s"), buf);
517 unpack_varlen_hex (p, &ul);
524 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
527 CATCH (ex, RETURN_MASK_ALL)
529 if (ex.error == MEMORY_ERROR)
531 /* Propagate memory errors silently back to the
532 target. The stub may have limited the range of
533 addresses we can write to, for example. */
537 /* Something unexpectedly bad happened. Be verbose
538 so we can tell what, and propagate the error back
539 to the stub, so it doesn't get stuck waiting for
541 exception_fprintf (gdb_stderr, ex,
542 _("warning: relocating instruction: "));
550 adjusted_size = to - org_to;
552 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
556 else if (buf[0] == 'O' && buf[1] != 'K')
557 remote_console_output (buf + 1); /* 'O' message from stub */
559 return buf; /* Here's the actual reply. */
564 /* Handle for retreving the remote protocol data from gdbarch. */
565 static struct gdbarch_data *remote_gdbarch_data_handle;
567 static struct remote_arch_state *
568 get_remote_arch_state (void)
570 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
573 /* Fetch the global remote target state. */
575 static struct remote_state *
576 get_remote_state (void)
578 /* Make sure that the remote architecture state has been
579 initialized, because doing so might reallocate rs->buf. Any
580 function which calls getpkt also needs to be mindful of changes
581 to rs->buf, but this call limits the number of places which run
583 get_remote_arch_state ();
585 return get_remote_state_raw ();
589 compare_pnums (const void *lhs_, const void *rhs_)
591 const struct packet_reg * const *lhs = lhs_;
592 const struct packet_reg * const *rhs = rhs_;
594 if ((*lhs)->pnum < (*rhs)->pnum)
596 else if ((*lhs)->pnum == (*rhs)->pnum)
603 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
605 int regnum, num_remote_regs, offset;
606 struct packet_reg **remote_regs;
608 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
610 struct packet_reg *r = ®s[regnum];
612 if (register_size (gdbarch, regnum) == 0)
613 /* Do not try to fetch zero-sized (placeholder) registers. */
616 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
621 /* Define the g/G packet format as the contents of each register
622 with a remote protocol number, in order of ascending protocol
625 remote_regs = alloca (gdbarch_num_regs (gdbarch)
626 * sizeof (struct packet_reg *));
627 for (num_remote_regs = 0, regnum = 0;
628 regnum < gdbarch_num_regs (gdbarch);
630 if (regs[regnum].pnum != -1)
631 remote_regs[num_remote_regs++] = ®s[regnum];
633 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
636 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
638 remote_regs[regnum]->in_g_packet = 1;
639 remote_regs[regnum]->offset = offset;
640 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
646 /* Given the architecture described by GDBARCH, return the remote
647 protocol register's number and the register's offset in the g/G
648 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
649 If the target does not have a mapping for REGNUM, return false,
650 otherwise, return true. */
653 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
654 int *pnum, int *poffset)
657 struct packet_reg *regs;
658 struct cleanup *old_chain;
660 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
662 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
663 old_chain = make_cleanup (xfree, regs);
665 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
667 *pnum = regs[regnum].pnum;
668 *poffset = regs[regnum].offset;
670 do_cleanups (old_chain);
676 init_remote_state (struct gdbarch *gdbarch)
678 struct remote_state *rs = get_remote_state_raw ();
679 struct remote_arch_state *rsa;
681 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
683 /* Use the architecture to build a regnum<->pnum table, which will be
684 1:1 unless a feature set specifies otherwise. */
685 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
686 gdbarch_num_regs (gdbarch),
689 /* Record the maximum possible size of the g packet - it may turn out
691 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
693 /* Default maximum number of characters in a packet body. Many
694 remote stubs have a hardwired buffer size of 400 bytes
695 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
696 as the maximum packet-size to ensure that the packet and an extra
697 NUL character can always fit in the buffer. This stops GDB
698 trashing stubs that try to squeeze an extra NUL into what is
699 already a full buffer (As of 1999-12-04 that was most stubs). */
700 rsa->remote_packet_size = 400 - 1;
702 /* This one is filled in when a ``g'' packet is received. */
703 rsa->actual_register_packet_size = 0;
705 /* Should rsa->sizeof_g_packet needs more space than the
706 default, adjust the size accordingly. Remember that each byte is
707 encoded as two characters. 32 is the overhead for the packet
708 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
709 (``$NN:G...#NN'') is a better guess, the below has been padded a
711 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
712 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
714 /* Make sure that the packet buffer is plenty big enough for
715 this architecture. */
716 if (rs->buf_size < rsa->remote_packet_size)
718 rs->buf_size = 2 * rsa->remote_packet_size;
719 rs->buf = xrealloc (rs->buf, rs->buf_size);
725 /* Return the current allowed size of a remote packet. This is
726 inferred from the current architecture, and should be used to
727 limit the length of outgoing packets. */
729 get_remote_packet_size (void)
731 struct remote_state *rs = get_remote_state ();
732 struct remote_arch_state *rsa = get_remote_arch_state ();
734 if (rs->explicit_packet_size)
735 return rs->explicit_packet_size;
737 return rsa->remote_packet_size;
740 static struct packet_reg *
741 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
743 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
747 struct packet_reg *r = &rsa->regs[regnum];
749 gdb_assert (r->regnum == regnum);
754 static struct packet_reg *
755 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
759 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
761 struct packet_reg *r = &rsa->regs[i];
769 static struct target_ops remote_ops;
771 static struct target_ops extended_remote_ops;
773 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
774 ``forever'' still use the normal timeout mechanism. This is
775 currently used by the ASYNC code to guarentee that target reads
776 during the initial connect always time-out. Once getpkt has been
777 modified to return a timeout indication and, in turn
778 remote_wait()/wait_for_inferior() have gained a timeout parameter
780 static int wait_forever_enabled_p = 1;
782 /* Allow the user to specify what sequence to send to the remote
783 when he requests a program interruption: Although ^C is usually
784 what remote systems expect (this is the default, here), it is
785 sometimes preferable to send a break. On other systems such
786 as the Linux kernel, a break followed by g, which is Magic SysRq g
787 is required in order to interrupt the execution. */
788 const char interrupt_sequence_control_c[] = "Ctrl-C";
789 const char interrupt_sequence_break[] = "BREAK";
790 const char interrupt_sequence_break_g[] = "BREAK-g";
791 static const char *const interrupt_sequence_modes[] =
793 interrupt_sequence_control_c,
794 interrupt_sequence_break,
795 interrupt_sequence_break_g,
798 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
801 show_interrupt_sequence (struct ui_file *file, int from_tty,
802 struct cmd_list_element *c,
805 if (interrupt_sequence_mode == interrupt_sequence_control_c)
806 fprintf_filtered (file,
807 _("Send the ASCII ETX character (Ctrl-c) "
808 "to the remote target to interrupt the "
809 "execution of the program.\n"));
810 else if (interrupt_sequence_mode == interrupt_sequence_break)
811 fprintf_filtered (file,
812 _("send a break signal to the remote target "
813 "to interrupt the execution of the program.\n"));
814 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
815 fprintf_filtered (file,
816 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
817 "the remote target to interrupt the execution "
818 "of Linux kernel.\n"));
820 internal_error (__FILE__, __LINE__,
821 _("Invalid value for interrupt_sequence_mode: %s."),
822 interrupt_sequence_mode);
825 /* This boolean variable specifies whether interrupt_sequence is sent
826 to the remote target when gdb connects to it.
827 This is mostly needed when you debug the Linux kernel: The Linux kernel
828 expects BREAK g which is Magic SysRq g for connecting gdb. */
829 static int interrupt_on_connect = 0;
831 /* This variable is used to implement the "set/show remotebreak" commands.
832 Since these commands are now deprecated in favor of "set/show remote
833 interrupt-sequence", it no longer has any effect on the code. */
834 static int remote_break;
837 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
840 interrupt_sequence_mode = interrupt_sequence_break;
842 interrupt_sequence_mode = interrupt_sequence_control_c;
846 show_remotebreak (struct ui_file *file, int from_tty,
847 struct cmd_list_element *c,
852 /* This variable sets the number of bits in an address that are to be
853 sent in a memory ("M" or "m") packet. Normally, after stripping
854 leading zeros, the entire address would be sent. This variable
855 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
856 initial implementation of remote.c restricted the address sent in
857 memory packets to ``host::sizeof long'' bytes - (typically 32
858 bits). Consequently, for 64 bit targets, the upper 32 bits of an
859 address was never sent. Since fixing this bug may cause a break in
860 some remote targets this variable is principly provided to
861 facilitate backward compatibility. */
863 static unsigned int remote_address_size;
865 /* Temporary to track who currently owns the terminal. See
866 remote_terminal_* for more details. */
868 static int remote_async_terminal_ours_p;
870 /* The executable file to use for "run" on the remote side. */
872 static char *remote_exec_file = "";
875 /* User configurable variables for the number of characters in a
876 memory read/write packet. MIN (rsa->remote_packet_size,
877 rsa->sizeof_g_packet) is the default. Some targets need smaller
878 values (fifo overruns, et.al.) and some users need larger values
879 (speed up transfers). The variables ``preferred_*'' (the user
880 request), ``current_*'' (what was actually set) and ``forced_*''
881 (Positive - a soft limit, negative - a hard limit). */
883 struct memory_packet_config
890 /* Compute the current size of a read/write packet. Since this makes
891 use of ``actual_register_packet_size'' the computation is dynamic. */
894 get_memory_packet_size (struct memory_packet_config *config)
896 struct remote_state *rs = get_remote_state ();
897 struct remote_arch_state *rsa = get_remote_arch_state ();
899 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
900 law?) that some hosts don't cope very well with large alloca()
901 calls. Eventually the alloca() code will be replaced by calls to
902 xmalloc() and make_cleanups() allowing this restriction to either
903 be lifted or removed. */
904 #ifndef MAX_REMOTE_PACKET_SIZE
905 #define MAX_REMOTE_PACKET_SIZE 16384
907 /* NOTE: 20 ensures we can write at least one byte. */
908 #ifndef MIN_REMOTE_PACKET_SIZE
909 #define MIN_REMOTE_PACKET_SIZE 20
914 if (config->size <= 0)
915 what_they_get = MAX_REMOTE_PACKET_SIZE;
917 what_they_get = config->size;
921 what_they_get = get_remote_packet_size ();
922 /* Limit the packet to the size specified by the user. */
924 && what_they_get > config->size)
925 what_they_get = config->size;
927 /* Limit it to the size of the targets ``g'' response unless we have
928 permission from the stub to use a larger packet size. */
929 if (rs->explicit_packet_size == 0
930 && rsa->actual_register_packet_size > 0
931 && what_they_get > rsa->actual_register_packet_size)
932 what_they_get = rsa->actual_register_packet_size;
934 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
935 what_they_get = MAX_REMOTE_PACKET_SIZE;
936 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
937 what_they_get = MIN_REMOTE_PACKET_SIZE;
939 /* Make sure there is room in the global buffer for this packet
940 (including its trailing NUL byte). */
941 if (rs->buf_size < what_they_get + 1)
943 rs->buf_size = 2 * what_they_get;
944 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
947 return what_they_get;
950 /* Update the size of a read/write packet. If they user wants
951 something really big then do a sanity check. */
954 set_memory_packet_size (char *args, struct memory_packet_config *config)
956 int fixed_p = config->fixed_p;
957 long size = config->size;
960 error (_("Argument required (integer, `fixed' or `limited')."));
961 else if (strcmp (args, "hard") == 0
962 || strcmp (args, "fixed") == 0)
964 else if (strcmp (args, "soft") == 0
965 || strcmp (args, "limit") == 0)
971 size = strtoul (args, &end, 0);
973 error (_("Invalid %s (bad syntax)."), config->name);
975 /* Instead of explicitly capping the size of a packet to
976 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
977 instead allowed to set the size to something arbitrarily
979 if (size > MAX_REMOTE_PACKET_SIZE)
980 error (_("Invalid %s (too large)."), config->name);
984 if (fixed_p && !config->fixed_p)
986 if (! query (_("The target may not be able to correctly handle a %s\n"
987 "of %ld bytes. Change the packet size? "),
989 error (_("Packet size not changed."));
991 /* Update the config. */
992 config->fixed_p = fixed_p;
997 show_memory_packet_size (struct memory_packet_config *config)
999 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1000 if (config->fixed_p)
1001 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1002 get_memory_packet_size (config));
1004 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1005 get_memory_packet_size (config));
1008 static struct memory_packet_config memory_write_packet_config =
1010 "memory-write-packet-size",
1014 set_memory_write_packet_size (char *args, int from_tty)
1016 set_memory_packet_size (args, &memory_write_packet_config);
1020 show_memory_write_packet_size (char *args, int from_tty)
1022 show_memory_packet_size (&memory_write_packet_config);
1026 get_memory_write_packet_size (void)
1028 return get_memory_packet_size (&memory_write_packet_config);
1031 static struct memory_packet_config memory_read_packet_config =
1033 "memory-read-packet-size",
1037 set_memory_read_packet_size (char *args, int from_tty)
1039 set_memory_packet_size (args, &memory_read_packet_config);
1043 show_memory_read_packet_size (char *args, int from_tty)
1045 show_memory_packet_size (&memory_read_packet_config);
1049 get_memory_read_packet_size (void)
1051 long size = get_memory_packet_size (&memory_read_packet_config);
1053 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1054 extra buffer size argument before the memory read size can be
1055 increased beyond this. */
1056 if (size > get_remote_packet_size ())
1057 size = get_remote_packet_size ();
1062 /* Generic configuration support for packets the stub optionally
1063 supports. Allows the user to specify the use of the packet as well
1064 as allowing GDB to auto-detect support in the remote stub. */
1068 PACKET_SUPPORT_UNKNOWN = 0,
1073 struct packet_config
1078 /* If auto, GDB auto-detects support for this packet or feature,
1079 either through qSupported, or by trying the packet and looking
1080 at the response. If true, GDB assumes the target supports this
1081 packet. If false, the packet is disabled. Configs that don't
1082 have an associated command always have this set to auto. */
1083 enum auto_boolean detect;
1085 /* Does the target support this packet? */
1086 enum packet_support support;
1089 /* Analyze a packet's return value and update the packet config
1099 static enum packet_support packet_config_support (struct packet_config *config);
1100 static enum packet_support packet_support (int packet);
1103 show_packet_config_cmd (struct packet_config *config)
1105 char *support = "internal-error";
1107 switch (packet_config_support (config))
1110 support = "enabled";
1112 case PACKET_DISABLE:
1113 support = "disabled";
1115 case PACKET_SUPPORT_UNKNOWN:
1116 support = "unknown";
1119 switch (config->detect)
1121 case AUTO_BOOLEAN_AUTO:
1122 printf_filtered (_("Support for the `%s' packet "
1123 "is auto-detected, currently %s.\n"),
1124 config->name, support);
1126 case AUTO_BOOLEAN_TRUE:
1127 case AUTO_BOOLEAN_FALSE:
1128 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1129 config->name, support);
1135 add_packet_config_cmd (struct packet_config *config, const char *name,
1136 const char *title, int legacy)
1142 config->name = name;
1143 config->title = title;
1144 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1146 show_doc = xstrprintf ("Show current use of remote "
1147 "protocol `%s' (%s) packet",
1149 /* set/show TITLE-packet {auto,on,off} */
1150 cmd_name = xstrprintf ("%s-packet", title);
1151 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1152 &config->detect, set_doc,
1153 show_doc, NULL, /* help_doc */
1155 show_remote_protocol_packet_cmd,
1156 &remote_set_cmdlist, &remote_show_cmdlist);
1157 /* The command code copies the documentation strings. */
1160 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1165 legacy_name = xstrprintf ("%s-packet", name);
1166 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1167 &remote_set_cmdlist);
1168 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1169 &remote_show_cmdlist);
1173 static enum packet_result
1174 packet_check_result (const char *buf)
1178 /* The stub recognized the packet request. Check that the
1179 operation succeeded. */
1181 && isxdigit (buf[1]) && isxdigit (buf[2])
1183 /* "Enn" - definitly an error. */
1184 return PACKET_ERROR;
1186 /* Always treat "E." as an error. This will be used for
1187 more verbose error messages, such as E.memtypes. */
1188 if (buf[0] == 'E' && buf[1] == '.')
1189 return PACKET_ERROR;
1191 /* The packet may or may not be OK. Just assume it is. */
1195 /* The stub does not support the packet. */
1196 return PACKET_UNKNOWN;
1199 static enum packet_result
1200 packet_ok (const char *buf, struct packet_config *config)
1202 enum packet_result result;
1204 if (config->detect != AUTO_BOOLEAN_TRUE
1205 && config->support == PACKET_DISABLE)
1206 internal_error (__FILE__, __LINE__,
1207 _("packet_ok: attempt to use a disabled packet"));
1209 result = packet_check_result (buf);
1214 /* The stub recognized the packet request. */
1215 if (config->support == PACKET_SUPPORT_UNKNOWN)
1218 fprintf_unfiltered (gdb_stdlog,
1219 "Packet %s (%s) is supported\n",
1220 config->name, config->title);
1221 config->support = PACKET_ENABLE;
1224 case PACKET_UNKNOWN:
1225 /* The stub does not support the packet. */
1226 if (config->detect == AUTO_BOOLEAN_AUTO
1227 && config->support == PACKET_ENABLE)
1229 /* If the stub previously indicated that the packet was
1230 supported then there is a protocol error. */
1231 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1232 config->name, config->title);
1234 else if (config->detect == AUTO_BOOLEAN_TRUE)
1236 /* The user set it wrong. */
1237 error (_("Enabled packet %s (%s) not recognized by stub"),
1238 config->name, config->title);
1242 fprintf_unfiltered (gdb_stdlog,
1243 "Packet %s (%s) is NOT supported\n",
1244 config->name, config->title);
1245 config->support = PACKET_DISABLE;
1266 PACKET_vFile_pwrite,
1268 PACKET_vFile_unlink,
1269 PACKET_vFile_readlink,
1272 PACKET_qXfer_features,
1273 PACKET_qXfer_exec_file,
1274 PACKET_qXfer_libraries,
1275 PACKET_qXfer_libraries_svr4,
1276 PACKET_qXfer_memory_map,
1277 PACKET_qXfer_spu_read,
1278 PACKET_qXfer_spu_write,
1279 PACKET_qXfer_osdata,
1280 PACKET_qXfer_threads,
1281 PACKET_qXfer_statictrace_read,
1282 PACKET_qXfer_traceframe_info,
1288 PACKET_QPassSignals,
1289 PACKET_QProgramSignals,
1291 PACKET_qSearch_memory,
1294 PACKET_QStartNoAckMode,
1296 PACKET_qXfer_siginfo_read,
1297 PACKET_qXfer_siginfo_write,
1300 /* Support for conditional tracepoints. */
1301 PACKET_ConditionalTracepoints,
1303 /* Support for target-side breakpoint conditions. */
1304 PACKET_ConditionalBreakpoints,
1306 /* Support for target-side breakpoint commands. */
1307 PACKET_BreakpointCommands,
1309 /* Support for fast tracepoints. */
1310 PACKET_FastTracepoints,
1312 /* Support for static tracepoints. */
1313 PACKET_StaticTracepoints,
1315 /* Support for installing tracepoints while a trace experiment is
1317 PACKET_InstallInTrace,
1321 PACKET_TracepointSource,
1324 PACKET_QDisableRandomization,
1326 PACKET_QTBuffer_size,
1330 PACKET_qXfer_btrace,
1332 /* Support for the QNonStop packet. */
1335 /* Support for multi-process extensions. */
1336 PACKET_multiprocess_feature,
1338 /* Support for enabling and disabling tracepoints while a trace
1339 experiment is running. */
1340 PACKET_EnableDisableTracepoints_feature,
1342 /* Support for collecting strings using the tracenz bytecode. */
1343 PACKET_tracenz_feature,
1345 /* Support for continuing to run a trace experiment while GDB is
1347 PACKET_DisconnectedTracing_feature,
1349 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1350 PACKET_augmented_libraries_svr4_read_feature,
1352 /* Support for the qXfer:btrace-conf:read packet. */
1353 PACKET_qXfer_btrace_conf,
1355 /* Support for the Qbtrace-conf:bts:size packet. */
1356 PACKET_Qbtrace_conf_bts_size,
1358 /* Support for swbreak+ feature. */
1359 PACKET_swbreak_feature,
1361 /* Support for hwbreak+ feature. */
1362 PACKET_hwbreak_feature,
1364 /* Support for fork events. */
1365 PACKET_fork_event_feature,
1367 /* Support for vfork events. */
1368 PACKET_vfork_event_feature,
1370 /* Support for the Qbtrace-conf:pt:size packet. */
1371 PACKET_Qbtrace_conf_pt_size,
1376 static struct packet_config remote_protocol_packets[PACKET_MAX];
1378 /* Returns the packet's corresponding "set remote foo-packet" command
1379 state. See struct packet_config for more details. */
1381 static enum auto_boolean
1382 packet_set_cmd_state (int packet)
1384 return remote_protocol_packets[packet].detect;
1387 /* Returns whether a given packet or feature is supported. This takes
1388 into account the state of the corresponding "set remote foo-packet"
1389 command, which may be used to bypass auto-detection. */
1391 static enum packet_support
1392 packet_config_support (struct packet_config *config)
1394 switch (config->detect)
1396 case AUTO_BOOLEAN_TRUE:
1397 return PACKET_ENABLE;
1398 case AUTO_BOOLEAN_FALSE:
1399 return PACKET_DISABLE;
1400 case AUTO_BOOLEAN_AUTO:
1401 return config->support;
1403 gdb_assert_not_reached (_("bad switch"));
1407 /* Same as packet_config_support, but takes the packet's enum value as
1410 static enum packet_support
1411 packet_support (int packet)
1413 struct packet_config *config = &remote_protocol_packets[packet];
1415 return packet_config_support (config);
1419 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1420 struct cmd_list_element *c,
1423 struct packet_config *packet;
1425 for (packet = remote_protocol_packets;
1426 packet < &remote_protocol_packets[PACKET_MAX];
1429 if (&packet->detect == c->var)
1431 show_packet_config_cmd (packet);
1435 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1439 /* Should we try one of the 'Z' requests? */
1443 Z_PACKET_SOFTWARE_BP,
1444 Z_PACKET_HARDWARE_BP,
1451 /* For compatibility with older distributions. Provide a ``set remote
1452 Z-packet ...'' command that updates all the Z packet types. */
1454 static enum auto_boolean remote_Z_packet_detect;
1457 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1458 struct cmd_list_element *c)
1462 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1463 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1467 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1468 struct cmd_list_element *c,
1473 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1475 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1479 /* Returns true if the multi-process extensions are in effect. */
1482 remote_multi_process_p (struct remote_state *rs)
1484 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1487 /* Returns true if fork events are supported. */
1490 remote_fork_event_p (struct remote_state *rs)
1492 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1495 /* Returns true if vfork events are supported. */
1498 remote_vfork_event_p (struct remote_state *rs)
1500 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1503 /* Insert fork catchpoint target routine. If fork events are enabled
1504 then return success, nothing more to do. */
1507 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1509 struct remote_state *rs = get_remote_state ();
1511 return !remote_fork_event_p (rs);
1514 /* Remove fork catchpoint target routine. Nothing to do, just
1518 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1523 /* Insert vfork catchpoint target routine. If vfork events are enabled
1524 then return success, nothing more to do. */
1527 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1529 struct remote_state *rs = get_remote_state ();
1531 return !remote_vfork_event_p (rs);
1534 /* Remove vfork catchpoint target routine. Nothing to do, just
1538 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1543 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1544 static struct async_signal_handler *async_sigint_remote_twice_token;
1545 static struct async_signal_handler *async_sigint_remote_token;
1548 /* Asynchronous signal handle registered as event loop source for
1549 when we have pending events ready to be passed to the core. */
1551 static struct async_event_handler *remote_async_inferior_event_token;
1555 static ptid_t magic_null_ptid;
1556 static ptid_t not_sent_ptid;
1557 static ptid_t any_thread_ptid;
1559 /* Find out if the stub attached to PID (and hence GDB should offer to
1560 detach instead of killing it when bailing out). */
1563 remote_query_attached (int pid)
1565 struct remote_state *rs = get_remote_state ();
1566 size_t size = get_remote_packet_size ();
1568 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1571 if (remote_multi_process_p (rs))
1572 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1574 xsnprintf (rs->buf, size, "qAttached");
1577 getpkt (&rs->buf, &rs->buf_size, 0);
1579 switch (packet_ok (rs->buf,
1580 &remote_protocol_packets[PACKET_qAttached]))
1583 if (strcmp (rs->buf, "1") == 0)
1587 warning (_("Remote failure reply: %s"), rs->buf);
1589 case PACKET_UNKNOWN:
1596 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1597 has been invented by GDB, instead of reported by the target. Since
1598 we can be connected to a remote system before before knowing about
1599 any inferior, mark the target with execution when we find the first
1600 inferior. If ATTACHED is 1, then we had just attached to this
1601 inferior. If it is 0, then we just created this inferior. If it
1602 is -1, then try querying the remote stub to find out if it had
1603 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1604 attempt to open this inferior's executable as the main executable
1605 if no main executable is open already. */
1607 static struct inferior *
1608 remote_add_inferior (int fake_pid_p, int pid, int attached,
1611 struct inferior *inf;
1613 /* Check whether this process we're learning about is to be
1614 considered attached, or if is to be considered to have been
1615 spawned by the stub. */
1617 attached = remote_query_attached (pid);
1619 if (gdbarch_has_global_solist (target_gdbarch ()))
1621 /* If the target shares code across all inferiors, then every
1622 attach adds a new inferior. */
1623 inf = add_inferior (pid);
1625 /* ... and every inferior is bound to the same program space.
1626 However, each inferior may still have its own address
1628 inf->aspace = maybe_new_address_space ();
1629 inf->pspace = current_program_space;
1633 /* In the traditional debugging scenario, there's a 1-1 match
1634 between program/address spaces. We simply bind the inferior
1635 to the program space's address space. */
1636 inf = current_inferior ();
1637 inferior_appeared (inf, pid);
1640 inf->attach_flag = attached;
1641 inf->fake_pid_p = fake_pid_p;
1643 /* If no main executable is currently open then attempt to
1644 open the file that was executed to create this inferior. */
1645 if (try_open_exec && get_exec_file (0) == NULL)
1646 exec_file_locate_attach (pid, 1);
1651 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1652 according to RUNNING. */
1655 remote_add_thread (ptid_t ptid, int running)
1657 struct remote_state *rs = get_remote_state ();
1659 /* GDB historically didn't pull threads in the initial connection
1660 setup. If the remote target doesn't even have a concept of
1661 threads (e.g., a bare-metal target), even if internally we
1662 consider that a single-threaded target, mentioning a new thread
1663 might be confusing to the user. Be silent then, preserving the
1664 age old behavior. */
1665 if (rs->starting_up)
1666 add_thread_silent (ptid);
1670 set_executing (ptid, running);
1671 set_running (ptid, running);
1674 /* Come here when we learn about a thread id from the remote target.
1675 It may be the first time we hear about such thread, so take the
1676 opportunity to add it to GDB's thread list. In case this is the
1677 first time we're noticing its corresponding inferior, add it to
1678 GDB's inferior list as well. */
1681 remote_notice_new_inferior (ptid_t currthread, int running)
1683 /* If this is a new thread, add it to GDB's thread list.
1684 If we leave it up to WFI to do this, bad things will happen. */
1686 if (in_thread_list (currthread) && is_exited (currthread))
1688 /* We're seeing an event on a thread id we knew had exited.
1689 This has to be a new thread reusing the old id. Add it. */
1690 remote_add_thread (currthread, running);
1694 if (!in_thread_list (currthread))
1696 struct inferior *inf = NULL;
1697 int pid = ptid_get_pid (currthread);
1699 if (ptid_is_pid (inferior_ptid)
1700 && pid == ptid_get_pid (inferior_ptid))
1702 /* inferior_ptid has no thread member yet. This can happen
1703 with the vAttach -> remote_wait,"TAAthread:" path if the
1704 stub doesn't support qC. This is the first stop reported
1705 after an attach, so this is the main thread. Update the
1706 ptid in the thread list. */
1707 if (in_thread_list (pid_to_ptid (pid)))
1708 thread_change_ptid (inferior_ptid, currthread);
1711 remote_add_thread (currthread, running);
1712 inferior_ptid = currthread;
1717 if (ptid_equal (magic_null_ptid, inferior_ptid))
1719 /* inferior_ptid is not set yet. This can happen with the
1720 vRun -> remote_wait,"TAAthread:" path if the stub
1721 doesn't support qC. This is the first stop reported
1722 after an attach, so this is the main thread. Update the
1723 ptid in the thread list. */
1724 thread_change_ptid (inferior_ptid, currthread);
1728 /* When connecting to a target remote, or to a target
1729 extended-remote which already was debugging an inferior, we
1730 may not know about it yet. Add it before adding its child
1731 thread, so notifications are emitted in a sensible order. */
1732 if (!in_inferior_list (ptid_get_pid (currthread)))
1734 struct remote_state *rs = get_remote_state ();
1735 int fake_pid_p = !remote_multi_process_p (rs);
1737 inf = remote_add_inferior (fake_pid_p,
1738 ptid_get_pid (currthread), -1, 1);
1741 /* This is really a new thread. Add it. */
1742 remote_add_thread (currthread, running);
1744 /* If we found a new inferior, let the common code do whatever
1745 it needs to with it (e.g., read shared libraries, insert
1746 breakpoints), unless we're just setting up an all-stop
1750 struct remote_state *rs = get_remote_state ();
1752 if (non_stop || !rs->starting_up)
1753 notice_new_inferior (currthread, running, 0);
1758 /* Return the private thread data, creating it if necessary. */
1760 static struct private_thread_info *
1761 demand_private_info (ptid_t ptid)
1763 struct thread_info *info = find_thread_ptid (ptid);
1769 info->priv = xmalloc (sizeof (*(info->priv)));
1770 info->private_dtor = free_private_thread_info;
1771 info->priv->core = -1;
1772 info->priv->extra = 0;
1778 /* Call this function as a result of
1779 1) A halt indication (T packet) containing a thread id
1780 2) A direct query of currthread
1781 3) Successful execution of set thread */
1784 record_currthread (struct remote_state *rs, ptid_t currthread)
1786 rs->general_thread = currthread;
1789 /* If 'QPassSignals' is supported, tell the remote stub what signals
1790 it can simply pass through to the inferior without reporting. */
1793 remote_pass_signals (struct target_ops *self,
1794 int numsigs, unsigned char *pass_signals)
1796 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1798 char *pass_packet, *p;
1800 struct remote_state *rs = get_remote_state ();
1802 gdb_assert (numsigs < 256);
1803 for (i = 0; i < numsigs; i++)
1805 if (pass_signals[i])
1808 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1809 strcpy (pass_packet, "QPassSignals:");
1810 p = pass_packet + strlen (pass_packet);
1811 for (i = 0; i < numsigs; i++)
1813 if (pass_signals[i])
1816 *p++ = tohex (i >> 4);
1817 *p++ = tohex (i & 15);
1826 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1828 putpkt (pass_packet);
1829 getpkt (&rs->buf, &rs->buf_size, 0);
1830 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1831 if (rs->last_pass_packet)
1832 xfree (rs->last_pass_packet);
1833 rs->last_pass_packet = pass_packet;
1836 xfree (pass_packet);
1840 /* If 'QProgramSignals' is supported, tell the remote stub what
1841 signals it should pass through to the inferior when detaching. */
1844 remote_program_signals (struct target_ops *self,
1845 int numsigs, unsigned char *signals)
1847 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1851 struct remote_state *rs = get_remote_state ();
1853 gdb_assert (numsigs < 256);
1854 for (i = 0; i < numsigs; i++)
1859 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1860 strcpy (packet, "QProgramSignals:");
1861 p = packet + strlen (packet);
1862 for (i = 0; i < numsigs; i++)
1864 if (signal_pass_state (i))
1867 *p++ = tohex (i >> 4);
1868 *p++ = tohex (i & 15);
1877 if (!rs->last_program_signals_packet
1878 || strcmp (rs->last_program_signals_packet, packet) != 0)
1881 getpkt (&rs->buf, &rs->buf_size, 0);
1882 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1883 xfree (rs->last_program_signals_packet);
1884 rs->last_program_signals_packet = packet;
1891 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1892 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1893 thread. If GEN is set, set the general thread, if not, then set
1894 the step/continue thread. */
1896 set_thread (struct ptid ptid, int gen)
1898 struct remote_state *rs = get_remote_state ();
1899 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1900 char *buf = rs->buf;
1901 char *endbuf = rs->buf + get_remote_packet_size ();
1903 if (ptid_equal (state, ptid))
1907 *buf++ = gen ? 'g' : 'c';
1908 if (ptid_equal (ptid, magic_null_ptid))
1909 xsnprintf (buf, endbuf - buf, "0");
1910 else if (ptid_equal (ptid, any_thread_ptid))
1911 xsnprintf (buf, endbuf - buf, "0");
1912 else if (ptid_equal (ptid, minus_one_ptid))
1913 xsnprintf (buf, endbuf - buf, "-1");
1915 write_ptid (buf, endbuf, ptid);
1917 getpkt (&rs->buf, &rs->buf_size, 0);
1919 rs->general_thread = ptid;
1921 rs->continue_thread = ptid;
1925 set_general_thread (struct ptid ptid)
1927 set_thread (ptid, 1);
1931 set_continue_thread (struct ptid ptid)
1933 set_thread (ptid, 0);
1936 /* Change the remote current process. Which thread within the process
1937 ends up selected isn't important, as long as it is the same process
1938 as what INFERIOR_PTID points to.
1940 This comes from that fact that there is no explicit notion of
1941 "selected process" in the protocol. The selected process for
1942 general operations is the process the selected general thread
1946 set_general_process (void)
1948 struct remote_state *rs = get_remote_state ();
1950 /* If the remote can't handle multiple processes, don't bother. */
1951 if (!rs->extended || !remote_multi_process_p (rs))
1954 /* We only need to change the remote current thread if it's pointing
1955 at some other process. */
1956 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1957 set_general_thread (inferior_ptid);
1961 /* Return nonzero if this is the main thread that we made up ourselves
1962 to model non-threaded targets as single-threaded. */
1965 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1967 struct remote_state *rs = get_remote_state ();
1970 if (ptid_equal (ptid, magic_null_ptid))
1971 /* The main thread is always alive. */
1974 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
1975 /* The main thread is always alive. This can happen after a
1976 vAttach, if the remote side doesn't support
1983 /* Return nonzero if the thread PTID is still alive on the remote
1987 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1989 struct remote_state *rs = get_remote_state ();
1992 /* Check if this is a thread that we made up ourselves to model
1993 non-threaded targets as single-threaded. */
1994 if (remote_thread_always_alive (ops, ptid))
1998 endp = rs->buf + get_remote_packet_size ();
2001 write_ptid (p, endp, ptid);
2004 getpkt (&rs->buf, &rs->buf_size, 0);
2005 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2008 /* About these extended threadlist and threadinfo packets. They are
2009 variable length packets but, the fields within them are often fixed
2010 length. They are redundent enough to send over UDP as is the
2011 remote protocol in general. There is a matching unit test module
2014 /* WARNING: This threadref data structure comes from the remote O.S.,
2015 libstub protocol encoding, and remote.c. It is not particularly
2018 /* Right now, the internal structure is int. We want it to be bigger.
2019 Plan to fix this. */
2021 typedef int gdb_threadref; /* Internal GDB thread reference. */
2023 /* gdb_ext_thread_info is an internal GDB data structure which is
2024 equivalent to the reply of the remote threadinfo packet. */
2026 struct gdb_ext_thread_info
2028 threadref threadid; /* External form of thread reference. */
2029 int active; /* Has state interesting to GDB?
2031 char display[256]; /* Brief state display, name,
2032 blocked/suspended. */
2033 char shortname[32]; /* To be used to name threads. */
2034 char more_display[256]; /* Long info, statistics, queue depth,
2038 /* The volume of remote transfers can be limited by submitting
2039 a mask containing bits specifying the desired information.
2040 Use a union of these values as the 'selection' parameter to
2041 get_thread_info. FIXME: Make these TAG names more thread specific. */
2043 #define TAG_THREADID 1
2044 #define TAG_EXISTS 2
2045 #define TAG_DISPLAY 4
2046 #define TAG_THREADNAME 8
2047 #define TAG_MOREDISPLAY 16
2049 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2051 static char *unpack_nibble (char *buf, int *val);
2053 static char *unpack_byte (char *buf, int *value);
2055 static char *pack_int (char *buf, int value);
2057 static char *unpack_int (char *buf, int *value);
2059 static char *unpack_string (char *src, char *dest, int length);
2061 static char *pack_threadid (char *pkt, threadref *id);
2063 static char *unpack_threadid (char *inbuf, threadref *id);
2065 void int_to_threadref (threadref *id, int value);
2067 static int threadref_to_int (threadref *ref);
2069 static void copy_threadref (threadref *dest, threadref *src);
2071 static int threadmatch (threadref *dest, threadref *src);
2073 static char *pack_threadinfo_request (char *pkt, int mode,
2076 static int remote_unpack_thread_info_response (char *pkt,
2077 threadref *expectedref,
2078 struct gdb_ext_thread_info
2082 static int remote_get_threadinfo (threadref *threadid,
2083 int fieldset, /*TAG mask */
2084 struct gdb_ext_thread_info *info);
2086 static char *pack_threadlist_request (char *pkt, int startflag,
2088 threadref *nextthread);
2090 static int parse_threadlist_response (char *pkt,
2092 threadref *original_echo,
2093 threadref *resultlist,
2096 static int remote_get_threadlist (int startflag,
2097 threadref *nextthread,
2101 threadref *threadlist);
2103 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2105 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2106 void *context, int looplimit);
2108 static int remote_newthread_step (threadref *ref, void *context);
2111 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2112 buffer we're allowed to write to. Returns
2113 BUF+CHARACTERS_WRITTEN. */
2116 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2119 struct remote_state *rs = get_remote_state ();
2121 if (remote_multi_process_p (rs))
2123 pid = ptid_get_pid (ptid);
2125 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2127 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2129 tid = ptid_get_lwp (ptid);
2131 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2133 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2138 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2139 passed the last parsed char. Returns null_ptid on error. */
2142 read_ptid (char *buf, char **obuf)
2146 ULONGEST pid = 0, tid = 0;
2150 /* Multi-process ptid. */
2151 pp = unpack_varlen_hex (p + 1, &pid);
2153 error (_("invalid remote ptid: %s"), p);
2156 pp = unpack_varlen_hex (p + 1, &tid);
2159 return ptid_build (pid, tid, 0);
2162 /* No multi-process. Just a tid. */
2163 pp = unpack_varlen_hex (p, &tid);
2165 /* Return null_ptid when no thread id is found. */
2173 /* Since the stub is not sending a process id, then default to
2174 what's in inferior_ptid, unless it's null at this point. If so,
2175 then since there's no way to know the pid of the reported
2176 threads, use the magic number. */
2177 if (ptid_equal (inferior_ptid, null_ptid))
2178 pid = ptid_get_pid (magic_null_ptid);
2180 pid = ptid_get_pid (inferior_ptid);
2184 return ptid_build (pid, tid, 0);
2190 if (ch >= 'a' && ch <= 'f')
2191 return ch - 'a' + 10;
2192 if (ch >= '0' && ch <= '9')
2194 if (ch >= 'A' && ch <= 'F')
2195 return ch - 'A' + 10;
2200 stub_unpack_int (char *buff, int fieldlength)
2207 nibble = stubhex (*buff++);
2211 retval = retval << 4;
2217 unpack_nibble (char *buf, int *val)
2219 *val = fromhex (*buf++);
2224 unpack_byte (char *buf, int *value)
2226 *value = stub_unpack_int (buf, 2);
2231 pack_int (char *buf, int value)
2233 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2234 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2235 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2236 buf = pack_hex_byte (buf, (value & 0xff));
2241 unpack_int (char *buf, int *value)
2243 *value = stub_unpack_int (buf, 8);
2247 #if 0 /* Currently unused, uncomment when needed. */
2248 static char *pack_string (char *pkt, char *string);
2251 pack_string (char *pkt, char *string)
2256 len = strlen (string);
2258 len = 200; /* Bigger than most GDB packets, junk??? */
2259 pkt = pack_hex_byte (pkt, len);
2263 if ((ch == '\0') || (ch == '#'))
2264 ch = '*'; /* Protect encapsulation. */
2269 #endif /* 0 (unused) */
2272 unpack_string (char *src, char *dest, int length)
2281 pack_threadid (char *pkt, threadref *id)
2284 unsigned char *altid;
2286 altid = (unsigned char *) id;
2287 limit = pkt + BUF_THREAD_ID_SIZE;
2289 pkt = pack_hex_byte (pkt, *altid++);
2295 unpack_threadid (char *inbuf, threadref *id)
2298 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2301 altref = (char *) id;
2303 while (inbuf < limit)
2305 x = stubhex (*inbuf++);
2306 y = stubhex (*inbuf++);
2307 *altref++ = (x << 4) | y;
2312 /* Externally, threadrefs are 64 bits but internally, they are still
2313 ints. This is due to a mismatch of specifications. We would like
2314 to use 64bit thread references internally. This is an adapter
2318 int_to_threadref (threadref *id, int value)
2320 unsigned char *scan;
2322 scan = (unsigned char *) id;
2328 *scan++ = (value >> 24) & 0xff;
2329 *scan++ = (value >> 16) & 0xff;
2330 *scan++ = (value >> 8) & 0xff;
2331 *scan++ = (value & 0xff);
2335 threadref_to_int (threadref *ref)
2338 unsigned char *scan;
2344 value = (value << 8) | ((*scan++) & 0xff);
2349 copy_threadref (threadref *dest, threadref *src)
2352 unsigned char *csrc, *cdest;
2354 csrc = (unsigned char *) src;
2355 cdest = (unsigned char *) dest;
2362 threadmatch (threadref *dest, threadref *src)
2364 /* Things are broken right now, so just assume we got a match. */
2366 unsigned char *srcp, *destp;
2368 srcp = (char *) src;
2369 destp = (char *) dest;
2373 result &= (*srcp++ == *destp++) ? 1 : 0;
2380 threadid:1, # always request threadid
2387 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2390 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2392 *pkt++ = 'q'; /* Info Query */
2393 *pkt++ = 'P'; /* process or thread info */
2394 pkt = pack_int (pkt, mode); /* mode */
2395 pkt = pack_threadid (pkt, id); /* threadid */
2396 *pkt = '\0'; /* terminate */
2400 /* These values tag the fields in a thread info response packet. */
2401 /* Tagging the fields allows us to request specific fields and to
2402 add more fields as time goes by. */
2404 #define TAG_THREADID 1 /* Echo the thread identifier. */
2405 #define TAG_EXISTS 2 /* Is this process defined enough to
2406 fetch registers and its stack? */
2407 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2408 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2409 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2413 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2414 struct gdb_ext_thread_info *info)
2416 struct remote_state *rs = get_remote_state ();
2420 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2423 /* info->threadid = 0; FIXME: implement zero_threadref. */
2425 info->display[0] = '\0';
2426 info->shortname[0] = '\0';
2427 info->more_display[0] = '\0';
2429 /* Assume the characters indicating the packet type have been
2431 pkt = unpack_int (pkt, &mask); /* arg mask */
2432 pkt = unpack_threadid (pkt, &ref);
2435 warning (_("Incomplete response to threadinfo request."));
2436 if (!threadmatch (&ref, expectedref))
2437 { /* This is an answer to a different request. */
2438 warning (_("ERROR RMT Thread info mismatch."));
2441 copy_threadref (&info->threadid, &ref);
2443 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2445 /* Packets are terminated with nulls. */
2446 while ((pkt < limit) && mask && *pkt)
2448 pkt = unpack_int (pkt, &tag); /* tag */
2449 pkt = unpack_byte (pkt, &length); /* length */
2450 if (!(tag & mask)) /* Tags out of synch with mask. */
2452 warning (_("ERROR RMT: threadinfo tag mismatch."));
2456 if (tag == TAG_THREADID)
2460 warning (_("ERROR RMT: length of threadid is not 16."));
2464 pkt = unpack_threadid (pkt, &ref);
2465 mask = mask & ~TAG_THREADID;
2468 if (tag == TAG_EXISTS)
2470 info->active = stub_unpack_int (pkt, length);
2472 mask = mask & ~(TAG_EXISTS);
2475 warning (_("ERROR RMT: 'exists' length too long."));
2481 if (tag == TAG_THREADNAME)
2483 pkt = unpack_string (pkt, &info->shortname[0], length);
2484 mask = mask & ~TAG_THREADNAME;
2487 if (tag == TAG_DISPLAY)
2489 pkt = unpack_string (pkt, &info->display[0], length);
2490 mask = mask & ~TAG_DISPLAY;
2493 if (tag == TAG_MOREDISPLAY)
2495 pkt = unpack_string (pkt, &info->more_display[0], length);
2496 mask = mask & ~TAG_MOREDISPLAY;
2499 warning (_("ERROR RMT: unknown thread info tag."));
2500 break; /* Not a tag we know about. */
2506 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2507 struct gdb_ext_thread_info *info)
2509 struct remote_state *rs = get_remote_state ();
2512 pack_threadinfo_request (rs->buf, fieldset, threadid);
2514 getpkt (&rs->buf, &rs->buf_size, 0);
2516 if (rs->buf[0] == '\0')
2519 result = remote_unpack_thread_info_response (rs->buf + 2,
2524 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2527 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2528 threadref *nextthread)
2530 *pkt++ = 'q'; /* info query packet */
2531 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2532 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2533 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2534 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2539 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2542 parse_threadlist_response (char *pkt, int result_limit,
2543 threadref *original_echo, threadref *resultlist,
2546 struct remote_state *rs = get_remote_state ();
2548 int count, resultcount, done;
2551 /* Assume the 'q' and 'M chars have been stripped. */
2552 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2553 /* done parse past here */
2554 pkt = unpack_byte (pkt, &count); /* count field */
2555 pkt = unpack_nibble (pkt, &done);
2556 /* The first threadid is the argument threadid. */
2557 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2558 while ((count-- > 0) && (pkt < limit))
2560 pkt = unpack_threadid (pkt, resultlist++);
2561 if (resultcount++ >= result_limit)
2569 /* Fetch the next batch of threads from the remote. Returns -1 if the
2570 qL packet is not supported, 0 on error and 1 on success. */
2573 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2574 int *done, int *result_count, threadref *threadlist)
2576 struct remote_state *rs = get_remote_state ();
2579 /* Trancate result limit to be smaller than the packet size. */
2580 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2581 >= get_remote_packet_size ())
2582 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2584 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2586 getpkt (&rs->buf, &rs->buf_size, 0);
2587 if (*rs->buf == '\0')
2589 /* Packet not supported. */
2594 parse_threadlist_response (rs->buf + 2, result_limit,
2595 &rs->echo_nextthread, threadlist, done);
2597 if (!threadmatch (&rs->echo_nextthread, nextthread))
2599 /* FIXME: This is a good reason to drop the packet. */
2600 /* Possably, there is a duplicate response. */
2602 retransmit immediatly - race conditions
2603 retransmit after timeout - yes
2605 wait for packet, then exit
2607 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2608 return 0; /* I choose simply exiting. */
2610 if (*result_count <= 0)
2614 warning (_("RMT ERROR : failed to get remote thread list."));
2617 return result; /* break; */
2619 if (*result_count > result_limit)
2622 warning (_("RMT ERROR: threadlist response longer than requested."));
2628 /* Fetch the list of remote threads, with the qL packet, and call
2629 STEPFUNCTION for each thread found. Stops iterating and returns 1
2630 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2631 STEPFUNCTION returns false. If the packet is not supported,
2635 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2638 struct remote_state *rs = get_remote_state ();
2639 int done, i, result_count;
2647 if (loopcount++ > looplimit)
2650 warning (_("Remote fetch threadlist -infinite loop-."));
2653 result = remote_get_threadlist (startflag, &rs->nextthread,
2654 MAXTHREADLISTRESULTS,
2655 &done, &result_count,
2656 rs->resultthreadlist);
2659 /* Clear for later iterations. */
2661 /* Setup to resume next batch of thread references, set nextthread. */
2662 if (result_count >= 1)
2663 copy_threadref (&rs->nextthread,
2664 &rs->resultthreadlist[result_count - 1]);
2666 while (result_count--)
2668 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2678 /* A thread found on the remote target. */
2680 typedef struct thread_item
2682 /* The thread's PTID. */
2685 /* The thread's extra info. May be NULL. */
2688 /* The core the thread was running on. -1 if not known. */
2691 DEF_VEC_O(thread_item_t);
2693 /* Context passed around to the various methods listing remote
2694 threads. As new threads are found, they're added to the ITEMS
2697 struct threads_listing_context
2699 /* The threads found on the remote target. */
2700 VEC (thread_item_t) *items;
2703 /* Discard the contents of the constructed thread listing context. */
2706 clear_threads_listing_context (void *p)
2708 struct threads_listing_context *context = p;
2710 struct thread_item *item;
2712 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2713 xfree (item->extra);
2715 VEC_free (thread_item_t, context->items);
2718 /* Remove the thread specified as the related_pid field of WS
2719 from the CONTEXT list. */
2722 threads_listing_context_remove (struct target_waitstatus *ws,
2723 struct threads_listing_context *context)
2725 struct thread_item *item;
2727 ptid_t child_ptid = ws->value.related_pid;
2729 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2731 if (ptid_equal (item->ptid, child_ptid))
2733 VEC_ordered_remove (thread_item_t, context->items, i);
2740 remote_newthread_step (threadref *ref, void *data)
2742 struct threads_listing_context *context = data;
2743 struct thread_item item;
2744 int pid = ptid_get_pid (inferior_ptid);
2746 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2750 VEC_safe_push (thread_item_t, context->items, &item);
2752 return 1; /* continue iterator */
2755 #define CRAZY_MAX_THREADS 1000
2758 remote_current_thread (ptid_t oldpid)
2760 struct remote_state *rs = get_remote_state ();
2763 getpkt (&rs->buf, &rs->buf_size, 0);
2764 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2769 result = read_ptid (&rs->buf[2], &obuf);
2770 if (*obuf != '\0' && remote_debug)
2771 fprintf_unfiltered (gdb_stdlog,
2772 "warning: garbage in qC reply\n");
2780 /* List remote threads using the deprecated qL packet. */
2783 remote_get_threads_with_ql (struct target_ops *ops,
2784 struct threads_listing_context *context)
2786 if (remote_threadlist_iterator (remote_newthread_step, context,
2787 CRAZY_MAX_THREADS) >= 0)
2793 #if defined(HAVE_LIBEXPAT)
2796 start_thread (struct gdb_xml_parser *parser,
2797 const struct gdb_xml_element *element,
2798 void *user_data, VEC(gdb_xml_value_s) *attributes)
2800 struct threads_listing_context *data = user_data;
2802 struct thread_item item;
2804 struct gdb_xml_value *attr;
2806 id = xml_find_attribute (attributes, "id")->value;
2807 item.ptid = read_ptid (id, NULL);
2809 attr = xml_find_attribute (attributes, "core");
2811 item.core = *(ULONGEST *) attr->value;
2817 VEC_safe_push (thread_item_t, data->items, &item);
2821 end_thread (struct gdb_xml_parser *parser,
2822 const struct gdb_xml_element *element,
2823 void *user_data, const char *body_text)
2825 struct threads_listing_context *data = user_data;
2827 if (body_text && *body_text)
2828 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2831 const struct gdb_xml_attribute thread_attributes[] = {
2832 { "id", GDB_XML_AF_NONE, NULL, NULL },
2833 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2834 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2837 const struct gdb_xml_element thread_children[] = {
2838 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2841 const struct gdb_xml_element threads_children[] = {
2842 { "thread", thread_attributes, thread_children,
2843 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2844 start_thread, end_thread },
2845 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2848 const struct gdb_xml_element threads_elements[] = {
2849 { "threads", NULL, threads_children,
2850 GDB_XML_EF_NONE, NULL, NULL },
2851 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2856 /* List remote threads using qXfer:threads:read. */
2859 remote_get_threads_with_qxfer (struct target_ops *ops,
2860 struct threads_listing_context *context)
2862 #if defined(HAVE_LIBEXPAT)
2863 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2865 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2866 struct cleanup *back_to = make_cleanup (xfree, xml);
2868 if (xml != NULL && *xml != '\0')
2870 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2871 threads_elements, xml, context);
2874 do_cleanups (back_to);
2882 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2885 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2886 struct threads_listing_context *context)
2888 struct remote_state *rs = get_remote_state ();
2890 if (rs->use_threadinfo_query)
2894 putpkt ("qfThreadInfo");
2895 getpkt (&rs->buf, &rs->buf_size, 0);
2897 if (bufp[0] != '\0') /* q packet recognized */
2899 while (*bufp++ == 'm') /* reply contains one or more TID */
2903 struct thread_item item;
2905 item.ptid = read_ptid (bufp, &bufp);
2909 VEC_safe_push (thread_item_t, context->items, &item);
2911 while (*bufp++ == ','); /* comma-separated list */
2912 putpkt ("qsThreadInfo");
2913 getpkt (&rs->buf, &rs->buf_size, 0);
2920 /* Packet not recognized. */
2921 rs->use_threadinfo_query = 0;
2928 /* Implement the to_update_thread_list function for the remote
2932 remote_update_thread_list (struct target_ops *ops)
2934 struct remote_state *rs = get_remote_state ();
2935 struct threads_listing_context context;
2936 struct cleanup *old_chain;
2939 context.items = NULL;
2940 old_chain = make_cleanup (clear_threads_listing_context, &context);
2942 /* We have a few different mechanisms to fetch the thread list. Try
2943 them all, starting with the most preferred one first, falling
2944 back to older methods. */
2945 if (remote_get_threads_with_qxfer (ops, &context)
2946 || remote_get_threads_with_qthreadinfo (ops, &context)
2947 || remote_get_threads_with_ql (ops, &context))
2950 struct thread_item *item;
2951 struct thread_info *tp, *tmp;
2955 if (VEC_empty (thread_item_t, context.items)
2956 && remote_thread_always_alive (ops, inferior_ptid))
2958 /* Some targets don't really support threads, but still
2959 reply an (empty) thread list in response to the thread
2960 listing packets, instead of replying "packet not
2961 supported". Exit early so we don't delete the main
2963 do_cleanups (old_chain);
2967 /* CONTEXT now holds the current thread list on the remote
2968 target end. Delete GDB-side threads no longer found on the
2970 ALL_THREADS_SAFE (tp, tmp)
2973 VEC_iterate (thread_item_t, context.items, i, item);
2976 if (ptid_equal (item->ptid, tp->ptid))
2980 if (i == VEC_length (thread_item_t, context.items))
2983 delete_thread (tp->ptid);
2987 /* Remove any unreported fork child threads from CONTEXT so
2988 that we don't interfere with follow fork, which is where
2989 creation of such threads is handled. */
2990 remove_new_fork_children (&context);
2992 /* And now add threads we don't know about yet to our list. */
2994 VEC_iterate (thread_item_t, context.items, i, item);
2997 if (!ptid_equal (item->ptid, null_ptid))
2999 struct private_thread_info *info;
3000 /* In non-stop mode, we assume new found threads are
3001 running until proven otherwise with a stop reply. In
3002 all-stop, we can only get here if all threads are
3004 int running = non_stop ? 1 : 0;
3006 remote_notice_new_inferior (item->ptid, running);
3008 info = demand_private_info (item->ptid);
3009 info->core = item->core;
3010 info->extra = item->extra;
3018 /* If no thread listing method is supported, then query whether
3019 each known thread is alive, one by one, with the T packet.
3020 If the target doesn't support threads at all, then this is a
3021 no-op. See remote_thread_alive. */
3025 do_cleanups (old_chain);
3029 * Collect a descriptive string about the given thread.
3030 * The target may say anything it wants to about the thread
3031 * (typically info about its blocked / runnable state, name, etc.).
3032 * This string will appear in the info threads display.
3034 * Optional: targets are not required to implement this function.
3038 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3040 struct remote_state *rs = get_remote_state ();
3044 struct gdb_ext_thread_info threadinfo;
3045 static char display_buf[100]; /* arbitrary... */
3046 int n = 0; /* position in display_buf */
3048 if (rs->remote_desc == 0) /* paranoia */
3049 internal_error (__FILE__, __LINE__,
3050 _("remote_threads_extra_info"));
3052 if (ptid_equal (tp->ptid, magic_null_ptid)
3053 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3054 /* This is the main thread which was added by GDB. The remote
3055 server doesn't know about it. */
3058 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3060 struct thread_info *info = find_thread_ptid (tp->ptid);
3062 if (info && info->priv)
3063 return info->priv->extra;
3068 if (rs->use_threadextra_query)
3071 char *endb = rs->buf + get_remote_packet_size ();
3073 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3075 write_ptid (b, endb, tp->ptid);
3078 getpkt (&rs->buf, &rs->buf_size, 0);
3079 if (rs->buf[0] != 0)
3081 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3082 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3083 display_buf [result] = '\0';
3088 /* If the above query fails, fall back to the old method. */
3089 rs->use_threadextra_query = 0;
3090 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3091 | TAG_MOREDISPLAY | TAG_DISPLAY;
3092 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3093 if (remote_get_threadinfo (&id, set, &threadinfo))
3094 if (threadinfo.active)
3096 if (*threadinfo.shortname)
3097 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3098 " Name: %s,", threadinfo.shortname);
3099 if (*threadinfo.display)
3100 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3101 " State: %s,", threadinfo.display);
3102 if (*threadinfo.more_display)
3103 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3104 " Priority: %s", threadinfo.more_display);
3108 /* For purely cosmetic reasons, clear up trailing commas. */
3109 if (',' == display_buf[n-1])
3110 display_buf[n-1] = ' ';
3119 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3120 struct static_tracepoint_marker *marker)
3122 struct remote_state *rs = get_remote_state ();
3125 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3127 p += hexnumstr (p, addr);
3129 getpkt (&rs->buf, &rs->buf_size, 0);
3133 error (_("Remote failure reply: %s"), p);
3137 parse_static_tracepoint_marker_definition (p, &p, marker);
3144 static VEC(static_tracepoint_marker_p) *
3145 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3148 struct remote_state *rs = get_remote_state ();
3149 VEC(static_tracepoint_marker_p) *markers = NULL;
3150 struct static_tracepoint_marker *marker = NULL;
3151 struct cleanup *old_chain;
3154 /* Ask for a first packet of static tracepoint marker
3157 getpkt (&rs->buf, &rs->buf_size, 0);
3160 error (_("Remote failure reply: %s"), p);
3162 old_chain = make_cleanup (free_current_marker, &marker);
3167 marker = XCNEW (struct static_tracepoint_marker);
3171 parse_static_tracepoint_marker_definition (p, &p, marker);
3173 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3175 VEC_safe_push (static_tracepoint_marker_p,
3181 release_static_tracepoint_marker (marker);
3182 memset (marker, 0, sizeof (*marker));
3185 while (*p++ == ','); /* comma-separated list */
3186 /* Ask for another packet of static tracepoint definition. */
3188 getpkt (&rs->buf, &rs->buf_size, 0);
3192 do_cleanups (old_chain);
3197 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3200 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3202 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3206 /* Restart the remote side; this is an extended protocol operation. */
3209 extended_remote_restart (void)
3211 struct remote_state *rs = get_remote_state ();
3213 /* Send the restart command; for reasons I don't understand the
3214 remote side really expects a number after the "R". */
3215 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3218 remote_fileio_reset ();
3221 /* Clean up connection to a remote debugger. */
3224 remote_close (struct target_ops *self)
3226 struct remote_state *rs = get_remote_state ();
3228 if (rs->remote_desc == NULL)
3229 return; /* already closed */
3231 /* Make sure we leave stdin registered in the event loop, and we
3232 don't leave the async SIGINT signal handler installed. */
3233 remote_terminal_ours (self);
3235 serial_close (rs->remote_desc);
3236 rs->remote_desc = NULL;
3238 /* We don't have a connection to the remote stub anymore. Get rid
3239 of all the inferiors and their threads we were controlling.
3240 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3241 will be unable to find the thread corresponding to (pid, 0, 0). */
3242 inferior_ptid = null_ptid;
3243 discard_all_inferiors ();
3245 /* We are closing the remote target, so we should discard
3246 everything of this target. */
3247 discard_pending_stop_replies_in_queue (rs);
3249 if (remote_async_inferior_event_token)
3250 delete_async_event_handler (&remote_async_inferior_event_token);
3252 remote_notif_state_xfree (rs->notif_state);
3254 trace_reset_local_state ();
3257 /* Query the remote side for the text, data and bss offsets. */
3262 struct remote_state *rs = get_remote_state ();
3265 int lose, num_segments = 0, do_sections, do_segments;
3266 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3267 struct section_offsets *offs;
3268 struct symfile_segment_data *data;
3270 if (symfile_objfile == NULL)
3273 putpkt ("qOffsets");
3274 getpkt (&rs->buf, &rs->buf_size, 0);
3277 if (buf[0] == '\000')
3278 return; /* Return silently. Stub doesn't support
3282 warning (_("Remote failure reply: %s"), buf);
3286 /* Pick up each field in turn. This used to be done with scanf, but
3287 scanf will make trouble if CORE_ADDR size doesn't match
3288 conversion directives correctly. The following code will work
3289 with any size of CORE_ADDR. */
3290 text_addr = data_addr = bss_addr = 0;
3294 if (startswith (ptr, "Text="))
3297 /* Don't use strtol, could lose on big values. */
3298 while (*ptr && *ptr != ';')
3299 text_addr = (text_addr << 4) + fromhex (*ptr++);
3301 if (startswith (ptr, ";Data="))
3304 while (*ptr && *ptr != ';')
3305 data_addr = (data_addr << 4) + fromhex (*ptr++);
3310 if (!lose && startswith (ptr, ";Bss="))
3313 while (*ptr && *ptr != ';')
3314 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3316 if (bss_addr != data_addr)
3317 warning (_("Target reported unsupported offsets: %s"), buf);
3322 else if (startswith (ptr, "TextSeg="))
3325 /* Don't use strtol, could lose on big values. */
3326 while (*ptr && *ptr != ';')
3327 text_addr = (text_addr << 4) + fromhex (*ptr++);
3330 if (startswith (ptr, ";DataSeg="))
3333 while (*ptr && *ptr != ';')
3334 data_addr = (data_addr << 4) + fromhex (*ptr++);
3342 error (_("Malformed response to offset query, %s"), buf);
3343 else if (*ptr != '\0')
3344 warning (_("Target reported unsupported offsets: %s"), buf);
3346 offs = ((struct section_offsets *)
3347 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3348 memcpy (offs, symfile_objfile->section_offsets,
3349 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3351 data = get_symfile_segment_data (symfile_objfile->obfd);
3352 do_segments = (data != NULL);
3353 do_sections = num_segments == 0;
3355 if (num_segments > 0)
3357 segments[0] = text_addr;
3358 segments[1] = data_addr;
3360 /* If we have two segments, we can still try to relocate everything
3361 by assuming that the .text and .data offsets apply to the whole
3362 text and data segments. Convert the offsets given in the packet
3363 to base addresses for symfile_map_offsets_to_segments. */
3364 else if (data && data->num_segments == 2)
3366 segments[0] = data->segment_bases[0] + text_addr;
3367 segments[1] = data->segment_bases[1] + data_addr;
3370 /* If the object file has only one segment, assume that it is text
3371 rather than data; main programs with no writable data are rare,
3372 but programs with no code are useless. Of course the code might
3373 have ended up in the data segment... to detect that we would need
3374 the permissions here. */
3375 else if (data && data->num_segments == 1)
3377 segments[0] = data->segment_bases[0] + text_addr;
3380 /* There's no way to relocate by segment. */
3386 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3387 offs, num_segments, segments);
3389 if (ret == 0 && !do_sections)
3390 error (_("Can not handle qOffsets TextSeg "
3391 "response with this symbol file"));
3398 free_symfile_segment_data (data);
3402 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3404 /* This is a temporary kludge to force data and bss to use the
3405 same offsets because that's what nlmconv does now. The real
3406 solution requires changes to the stub and remote.c that I
3407 don't have time to do right now. */
3409 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3410 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3413 objfile_relocate (symfile_objfile, offs);
3416 /* Send interrupt_sequence to remote target. */
3418 send_interrupt_sequence (void)
3420 struct remote_state *rs = get_remote_state ();
3422 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3423 remote_serial_write ("\x03", 1);
3424 else if (interrupt_sequence_mode == interrupt_sequence_break)
3425 serial_send_break (rs->remote_desc);
3426 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3428 serial_send_break (rs->remote_desc);
3429 remote_serial_write ("g", 1);
3432 internal_error (__FILE__, __LINE__,
3433 _("Invalid value for interrupt_sequence_mode: %s."),
3434 interrupt_sequence_mode);
3438 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3439 and extract the PTID. Returns NULL_PTID if not found. */
3442 stop_reply_extract_thread (char *stop_reply)
3444 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3448 /* Txx r:val ; r:val (...) */
3451 /* Look for "register" named "thread". */
3456 p1 = strchr (p, ':');
3460 if (strncmp (p, "thread", p1 - p) == 0)
3461 return read_ptid (++p1, &p);
3463 p1 = strchr (p, ';');
3475 /* Determine the remote side's current thread. If we have a stop
3476 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3477 "thread" register we can extract the current thread from. If not,
3478 ask the remote which is the current thread with qC. The former
3479 method avoids a roundtrip. */
3482 get_current_thread (char *wait_status)
3484 ptid_t ptid = null_ptid;
3486 /* Note we don't use remote_parse_stop_reply as that makes use of
3487 the target architecture, which we haven't yet fully determined at
3489 if (wait_status != NULL)
3490 ptid = stop_reply_extract_thread (wait_status);
3491 if (ptid_equal (ptid, null_ptid))
3492 ptid = remote_current_thread (inferior_ptid);
3497 /* Query the remote target for which is the current thread/process,
3498 add it to our tables, and update INFERIOR_PTID. The caller is
3499 responsible for setting the state such that the remote end is ready
3500 to return the current thread.
3502 This function is called after handling the '?' or 'vRun' packets,
3503 whose response is a stop reply from which we can also try
3504 extracting the thread. If the target doesn't support the explicit
3505 qC query, we infer the current thread from that stop reply, passed
3506 in in WAIT_STATUS, which may be NULL. */
3509 add_current_inferior_and_thread (char *wait_status)
3511 struct remote_state *rs = get_remote_state ();
3515 inferior_ptid = null_ptid;
3517 /* Now, if we have thread information, update inferior_ptid. */
3518 ptid = get_current_thread (wait_status);
3520 if (!ptid_equal (ptid, null_ptid))
3522 if (!remote_multi_process_p (rs))
3525 inferior_ptid = ptid;
3529 /* Without this, some commands which require an active target
3530 (such as kill) won't work. This variable serves (at least)
3531 double duty as both the pid of the target process (if it has
3532 such), and as a flag indicating that a target is active. */
3533 inferior_ptid = magic_null_ptid;
3537 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3539 /* Add the main thread. */
3540 add_thread_silent (inferior_ptid);
3543 /* Process all initial stop replies the remote side sent in response
3544 to the ? packet. These indicate threads that were already stopped
3545 on initial connection. We mark these threads as stopped and print
3546 their current frame before giving the user the prompt. */
3549 process_initial_stop_replies (void)
3551 int pending_stop_replies = stop_reply_queue_length ();
3553 /* Consume the initial pending events. */
3554 while (pending_stop_replies-- > 0)
3556 ptid_t waiton_ptid = minus_one_ptid;
3558 struct target_waitstatus ws;
3559 int ignore_event = 0;
3561 memset (&ws, 0, sizeof (ws));
3562 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3564 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3568 case TARGET_WAITKIND_IGNORE:
3569 case TARGET_WAITKIND_NO_RESUMED:
3570 case TARGET_WAITKIND_SIGNALLED:
3571 case TARGET_WAITKIND_EXITED:
3572 /* We shouldn't see these, but if we do, just ignore. */
3574 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3578 case TARGET_WAITKIND_EXECD:
3579 xfree (ws.value.execd_pathname);
3588 switch_to_thread (event_ptid);
3589 set_executing (event_ptid, 0);
3590 set_running (event_ptid, 0);
3592 stop_pc = get_frame_pc (get_current_frame ());
3593 set_current_sal_from_frame (get_current_frame ());
3595 if (ws.kind == TARGET_WAITKIND_STOPPED)
3597 enum gdb_signal sig = ws.value.sig;
3599 /* Stubs traditionally report SIGTRAP as initial signal,
3600 instead of signal 0. Suppress it. */
3601 if (sig == GDB_SIGNAL_TRAP)
3603 inferior_thread ()->suspend.stop_signal = sig;
3605 if (signal_print_state (sig))
3606 observer_notify_signal_received (sig);
3609 print_stop_event (&ws);
3610 observer_notify_normal_stop (NULL, 1);
3615 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3617 struct remote_state *rs = get_remote_state ();
3618 struct packet_config *noack_config;
3619 char *wait_status = NULL;
3621 immediate_quit++; /* Allow user to interrupt it. */
3624 if (interrupt_on_connect)
3625 send_interrupt_sequence ();
3627 /* Ack any packet which the remote side has already sent. */
3628 serial_write (rs->remote_desc, "+", 1);
3630 /* Signal other parts that we're going through the initial setup,
3631 and so things may not be stable yet. */
3632 rs->starting_up = 1;
3634 /* The first packet we send to the target is the optional "supported
3635 packets" request. If the target can answer this, it will tell us
3636 which later probes to skip. */
3637 remote_query_supported ();
3639 /* If the stub wants to get a QAllow, compose one and send it. */
3640 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3641 remote_set_permissions (target);
3643 /* Next, we possibly activate noack mode.
3645 If the QStartNoAckMode packet configuration is set to AUTO,
3646 enable noack mode if the stub reported a wish for it with
3649 If set to TRUE, then enable noack mode even if the stub didn't
3650 report it in qSupported. If the stub doesn't reply OK, the
3651 session ends with an error.
3653 If FALSE, then don't activate noack mode, regardless of what the
3654 stub claimed should be the default with qSupported. */
3656 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3657 if (packet_config_support (noack_config) != PACKET_DISABLE)
3659 putpkt ("QStartNoAckMode");
3660 getpkt (&rs->buf, &rs->buf_size, 0);
3661 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3667 /* Tell the remote that we are using the extended protocol. */
3669 getpkt (&rs->buf, &rs->buf_size, 0);
3672 /* Let the target know which signals it is allowed to pass down to
3674 update_signals_program_target ();
3676 /* Next, if the target can specify a description, read it. We do
3677 this before anything involving memory or registers. */
3678 target_find_description ();
3680 /* Next, now that we know something about the target, update the
3681 address spaces in the program spaces. */
3682 update_address_spaces ();
3684 /* On OSs where the list of libraries is global to all
3685 processes, we fetch them early. */
3686 if (gdbarch_has_global_solist (target_gdbarch ()))
3687 solib_add (NULL, from_tty, target, auto_solib_add);
3691 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3692 error (_("Non-stop mode requested, but remote "
3693 "does not support non-stop"));
3695 putpkt ("QNonStop:1");
3696 getpkt (&rs->buf, &rs->buf_size, 0);
3698 if (strcmp (rs->buf, "OK") != 0)
3699 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3701 /* Find about threads and processes the stub is already
3702 controlling. We default to adding them in the running state.
3703 The '?' query below will then tell us about which threads are
3705 remote_update_thread_list (target);
3707 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3709 /* Don't assume that the stub can operate in all-stop mode.
3710 Request it explicitly. */
3711 putpkt ("QNonStop:0");
3712 getpkt (&rs->buf, &rs->buf_size, 0);
3714 if (strcmp (rs->buf, "OK") != 0)
3715 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3718 /* Upload TSVs regardless of whether the target is running or not. The
3719 remote stub, such as GDBserver, may have some predefined or builtin
3720 TSVs, even if the target is not running. */
3721 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3723 struct uploaded_tsv *uploaded_tsvs = NULL;
3725 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3726 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3729 /* Check whether the target is running now. */
3731 getpkt (&rs->buf, &rs->buf_size, 0);
3737 struct inferior *inf;
3739 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3742 error (_("The target is not running (try extended-remote?)"));
3744 /* We're connected, but not running. Drop out before we
3745 call start_remote. */
3746 rs->starting_up = 0;
3751 /* Save the reply for later. */
3752 wait_status = alloca (strlen (rs->buf) + 1);
3753 strcpy (wait_status, rs->buf);
3756 /* Fetch thread list. */
3757 target_update_thread_list ();
3759 /* Let the stub know that we want it to return the thread. */
3760 set_continue_thread (minus_one_ptid);
3762 if (thread_count () == 0)
3764 /* Target has no concept of threads at all. GDB treats
3765 non-threaded target as single-threaded; add a main
3767 add_current_inferior_and_thread (wait_status);
3771 /* We have thread information; select the thread the target
3772 says should be current. If we're reconnecting to a
3773 multi-threaded program, this will ideally be the thread
3774 that last reported an event before GDB disconnected. */
3775 inferior_ptid = get_current_thread (wait_status);
3776 if (ptid_equal (inferior_ptid, null_ptid))
3778 /* Odd... The target was able to list threads, but not
3779 tell us which thread was current (no "thread"
3780 register in T stop reply?). Just pick the first
3781 thread in the thread list then. */
3784 fprintf_unfiltered (gdb_stdlog,
3785 "warning: couldn't determine remote "
3786 "current thread; picking first in list.\n");
3788 inferior_ptid = thread_list->ptid;
3792 /* init_wait_for_inferior should be called before get_offsets in order
3793 to manage `inserted' flag in bp loc in a correct state.
3794 breakpoint_init_inferior, called from init_wait_for_inferior, set
3795 `inserted' flag to 0, while before breakpoint_re_set, called from
3796 start_remote, set `inserted' flag to 1. In the initialization of
3797 inferior, breakpoint_init_inferior should be called first, and then
3798 breakpoint_re_set can be called. If this order is broken, state of
3799 `inserted' flag is wrong, and cause some problems on breakpoint
3801 init_wait_for_inferior ();
3803 get_offsets (); /* Get text, data & bss offsets. */
3805 /* If we could not find a description using qXfer, and we know
3806 how to do it some other way, try again. This is not
3807 supported for non-stop; it could be, but it is tricky if
3808 there are no stopped threads when we connect. */
3809 if (remote_read_description_p (target)
3810 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3812 target_clear_description ();
3813 target_find_description ();
3816 /* Use the previously fetched status. */
3817 gdb_assert (wait_status != NULL);
3818 strcpy (rs->buf, wait_status);
3819 rs->cached_wait_status = 1;
3822 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3826 ptid_t current_ptid;
3828 /* Clear WFI global state. Do this before finding about new
3829 threads and inferiors, and setting the current inferior.
3830 Otherwise we would clear the proceed status of the current
3831 inferior when we want its stop_soon state to be preserved
3832 (see notice_new_inferior). */
3833 init_wait_for_inferior ();
3835 /* In non-stop, we will either get an "OK", meaning that there
3836 are no stopped threads at this time; or, a regular stop
3837 reply. In the latter case, there may be more than one thread
3838 stopped --- we pull them all out using the vStopped
3840 if (strcmp (rs->buf, "OK") != 0)
3842 struct notif_client *notif = ¬if_client_stop;
3844 /* remote_notif_get_pending_replies acks this one, and gets
3846 rs->notif_state->pending_event[notif_client_stop.id]
3847 = remote_notif_parse (notif, rs->buf);
3848 remote_notif_get_pending_events (notif);
3851 if (thread_count () == 0)
3854 error (_("The target is not running (try extended-remote?)"));
3856 /* We're connected, but not running. Drop out before we
3857 call start_remote. */
3858 rs->starting_up = 0;
3862 /* Let the stub know that we want it to return the thread. */
3864 /* Force the stub to choose a thread. */
3865 set_general_thread (null_ptid);
3868 current_ptid = remote_current_thread (minus_one_ptid);
3869 if (ptid_equal (inferior_ptid, minus_one_ptid))
3870 error (_("remote didn't report the current thread in non-stop mode"));
3872 inferior_ptid = current_ptid;
3873 get_offsets (); /* Get text, data & bss offsets. */
3875 /* In non-stop mode, any cached wait status will be stored in
3876 the stop reply queue. */
3877 gdb_assert (wait_status == NULL);
3879 /* Report all signals during attach/startup. */
3880 remote_pass_signals (target, 0, NULL);
3882 /* If there are already stopped threads, mark them stopped and
3883 report their stops before giving the prompt to the user. */
3884 process_initial_stop_replies ();
3886 switch_to_thread (current_ptid);
3888 if (target_can_async_p ())
3892 /* If we connected to a live target, do some additional setup. */
3893 if (target_has_execution)
3895 if (symfile_objfile) /* No use without a symbol-file. */
3896 remote_check_symbols ();
3899 /* Possibly the target has been engaged in a trace run started
3900 previously; find out where things are at. */
3901 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3903 struct uploaded_tp *uploaded_tps = NULL;
3905 if (current_trace_status ()->running)
3906 printf_filtered (_("Trace is already running on the target.\n"));
3908 remote_upload_tracepoints (target, &uploaded_tps);
3910 merge_uploaded_tracepoints (&uploaded_tps);
3913 /* The thread and inferior lists are now synchronized with the
3914 target, our symbols have been relocated, and we're merged the
3915 target's tracepoints with ours. We're done with basic start
3917 rs->starting_up = 0;
3919 /* Maybe breakpoints are global and need to be inserted now. */
3920 if (breakpoints_should_be_inserted_now ())
3921 insert_breakpoints ();
3924 /* Open a connection to a remote debugger.
3925 NAME is the filename used for communication. */
3928 remote_open (const char *name, int from_tty)
3930 remote_open_1 (name, from_tty, &remote_ops, 0);
3933 /* Open a connection to a remote debugger using the extended
3934 remote gdb protocol. NAME is the filename used for communication. */
3937 extended_remote_open (const char *name, int from_tty)
3939 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3942 /* Reset all packets back to "unknown support". Called when opening a
3943 new connection to a remote target. */
3946 reset_all_packet_configs_support (void)
3950 for (i = 0; i < PACKET_MAX; i++)
3951 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3954 /* Initialize all packet configs. */
3957 init_all_packet_configs (void)
3961 for (i = 0; i < PACKET_MAX; i++)
3963 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3964 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3968 /* Symbol look-up. */
3971 remote_check_symbols (void)
3973 struct remote_state *rs = get_remote_state ();
3974 char *msg, *reply, *tmp;
3975 struct bound_minimal_symbol sym;
3978 /* The remote side has no concept of inferiors that aren't running
3979 yet, it only knows about running processes. If we're connected
3980 but our current inferior is not running, we should not invite the
3981 remote target to request symbol lookups related to its
3982 (unrelated) current process. */
3983 if (!target_has_execution)
3986 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3989 /* Make sure the remote is pointing at the right process. Note
3990 there's no way to select "no process". */
3991 set_general_process ();
3993 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3994 because we need both at the same time. */
3995 msg = alloca (get_remote_packet_size ());
3997 /* Invite target to request symbol lookups. */
3999 putpkt ("qSymbol::");
4000 getpkt (&rs->buf, &rs->buf_size, 0);
4001 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4004 while (startswith (reply, "qSymbol:"))
4006 struct bound_minimal_symbol sym;
4009 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4011 sym = lookup_minimal_symbol (msg, NULL, NULL);
4012 if (sym.minsym == NULL)
4013 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4016 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4017 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4019 /* If this is a function address, return the start of code
4020 instead of any data function descriptor. */
4021 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4025 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4026 phex_nz (sym_addr, addr_size), &reply[8]);
4030 getpkt (&rs->buf, &rs->buf_size, 0);
4035 static struct serial *
4036 remote_serial_open (const char *name)
4038 static int udp_warning = 0;
4040 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4041 of in ser-tcp.c, because it is the remote protocol assuming that the
4042 serial connection is reliable and not the serial connection promising
4044 if (!udp_warning && startswith (name, "udp:"))
4046 warning (_("The remote protocol may be unreliable over UDP.\n"
4047 "Some events may be lost, rendering further debugging "
4052 return serial_open (name);
4055 /* Inform the target of our permission settings. The permission flags
4056 work without this, but if the target knows the settings, it can do
4057 a couple things. First, it can add its own check, to catch cases
4058 that somehow manage to get by the permissions checks in target
4059 methods. Second, if the target is wired to disallow particular
4060 settings (for instance, a system in the field that is not set up to
4061 be able to stop at a breakpoint), it can object to any unavailable
4065 remote_set_permissions (struct target_ops *self)
4067 struct remote_state *rs = get_remote_state ();
4069 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4070 "WriteReg:%x;WriteMem:%x;"
4071 "InsertBreak:%x;InsertTrace:%x;"
4072 "InsertFastTrace:%x;Stop:%x",
4073 may_write_registers, may_write_memory,
4074 may_insert_breakpoints, may_insert_tracepoints,
4075 may_insert_fast_tracepoints, may_stop);
4077 getpkt (&rs->buf, &rs->buf_size, 0);
4079 /* If the target didn't like the packet, warn the user. Do not try
4080 to undo the user's settings, that would just be maddening. */
4081 if (strcmp (rs->buf, "OK") != 0)
4082 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4085 /* This type describes each known response to the qSupported
4087 struct protocol_feature
4089 /* The name of this protocol feature. */
4092 /* The default for this protocol feature. */
4093 enum packet_support default_support;
4095 /* The function to call when this feature is reported, or after
4096 qSupported processing if the feature is not supported.
4097 The first argument points to this structure. The second
4098 argument indicates whether the packet requested support be
4099 enabled, disabled, or probed (or the default, if this function
4100 is being called at the end of processing and this feature was
4101 not reported). The third argument may be NULL; if not NULL, it
4102 is a NUL-terminated string taken from the packet following
4103 this feature's name and an equals sign. */
4104 void (*func) (const struct protocol_feature *, enum packet_support,
4107 /* The corresponding packet for this feature. Only used if
4108 FUNC is remote_supported_packet. */
4113 remote_supported_packet (const struct protocol_feature *feature,
4114 enum packet_support support,
4115 const char *argument)
4119 warning (_("Remote qSupported response supplied an unexpected value for"
4120 " \"%s\"."), feature->name);
4124 remote_protocol_packets[feature->packet].support = support;
4128 remote_packet_size (const struct protocol_feature *feature,
4129 enum packet_support support, const char *value)
4131 struct remote_state *rs = get_remote_state ();
4136 if (support != PACKET_ENABLE)
4139 if (value == NULL || *value == '\0')
4141 warning (_("Remote target reported \"%s\" without a size."),
4147 packet_size = strtol (value, &value_end, 16);
4148 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4150 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4151 feature->name, value);
4155 if (packet_size > MAX_REMOTE_PACKET_SIZE)
4157 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
4158 packet_size, MAX_REMOTE_PACKET_SIZE);
4159 packet_size = MAX_REMOTE_PACKET_SIZE;
4162 /* Record the new maximum packet size. */
4163 rs->explicit_packet_size = packet_size;
4166 static const struct protocol_feature remote_protocol_features[] = {
4167 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4168 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4169 PACKET_qXfer_auxv },
4170 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4171 PACKET_qXfer_exec_file },
4172 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4173 PACKET_qXfer_features },
4174 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4175 PACKET_qXfer_libraries },
4176 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4177 PACKET_qXfer_libraries_svr4 },
4178 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4179 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4180 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4181 PACKET_qXfer_memory_map },
4182 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4183 PACKET_qXfer_spu_read },
4184 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4185 PACKET_qXfer_spu_write },
4186 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4187 PACKET_qXfer_osdata },
4188 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4189 PACKET_qXfer_threads },
4190 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4191 PACKET_qXfer_traceframe_info },
4192 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4193 PACKET_QPassSignals },
4194 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4195 PACKET_QProgramSignals },
4196 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4197 PACKET_QStartNoAckMode },
4198 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4199 PACKET_multiprocess_feature },
4200 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4201 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4202 PACKET_qXfer_siginfo_read },
4203 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4204 PACKET_qXfer_siginfo_write },
4205 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4206 PACKET_ConditionalTracepoints },
4207 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4208 PACKET_ConditionalBreakpoints },
4209 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4210 PACKET_BreakpointCommands },
4211 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4212 PACKET_FastTracepoints },
4213 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4214 PACKET_StaticTracepoints },
4215 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4216 PACKET_InstallInTrace},
4217 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4218 PACKET_DisconnectedTracing_feature },
4219 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4221 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4223 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4224 PACKET_TracepointSource },
4225 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4227 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4228 PACKET_EnableDisableTracepoints_feature },
4229 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4230 PACKET_qXfer_fdpic },
4231 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4233 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4234 PACKET_QDisableRandomization },
4235 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4236 { "QTBuffer:size", PACKET_DISABLE,
4237 remote_supported_packet, PACKET_QTBuffer_size},
4238 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4239 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4240 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4241 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4242 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4243 PACKET_qXfer_btrace },
4244 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4245 PACKET_qXfer_btrace_conf },
4246 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4247 PACKET_Qbtrace_conf_bts_size },
4248 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4249 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4250 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4251 PACKET_fork_event_feature },
4252 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4253 PACKET_vfork_event_feature },
4254 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4255 PACKET_Qbtrace_conf_pt_size }
4258 static char *remote_support_xml;
4260 /* Register string appended to "xmlRegisters=" in qSupported query. */
4263 register_remote_support_xml (const char *xml)
4265 #if defined(HAVE_LIBEXPAT)
4266 if (remote_support_xml == NULL)
4267 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4270 char *copy = xstrdup (remote_support_xml + 13);
4271 char *p = strtok (copy, ",");
4275 if (strcmp (p, xml) == 0)
4282 while ((p = strtok (NULL, ",")) != NULL);
4285 remote_support_xml = reconcat (remote_support_xml,
4286 remote_support_xml, ",", xml,
4293 remote_query_supported_append (char *msg, const char *append)
4296 return reconcat (msg, msg, ";", append, (char *) NULL);
4298 return xstrdup (append);
4302 remote_query_supported (void)
4304 struct remote_state *rs = get_remote_state ();
4307 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4309 /* The packet support flags are handled differently for this packet
4310 than for most others. We treat an error, a disabled packet, and
4311 an empty response identically: any features which must be reported
4312 to be used will be automatically disabled. An empty buffer
4313 accomplishes this, since that is also the representation for a list
4314 containing no features. */
4317 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4320 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4322 q = remote_query_supported_append (q, "multiprocess+");
4324 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4325 q = remote_query_supported_append (q, "swbreak+");
4326 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4327 q = remote_query_supported_append (q, "hwbreak+");
4329 if (remote_support_xml)
4330 q = remote_query_supported_append (q, remote_support_xml);
4332 q = remote_query_supported_append (q, "qRelocInsn+");
4336 if (packet_set_cmd_state (PACKET_fork_event_feature)
4337 != AUTO_BOOLEAN_FALSE)
4338 q = remote_query_supported_append (q, "fork-events+");
4339 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4340 != AUTO_BOOLEAN_FALSE)
4341 q = remote_query_supported_append (q, "vfork-events+");
4344 q = reconcat (q, "qSupported:", q, (char *) NULL);
4347 do_cleanups (old_chain);
4349 getpkt (&rs->buf, &rs->buf_size, 0);
4351 /* If an error occured, warn, but do not return - just reset the
4352 buffer to empty and go on to disable features. */
4353 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4356 warning (_("Remote failure reply: %s"), rs->buf);
4361 memset (seen, 0, sizeof (seen));
4366 enum packet_support is_supported;
4367 char *p, *end, *name_end, *value;
4369 /* First separate out this item from the rest of the packet. If
4370 there's another item after this, we overwrite the separator
4371 (terminated strings are much easier to work with). */
4373 end = strchr (p, ';');
4376 end = p + strlen (p);
4386 warning (_("empty item in \"qSupported\" response"));
4391 name_end = strchr (p, '=');
4394 /* This is a name=value entry. */
4395 is_supported = PACKET_ENABLE;
4396 value = name_end + 1;
4405 is_supported = PACKET_ENABLE;
4409 is_supported = PACKET_DISABLE;
4413 is_supported = PACKET_SUPPORT_UNKNOWN;
4417 warning (_("unrecognized item \"%s\" "
4418 "in \"qSupported\" response"), p);
4424 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4425 if (strcmp (remote_protocol_features[i].name, p) == 0)
4427 const struct protocol_feature *feature;
4430 feature = &remote_protocol_features[i];
4431 feature->func (feature, is_supported, value);
4436 /* If we increased the packet size, make sure to increase the global
4437 buffer size also. We delay this until after parsing the entire
4438 qSupported packet, because this is the same buffer we were
4440 if (rs->buf_size < rs->explicit_packet_size)
4442 rs->buf_size = rs->explicit_packet_size;
4443 rs->buf = xrealloc (rs->buf, rs->buf_size);
4446 /* Handle the defaults for unmentioned features. */
4447 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4450 const struct protocol_feature *feature;
4452 feature = &remote_protocol_features[i];
4453 feature->func (feature, feature->default_support, NULL);
4457 /* Remove any of the remote.c targets from target stack. Upper targets depend
4458 on it so remove them first. */
4461 remote_unpush_target (void)
4463 pop_all_targets_above (process_stratum - 1);
4467 remote_open_1 (const char *name, int from_tty,
4468 struct target_ops *target, int extended_p)
4470 struct remote_state *rs = get_remote_state ();
4473 error (_("To open a remote debug connection, you need to specify what\n"
4474 "serial device is attached to the remote system\n"
4475 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4477 /* See FIXME above. */
4478 if (!target_async_permitted)
4479 wait_forever_enabled_p = 1;
4481 /* If we're connected to a running target, target_preopen will kill it.
4482 Ask this question first, before target_preopen has a chance to kill
4484 if (rs->remote_desc != NULL && !have_inferiors ())
4487 && !query (_("Already connected to a remote target. Disconnect? ")))
4488 error (_("Still connected."));
4491 /* Here the possibly existing remote target gets unpushed. */
4492 target_preopen (from_tty);
4494 /* Make sure we send the passed signals list the next time we resume. */
4495 xfree (rs->last_pass_packet);
4496 rs->last_pass_packet = NULL;
4498 /* Make sure we send the program signals list the next time we
4500 xfree (rs->last_program_signals_packet);
4501 rs->last_program_signals_packet = NULL;
4503 remote_fileio_reset ();
4504 reopen_exec_file ();
4507 rs->remote_desc = remote_serial_open (name);
4508 if (!rs->remote_desc)
4509 perror_with_name (name);
4511 if (baud_rate != -1)
4513 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4515 /* The requested speed could not be set. Error out to
4516 top level after closing remote_desc. Take care to
4517 set remote_desc to NULL to avoid closing remote_desc
4519 serial_close (rs->remote_desc);
4520 rs->remote_desc = NULL;
4521 perror_with_name (name);
4525 serial_setparity (rs->remote_desc, serial_parity);
4526 serial_raw (rs->remote_desc);
4528 /* If there is something sitting in the buffer we might take it as a
4529 response to a command, which would be bad. */
4530 serial_flush_input (rs->remote_desc);
4534 puts_filtered ("Remote debugging using ");
4535 puts_filtered (name);
4536 puts_filtered ("\n");
4538 push_target (target); /* Switch to using remote target now. */
4540 /* Register extra event sources in the event loop. */
4541 remote_async_inferior_event_token
4542 = create_async_event_handler (remote_async_inferior_event_handler,
4544 rs->notif_state = remote_notif_state_allocate ();
4546 /* Reset the target state; these things will be queried either by
4547 remote_query_supported or as they are needed. */
4548 reset_all_packet_configs_support ();
4549 rs->cached_wait_status = 0;
4550 rs->explicit_packet_size = 0;
4552 rs->extended = extended_p;
4553 rs->waiting_for_stop_reply = 0;
4554 rs->ctrlc_pending_p = 0;
4556 rs->general_thread = not_sent_ptid;
4557 rs->continue_thread = not_sent_ptid;
4558 rs->remote_traceframe_number = -1;
4560 /* Probe for ability to use "ThreadInfo" query, as required. */
4561 rs->use_threadinfo_query = 1;
4562 rs->use_threadextra_query = 1;
4564 if (target_async_permitted)
4566 /* With this target we start out by owning the terminal. */
4567 remote_async_terminal_ours_p = 1;
4569 /* FIXME: cagney/1999-09-23: During the initial connection it is
4570 assumed that the target is already ready and able to respond to
4571 requests. Unfortunately remote_start_remote() eventually calls
4572 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4573 around this. Eventually a mechanism that allows
4574 wait_for_inferior() to expect/get timeouts will be
4576 wait_forever_enabled_p = 0;
4579 /* First delete any symbols previously loaded from shared libraries. */
4580 no_shared_libraries (NULL, 0);
4583 init_thread_list ();
4585 /* Start the remote connection. If error() or QUIT, discard this
4586 target (we'd otherwise be in an inconsistent state) and then
4587 propogate the error on up the exception chain. This ensures that
4588 the caller doesn't stumble along blindly assuming that the
4589 function succeeded. The CLI doesn't have this problem but other
4590 UI's, such as MI do.
4592 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4593 this function should return an error indication letting the
4594 caller restore the previous state. Unfortunately the command
4595 ``target remote'' is directly wired to this function making that
4596 impossible. On a positive note, the CLI side of this problem has
4597 been fixed - the function set_cmd_context() makes it possible for
4598 all the ``target ....'' commands to share a common callback
4599 function. See cli-dump.c. */
4604 remote_start_remote (from_tty, target, extended_p);
4606 CATCH (ex, RETURN_MASK_ALL)
4608 /* Pop the partially set up target - unless something else did
4609 already before throwing the exception. */
4610 if (rs->remote_desc != NULL)
4611 remote_unpush_target ();
4612 if (target_async_permitted)
4613 wait_forever_enabled_p = 1;
4614 throw_exception (ex);
4619 remote_btrace_reset ();
4621 if (target_async_permitted)
4622 wait_forever_enabled_p = 1;
4625 /* Detach the specified process. */
4628 remote_detach_pid (int pid)
4630 struct remote_state *rs = get_remote_state ();
4632 if (remote_multi_process_p (rs))
4633 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4635 strcpy (rs->buf, "D");
4638 getpkt (&rs->buf, &rs->buf_size, 0);
4640 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4642 else if (rs->buf[0] == '\0')
4643 error (_("Remote doesn't know how to detach"));
4645 error (_("Can't detach process."));
4648 /* This detaches a program to which we previously attached, using
4649 inferior_ptid to identify the process. After this is done, GDB
4650 can be used to debug some other program. We better not have left
4651 any breakpoints in the target program or it'll die when it hits
4655 remote_detach_1 (const char *args, int from_tty)
4657 int pid = ptid_get_pid (inferior_ptid);
4658 struct remote_state *rs = get_remote_state ();
4659 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4663 error (_("Argument given to \"detach\" when remotely debugging."));
4665 if (!target_has_execution)
4666 error (_("No process to detach from."));
4670 char *exec_file = get_exec_file (0);
4671 if (exec_file == NULL)
4673 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4674 target_pid_to_str (pid_to_ptid (pid)));
4675 gdb_flush (gdb_stdout);
4678 /* Tell the remote target to detach. */
4679 remote_detach_pid (pid);
4681 if (from_tty && !rs->extended)
4682 puts_filtered (_("Ending remote debugging.\n"));
4684 /* Check to see if we are detaching a fork parent. Note that if we
4685 are detaching a fork child, tp == NULL. */
4686 is_fork_parent = (tp != NULL
4687 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4689 /* If doing detach-on-fork, we don't mourn, because that will delete
4690 breakpoints that should be available for the followed inferior. */
4691 if (!is_fork_parent)
4692 target_mourn_inferior ();
4695 inferior_ptid = null_ptid;
4696 detach_inferior (pid);
4701 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4703 remote_detach_1 (args, from_tty);
4707 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4709 remote_detach_1 (args, from_tty);
4712 /* Target follow-fork function for remote targets. On entry, and
4713 at return, the current inferior is the fork parent.
4715 Note that although this is currently only used for extended-remote,
4716 it is named remote_follow_fork in anticipation of using it for the
4717 remote target as well. */
4720 remote_follow_fork (struct target_ops *ops, int follow_child,
4723 struct remote_state *rs = get_remote_state ();
4724 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
4726 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4727 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
4729 /* When following the parent and detaching the child, we detach
4730 the child here. For the case of following the child and
4731 detaching the parent, the detach is done in the target-
4732 independent follow fork code in infrun.c. We can't use
4733 target_detach when detaching an unfollowed child because
4734 the client side doesn't know anything about the child. */
4735 if (detach_fork && !follow_child)
4737 /* Detach the fork child. */
4741 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4742 child_pid = ptid_get_pid (child_ptid);
4744 remote_detach_pid (child_pid);
4745 detach_inferior (child_pid);
4751 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4754 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4757 error (_("Argument given to \"disconnect\" when remotely debugging."));
4759 /* Make sure we unpush even the extended remote targets; mourn
4760 won't do it. So call remote_mourn directly instead of
4761 target_mourn_inferior. */
4762 remote_mourn (target);
4765 puts_filtered ("Ending remote debugging.\n");
4768 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4769 be chatty about it. */
4772 extended_remote_attach (struct target_ops *target, const char *args,
4775 struct remote_state *rs = get_remote_state ();
4777 char *wait_status = NULL;
4779 pid = parse_pid_to_attach (args);
4781 /* Remote PID can be freely equal to getpid, do not check it here the same
4782 way as in other targets. */
4784 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4785 error (_("This target does not support attaching to a process"));
4789 char *exec_file = get_exec_file (0);
4792 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4793 target_pid_to_str (pid_to_ptid (pid)));
4795 printf_unfiltered (_("Attaching to %s\n"),
4796 target_pid_to_str (pid_to_ptid (pid)));
4798 gdb_flush (gdb_stdout);
4801 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4803 getpkt (&rs->buf, &rs->buf_size, 0);
4805 switch (packet_ok (rs->buf,
4806 &remote_protocol_packets[PACKET_vAttach]))
4811 /* Save the reply for later. */
4812 wait_status = alloca (strlen (rs->buf) + 1);
4813 strcpy (wait_status, rs->buf);
4815 else if (strcmp (rs->buf, "OK") != 0)
4816 error (_("Attaching to %s failed with: %s"),
4817 target_pid_to_str (pid_to_ptid (pid)),
4820 case PACKET_UNKNOWN:
4821 error (_("This target does not support attaching to a process"));
4823 error (_("Attaching to %s failed"),
4824 target_pid_to_str (pid_to_ptid (pid)));
4827 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
4829 inferior_ptid = pid_to_ptid (pid);
4833 struct thread_info *thread;
4835 /* Get list of threads. */
4836 remote_update_thread_list (target);
4838 thread = first_thread_of_process (pid);
4840 inferior_ptid = thread->ptid;
4842 inferior_ptid = pid_to_ptid (pid);
4844 /* Invalidate our notion of the remote current thread. */
4845 record_currthread (rs, minus_one_ptid);
4849 /* Now, if we have thread information, update inferior_ptid. */
4850 inferior_ptid = remote_current_thread (inferior_ptid);
4852 /* Add the main thread to the thread list. */
4853 add_thread_silent (inferior_ptid);
4856 /* Next, if the target can specify a description, read it. We do
4857 this before anything involving memory or registers. */
4858 target_find_description ();
4862 /* Use the previously fetched status. */
4863 gdb_assert (wait_status != NULL);
4865 if (target_can_async_p ())
4867 struct notif_event *reply
4868 = remote_notif_parse (¬if_client_stop, wait_status);
4870 push_stop_reply ((struct stop_reply *) reply);
4876 gdb_assert (wait_status != NULL);
4877 strcpy (rs->buf, wait_status);
4878 rs->cached_wait_status = 1;
4882 gdb_assert (wait_status == NULL);
4885 /* Implementation of the to_post_attach method. */
4888 extended_remote_post_attach (struct target_ops *ops, int pid)
4890 /* In certain cases GDB might not have had the chance to start
4891 symbol lookup up until now. This could happen if the debugged
4892 binary is not using shared libraries, the vsyscall page is not
4893 present (on Linux) and the binary itself hadn't changed since the
4894 debugging process was started. */
4895 if (symfile_objfile != NULL)
4896 remote_check_symbols();
4900 /* Check for the availability of vCont. This function should also check
4904 remote_vcont_probe (struct remote_state *rs)
4908 strcpy (rs->buf, "vCont?");
4910 getpkt (&rs->buf, &rs->buf_size, 0);
4913 /* Make sure that the features we assume are supported. */
4914 if (startswith (buf, "vCont"))
4917 int support_s, support_S, support_c, support_C;
4923 rs->supports_vCont.t = 0;
4924 rs->supports_vCont.r = 0;
4925 while (p && *p == ';')
4928 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4930 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4932 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4934 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4936 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4937 rs->supports_vCont.t = 1;
4938 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4939 rs->supports_vCont.r = 1;
4941 p = strchr (p, ';');
4944 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4945 BUF will make packet_ok disable the packet. */
4946 if (!support_s || !support_S || !support_c || !support_C)
4950 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4953 /* Helper function for building "vCont" resumptions. Write a
4954 resumption to P. ENDP points to one-passed-the-end of the buffer
4955 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4956 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4957 resumed thread should be single-stepped and/or signalled. If PTID
4958 equals minus_one_ptid, then all threads are resumed; if PTID
4959 represents a process, then all threads of the process are resumed;
4960 the thread to be stepped and/or signalled is given in the global
4964 append_resumption (char *p, char *endp,
4965 ptid_t ptid, int step, enum gdb_signal siggnal)
4967 struct remote_state *rs = get_remote_state ();
4969 if (step && siggnal != GDB_SIGNAL_0)
4970 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4972 /* GDB is willing to range step. */
4973 && use_range_stepping
4974 /* Target supports range stepping. */
4975 && rs->supports_vCont.r
4976 /* We don't currently support range stepping multiple
4977 threads with a wildcard (though the protocol allows it,
4978 so stubs shouldn't make an active effort to forbid
4980 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4982 struct thread_info *tp;
4984 if (ptid_equal (ptid, minus_one_ptid))
4986 /* If we don't know about the target thread's tid, then
4987 we're resuming magic_null_ptid (see caller). */
4988 tp = find_thread_ptid (magic_null_ptid);
4991 tp = find_thread_ptid (ptid);
4992 gdb_assert (tp != NULL);
4994 if (tp->control.may_range_step)
4996 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4998 p += xsnprintf (p, endp - p, ";r%s,%s",
4999 phex_nz (tp->control.step_range_start,
5001 phex_nz (tp->control.step_range_end,
5005 p += xsnprintf (p, endp - p, ";s");
5008 p += xsnprintf (p, endp - p, ";s");
5009 else if (siggnal != GDB_SIGNAL_0)
5010 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5012 p += xsnprintf (p, endp - p, ";c");
5014 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5018 /* All (-1) threads of process. */
5019 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5021 p += xsnprintf (p, endp - p, ":");
5022 p = write_ptid (p, endp, nptid);
5024 else if (!ptid_equal (ptid, minus_one_ptid))
5026 p += xsnprintf (p, endp - p, ":");
5027 p = write_ptid (p, endp, ptid);
5033 /* Append a vCont continue-with-signal action for threads that have a
5034 non-zero stop signal. */
5037 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5039 struct thread_info *thread;
5041 ALL_NON_EXITED_THREADS (thread)
5042 if (ptid_match (thread->ptid, ptid)
5043 && !ptid_equal (inferior_ptid, thread->ptid)
5044 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5046 p = append_resumption (p, endp, thread->ptid,
5047 0, thread->suspend.stop_signal);
5048 thread->suspend.stop_signal = GDB_SIGNAL_0;
5054 /* Resume the remote inferior by using a "vCont" packet. The thread
5055 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5056 resumed thread should be single-stepped and/or signalled. If PTID
5057 equals minus_one_ptid, then all threads are resumed; the thread to
5058 be stepped and/or signalled is given in the global INFERIOR_PTID.
5059 This function returns non-zero iff it resumes the inferior.
5061 This function issues a strict subset of all possible vCont commands at the
5065 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5067 struct remote_state *rs = get_remote_state ();
5071 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5072 remote_vcont_probe (rs);
5074 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5078 endp = rs->buf + get_remote_packet_size ();
5080 /* If we could generate a wider range of packets, we'd have to worry
5081 about overflowing BUF. Should there be a generic
5082 "multi-part-packet" packet? */
5084 p += xsnprintf (p, endp - p, "vCont");
5086 if (ptid_equal (ptid, magic_null_ptid))
5088 /* MAGIC_NULL_PTID means that we don't have any active threads,
5089 so we don't have any TID numbers the inferior will
5090 understand. Make sure to only send forms that do not specify
5092 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5094 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5096 /* Resume all threads (of all processes, or of a single
5097 process), with preference for INFERIOR_PTID. This assumes
5098 inferior_ptid belongs to the set of all threads we are about
5100 if (step || siggnal != GDB_SIGNAL_0)
5102 /* Step inferior_ptid, with or without signal. */
5103 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5106 /* Also pass down any pending signaled resumption for other
5107 threads not the current. */
5108 p = append_pending_thread_resumptions (p, endp, ptid);
5110 /* And continue others without a signal. */
5111 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5115 /* Scheduler locking; resume only PTID. */
5116 append_resumption (p, endp, ptid, step, siggnal);
5119 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5124 /* In non-stop, the stub replies to vCont with "OK". The stop
5125 reply will be reported asynchronously by means of a `%Stop'
5127 getpkt (&rs->buf, &rs->buf_size, 0);
5128 if (strcmp (rs->buf, "OK") != 0)
5129 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5135 /* Tell the remote machine to resume. */
5138 remote_resume (struct target_ops *ops,
5139 ptid_t ptid, int step, enum gdb_signal siggnal)
5141 struct remote_state *rs = get_remote_state ();
5144 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5145 (explained in remote-notif.c:handle_notification) so
5146 remote_notif_process is not called. We need find a place where
5147 it is safe to start a 'vNotif' sequence. It is good to do it
5148 before resuming inferior, because inferior was stopped and no RSP
5149 traffic at that moment. */
5151 remote_notif_process (rs->notif_state, ¬if_client_stop);
5153 rs->last_sent_signal = siggnal;
5154 rs->last_sent_step = step;
5156 /* The vCont packet doesn't need to specify threads via Hc. */
5157 /* No reverse support (yet) for vCont. */
5158 if (execution_direction != EXEC_REVERSE)
5159 if (remote_vcont_resume (ptid, step, siggnal))
5162 /* All other supported resume packets do use Hc, so set the continue
5164 if (ptid_equal (ptid, minus_one_ptid))
5165 set_continue_thread (any_thread_ptid);
5167 set_continue_thread (ptid);
5170 if (execution_direction == EXEC_REVERSE)
5172 /* We don't pass signals to the target in reverse exec mode. */
5173 if (info_verbose && siggnal != GDB_SIGNAL_0)
5174 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5177 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5178 error (_("Remote reverse-step not supported."));
5179 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5180 error (_("Remote reverse-continue not supported."));
5182 strcpy (buf, step ? "bs" : "bc");
5184 else if (siggnal != GDB_SIGNAL_0)
5186 buf[0] = step ? 'S' : 'C';
5187 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5188 buf[2] = tohex (((int) siggnal) & 0xf);
5192 strcpy (buf, step ? "s" : "c");
5197 /* We are about to start executing the inferior, let's register it
5198 with the event loop. NOTE: this is the one place where all the
5199 execution commands end up. We could alternatively do this in each
5200 of the execution commands in infcmd.c. */
5201 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5202 into infcmd.c in order to allow inferior function calls to work
5203 NOT asynchronously. */
5204 if (target_can_async_p ())
5207 /* We've just told the target to resume. The remote server will
5208 wait for the inferior to stop, and then send a stop reply. In
5209 the mean time, we can't start another command/query ourselves
5210 because the stub wouldn't be ready to process it. This applies
5211 only to the base all-stop protocol, however. In non-stop (which
5212 only supports vCont), the stub replies with an "OK", and is
5213 immediate able to process further serial input. */
5215 rs->waiting_for_stop_reply = 1;
5219 /* Set up the signal handler for SIGINT, while the target is
5220 executing, ovewriting the 'regular' SIGINT signal handler. */
5222 async_initialize_sigint_signal_handler (void)
5224 signal (SIGINT, async_handle_remote_sigint);
5227 /* Signal handler for SIGINT, while the target is executing. */
5229 async_handle_remote_sigint (int sig)
5231 signal (sig, async_handle_remote_sigint_twice);
5232 /* Note we need to go through gdb_call_async_signal_handler in order
5233 to wake up the event loop on Windows. */
5234 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5237 /* Signal handler for SIGINT, installed after SIGINT has already been
5238 sent once. It will take effect the second time that the user sends
5241 async_handle_remote_sigint_twice (int sig)
5243 signal (sig, async_handle_remote_sigint);
5244 /* See note in async_handle_remote_sigint. */
5245 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5248 /* Perform the real interruption of the target execution, in response
5251 async_remote_interrupt (gdb_client_data arg)
5254 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5256 target_stop (inferior_ptid);
5259 /* Perform interrupt, if the first attempt did not succeed. Just give
5260 up on the target alltogether. */
5262 async_remote_interrupt_twice (gdb_client_data arg)
5265 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5270 /* Reinstall the usual SIGINT handlers, after the target has
5273 async_cleanup_sigint_signal_handler (void *dummy)
5275 signal (SIGINT, handle_sigint);
5278 /* Send ^C to target to halt it. Target will respond, and send us a
5280 static void (*ofunc) (int);
5282 /* The command line interface's interrupt routine. This function is installed
5283 as a signal handler for SIGINT. The first time a user requests an
5284 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5285 response from the target (it didn't stop when the user requested it),
5286 we ask the user if he'd like to detach from the target. */
5289 sync_remote_interrupt (int signo)
5291 /* If this doesn't work, try more severe steps. */
5292 signal (signo, sync_remote_interrupt_twice);
5294 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5297 /* The user typed ^C twice. */
5300 sync_remote_interrupt_twice (int signo)
5302 signal (signo, ofunc);
5303 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5304 signal (signo, sync_remote_interrupt);
5307 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5308 thread, all threads of a remote process, or all threads of all
5312 remote_stop_ns (ptid_t ptid)
5314 struct remote_state *rs = get_remote_state ();
5316 char *endp = rs->buf + get_remote_packet_size ();
5318 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5319 remote_vcont_probe (rs);
5321 if (!rs->supports_vCont.t)
5322 error (_("Remote server does not support stopping threads"));
5324 if (ptid_equal (ptid, minus_one_ptid)
5325 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5326 p += xsnprintf (p, endp - p, "vCont;t");
5331 p += xsnprintf (p, endp - p, "vCont;t:");
5333 if (ptid_is_pid (ptid))
5334 /* All (-1) threads of process. */
5335 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5338 /* Small optimization: if we already have a stop reply for
5339 this thread, no use in telling the stub we want this
5341 if (peek_stop_reply (ptid))
5347 write_ptid (p, endp, nptid);
5350 /* In non-stop, we get an immediate OK reply. The stop reply will
5351 come in asynchronously by notification. */
5353 getpkt (&rs->buf, &rs->buf_size, 0);
5354 if (strcmp (rs->buf, "OK") != 0)
5355 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5358 /* All-stop version of target_interrupt. Sends a break or a ^C to
5359 interrupt the remote target. It is undefined which thread of which
5360 process reports the interrupt. */
5363 remote_interrupt_as (ptid_t ptid)
5365 struct remote_state *rs = get_remote_state ();
5367 rs->ctrlc_pending_p = 1;
5369 /* If the inferior is stopped already, but the core didn't know
5370 about it yet, just ignore the request. The cached wait status
5371 will be collected in remote_wait. */
5372 if (rs->cached_wait_status)
5375 /* Send interrupt_sequence to remote target. */
5376 send_interrupt_sequence ();
5379 /* Implement the to_stop function for the remote targets. */
5382 remote_stop (struct target_ops *self, ptid_t ptid)
5385 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5388 remote_stop_ns (ptid);
5391 /* We don't currently have a way to transparently pause the
5392 remote target in all-stop mode. Interrupt it instead. */
5393 remote_interrupt_as (ptid);
5397 /* Implement the to_interrupt function for the remote targets. */
5400 remote_interrupt (struct target_ops *self, ptid_t ptid)
5403 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5407 /* We don't currently have a way to ^C the remote target in
5408 non-stop mode. Stop it (with no signal) instead. */
5409 remote_stop_ns (ptid);
5412 remote_interrupt_as (ptid);
5415 /* Ask the user what to do when an interrupt is received. */
5418 interrupt_query (void)
5420 target_terminal_ours ();
5422 if (target_is_async_p ())
5424 signal (SIGINT, handle_sigint);
5429 if (query (_("Interrupted while waiting for the program.\n\
5430 Give up (and stop debugging it)? ")))
5432 remote_unpush_target ();
5437 target_terminal_inferior ();
5440 /* Enable/disable target terminal ownership. Most targets can use
5441 terminal groups to control terminal ownership. Remote targets are
5442 different in that explicit transfer of ownership to/from GDB/target
5446 remote_terminal_inferior (struct target_ops *self)
5448 if (!target_async_permitted)
5449 /* Nothing to do. */
5452 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5453 idempotent. The event-loop GDB talking to an asynchronous target
5454 with a synchronous command calls this function from both
5455 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5456 transfer the terminal to the target when it shouldn't this guard
5458 if (!remote_async_terminal_ours_p)
5460 delete_file_handler (input_fd);
5461 remote_async_terminal_ours_p = 0;
5462 async_initialize_sigint_signal_handler ();
5463 /* NOTE: At this point we could also register our selves as the
5464 recipient of all input. Any characters typed could then be
5465 passed on down to the target. */
5469 remote_terminal_ours (struct target_ops *self)
5471 if (!target_async_permitted)
5472 /* Nothing to do. */
5475 /* See FIXME in remote_terminal_inferior. */
5476 if (remote_async_terminal_ours_p)
5478 async_cleanup_sigint_signal_handler (NULL);
5479 add_file_handler (input_fd, stdin_event_handler, 0);
5480 remote_async_terminal_ours_p = 1;
5484 remote_console_output (char *msg)
5488 for (p = msg; p[0] && p[1]; p += 2)
5491 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5495 fputs_unfiltered (tb, gdb_stdtarg);
5497 gdb_flush (gdb_stdtarg);
5500 typedef struct cached_reg
5503 gdb_byte data[MAX_REGISTER_SIZE];
5506 DEF_VEC_O(cached_reg_t);
5508 typedef struct stop_reply
5510 struct notif_event base;
5512 /* The identifier of the thread about this event */
5515 /* The remote state this event is associated with. When the remote
5516 connection, represented by a remote_state object, is closed,
5517 all the associated stop_reply events should be released. */
5518 struct remote_state *rs;
5520 struct target_waitstatus ws;
5522 /* Expedited registers. This makes remote debugging a bit more
5523 efficient for those targets that provide critical registers as
5524 part of their normal status mechanism (as another roundtrip to
5525 fetch them is avoided). */
5526 VEC(cached_reg_t) *regcache;
5528 enum target_stop_reason stop_reason;
5530 CORE_ADDR watch_data_address;
5535 DECLARE_QUEUE_P (stop_reply_p);
5536 DEFINE_QUEUE_P (stop_reply_p);
5537 /* The list of already fetched and acknowledged stop events. This
5538 queue is used for notification Stop, and other notifications
5539 don't need queue for their events, because the notification events
5540 of Stop can't be consumed immediately, so that events should be
5541 queued first, and be consumed by remote_wait_{ns,as} one per
5542 time. Other notifications can consume their events immediately,
5543 so queue is not needed for them. */
5544 static QUEUE (stop_reply_p) *stop_reply_queue;
5547 stop_reply_xfree (struct stop_reply *r)
5549 notif_event_xfree ((struct notif_event *) r);
5552 /* Return the length of the stop reply queue. */
5555 stop_reply_queue_length (void)
5557 return QUEUE_length (stop_reply_p, stop_reply_queue);
5561 remote_notif_stop_parse (struct notif_client *self, char *buf,
5562 struct notif_event *event)
5564 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5568 remote_notif_stop_ack (struct notif_client *self, char *buf,
5569 struct notif_event *event)
5571 struct stop_reply *stop_reply = (struct stop_reply *) event;
5574 putpkt ((char *) self->ack_command);
5576 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5577 /* We got an unknown stop reply. */
5578 error (_("Unknown stop reply"));
5580 push_stop_reply (stop_reply);
5584 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5586 /* We can't get pending events in remote_notif_process for
5587 notification stop, and we have to do this in remote_wait_ns
5588 instead. If we fetch all queued events from stub, remote stub
5589 may exit and we have no chance to process them back in
5591 mark_async_event_handler (remote_async_inferior_event_token);
5596 stop_reply_dtr (struct notif_event *event)
5598 struct stop_reply *r = (struct stop_reply *) event;
5600 VEC_free (cached_reg_t, r->regcache);
5603 static struct notif_event *
5604 remote_notif_stop_alloc_reply (void)
5606 struct notif_event *r
5607 = (struct notif_event *) XNEW (struct stop_reply);
5609 r->dtr = stop_reply_dtr;
5614 /* A client of notification Stop. */
5616 struct notif_client notif_client_stop =
5620 remote_notif_stop_parse,
5621 remote_notif_stop_ack,
5622 remote_notif_stop_can_get_pending_events,
5623 remote_notif_stop_alloc_reply,
5627 /* A parameter to pass data in and out. */
5629 struct queue_iter_param
5632 struct stop_reply *output;
5635 /* Determine if THREAD is a pending fork parent thread. ARG contains
5636 the pid of the process that owns the threads we want to check, or
5637 -1 if we want to check all threads. */
5640 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5643 if (ws->kind == TARGET_WAITKIND_FORKED
5644 || ws->kind == TARGET_WAITKIND_VFORKED)
5646 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5653 /* Check whether EVENT is a fork event, and if it is, remove the
5654 fork child from the context list passed in DATA. */
5657 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5658 QUEUE_ITER (stop_reply_p) *iter,
5662 struct queue_iter_param *param = data;
5663 struct threads_listing_context *context = param->input;
5665 if (event->ws.kind == TARGET_WAITKIND_FORKED
5666 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5668 threads_listing_context_remove (&event->ws, context);
5674 /* If CONTEXT contains any fork child threads that have not been
5675 reported yet, remove them from the CONTEXT list. If such a
5676 thread exists it is because we are stopped at a fork catchpoint
5677 and have not yet called follow_fork, which will set up the
5678 host-side data structures for the new process. */
5681 remove_new_fork_children (struct threads_listing_context *context)
5683 struct thread_info * thread;
5685 struct notif_client *notif = ¬if_client_stop;
5686 struct queue_iter_param param;
5688 /* For any threads stopped at a fork event, remove the corresponding
5689 fork child threads from the CONTEXT list. */
5690 ALL_NON_EXITED_THREADS (thread)
5692 struct target_waitstatus *ws = &thread->pending_follow;
5694 if (is_pending_fork_parent (ws, pid, thread->ptid))
5696 threads_listing_context_remove (ws, context);
5700 /* Check for any pending fork events (not reported or processed yet)
5701 in process PID and remove those fork child threads from the
5702 CONTEXT list as well. */
5703 remote_notif_get_pending_events (notif);
5704 param.input = context;
5705 param.output = NULL;
5706 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5707 remove_child_of_pending_fork, ¶m);
5710 /* Remove stop replies in the queue if its pid is equal to the given
5714 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5715 QUEUE_ITER (stop_reply_p) *iter,
5719 struct queue_iter_param *param = data;
5720 struct inferior *inf = param->input;
5722 if (ptid_get_pid (event->ptid) == inf->pid)
5724 stop_reply_xfree (event);
5725 QUEUE_remove_elem (stop_reply_p, q, iter);
5731 /* Discard all pending stop replies of inferior INF. */
5734 discard_pending_stop_replies (struct inferior *inf)
5737 struct queue_iter_param param;
5738 struct stop_reply *reply;
5739 struct remote_state *rs = get_remote_state ();
5740 struct remote_notif_state *rns = rs->notif_state;
5742 /* This function can be notified when an inferior exists. When the
5743 target is not remote, the notification state is NULL. */
5744 if (rs->remote_desc == NULL)
5747 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5749 /* Discard the in-flight notification. */
5750 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5752 stop_reply_xfree (reply);
5753 rns->pending_event[notif_client_stop.id] = NULL;
5757 param.output = NULL;
5758 /* Discard the stop replies we have already pulled with
5760 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5761 remove_stop_reply_for_inferior, ¶m);
5764 /* If its remote state is equal to the given remote state,
5765 remove EVENT from the stop reply queue. */
5768 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5769 QUEUE_ITER (stop_reply_p) *iter,
5773 struct queue_iter_param *param = data;
5774 struct remote_state *rs = param->input;
5776 if (event->rs == rs)
5778 stop_reply_xfree (event);
5779 QUEUE_remove_elem (stop_reply_p, q, iter);
5785 /* Discard the stop replies for RS in stop_reply_queue. */
5788 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5790 struct queue_iter_param param;
5793 param.output = NULL;
5794 /* Discard the stop replies we have already pulled with
5796 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5797 remove_stop_reply_of_remote_state, ¶m);
5800 /* A parameter to pass data in and out. */
5803 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5804 QUEUE_ITER (stop_reply_p) *iter,
5808 struct queue_iter_param *param = data;
5809 ptid_t *ptid = param->input;
5811 if (ptid_match (event->ptid, *ptid))
5813 param->output = event;
5814 QUEUE_remove_elem (stop_reply_p, q, iter);
5821 /* Remove the first reply in 'stop_reply_queue' which matches
5824 static struct stop_reply *
5825 remote_notif_remove_queued_reply (ptid_t ptid)
5827 struct queue_iter_param param;
5829 param.input = &ptid;
5830 param.output = NULL;
5832 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5833 remote_notif_remove_once_on_match, ¶m);
5835 fprintf_unfiltered (gdb_stdlog,
5836 "notif: discard queued event: 'Stop' in %s\n",
5837 target_pid_to_str (ptid));
5839 return param.output;
5842 /* Look for a queued stop reply belonging to PTID. If one is found,
5843 remove it from the queue, and return it. Returns NULL if none is
5844 found. If there are still queued events left to process, tell the
5845 event loop to get back to target_wait soon. */
5847 static struct stop_reply *
5848 queued_stop_reply (ptid_t ptid)
5850 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5852 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5853 /* There's still at least an event left. */
5854 mark_async_event_handler (remote_async_inferior_event_token);
5859 /* Push a fully parsed stop reply in the stop reply queue. Since we
5860 know that we now have at least one queued event left to pass to the
5861 core side, tell the event loop to get back to target_wait soon. */
5864 push_stop_reply (struct stop_reply *new_event)
5866 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5869 fprintf_unfiltered (gdb_stdlog,
5870 "notif: push 'Stop' %s to queue %d\n",
5871 target_pid_to_str (new_event->ptid),
5872 QUEUE_length (stop_reply_p,
5875 mark_async_event_handler (remote_async_inferior_event_token);
5879 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5880 QUEUE_ITER (stop_reply_p) *iter,
5881 struct stop_reply *event,
5884 ptid_t *ptid = data;
5886 return !(ptid_equal (*ptid, event->ptid)
5887 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5890 /* Returns true if we have a stop reply for PTID. */
5893 peek_stop_reply (ptid_t ptid)
5895 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5896 stop_reply_match_ptid_and_ws, &ptid);
5899 /* Skip PACKET until the next semi-colon (or end of string). */
5902 skip_to_semicolon (char *p)
5904 while (*p != '\0' && *p != ';')
5909 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
5910 starting with P and ending with PEND matches PREFIX. */
5913 strprefix (const char *p, const char *pend, const char *prefix)
5915 for ( ; p < pend; p++, prefix++)
5918 return *prefix == '\0';
5921 /* Parse the stop reply in BUF. Either the function succeeds, and the
5922 result is stored in EVENT, or throws an error. */
5925 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5927 struct remote_arch_state *rsa = get_remote_arch_state ();
5931 event->ptid = null_ptid;
5932 event->rs = get_remote_state ();
5933 event->ws.kind = TARGET_WAITKIND_IGNORE;
5934 event->ws.value.integer = 0;
5935 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5936 event->regcache = NULL;
5941 case 'T': /* Status with PC, SP, FP, ... */
5942 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5943 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5945 n... = register number
5946 r... = register contents
5949 p = &buf[3]; /* after Txx */
5955 p1 = strchr (p, ':');
5957 error (_("Malformed packet(a) (missing colon): %s\n\
5961 error (_("Malformed packet(a) (missing register number): %s\n\
5965 /* Some "registers" are actually extended stop information.
5966 Note if you're adding a new entry here: GDB 7.9 and
5967 earlier assume that all register "numbers" that start
5968 with an hex digit are real register numbers. Make sure
5969 the server only sends such a packet if it knows the
5970 client understands it. */
5972 if (strprefix (p, p1, "thread"))
5973 event->ptid = read_ptid (++p1, &p);
5974 else if (strprefix (p, p1, "watch")
5975 || strprefix (p, p1, "rwatch")
5976 || strprefix (p, p1, "awatch"))
5978 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
5979 p = unpack_varlen_hex (++p1, &addr);
5980 event->watch_data_address = (CORE_ADDR) addr;
5982 else if (strprefix (p, p1, "swbreak"))
5984 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5986 /* Make sure the stub doesn't forget to indicate support
5988 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5989 error (_("Unexpected swbreak stop reason"));
5991 /* The value part is documented as "must be empty",
5992 though we ignore it, in case we ever decide to make
5993 use of it in a backward compatible way. */
5994 p = skip_to_semicolon (p1 + 1);
5996 else if (strprefix (p, p1, "hwbreak"))
5998 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6000 /* Make sure the stub doesn't forget to indicate support
6002 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6003 error (_("Unexpected hwbreak stop reason"));
6006 p = skip_to_semicolon (p1 + 1);
6008 else if (strprefix (p, p1, "library"))
6010 event->ws.kind = TARGET_WAITKIND_LOADED;
6011 p = skip_to_semicolon (p1 + 1);
6013 else if (strprefix (p, p1, "replaylog"))
6015 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6016 /* p1 will indicate "begin" or "end", but it makes
6017 no difference for now, so ignore it. */
6018 p = skip_to_semicolon (p1 + 1);
6020 else if (strprefix (p, p1, "core"))
6024 p = unpack_varlen_hex (++p1, &c);
6027 else if (strprefix (p, p1, "fork"))
6029 event->ws.value.related_pid = read_ptid (++p1, &p);
6030 event->ws.kind = TARGET_WAITKIND_FORKED;
6032 else if (strprefix (p, p1, "vfork"))
6034 event->ws.value.related_pid = read_ptid (++p1, &p);
6035 event->ws.kind = TARGET_WAITKIND_VFORKED;
6037 else if (strprefix (p, p1, "vforkdone"))
6039 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6040 p = skip_to_semicolon (p1 + 1);
6047 /* Maybe a real ``P'' register number. */
6048 p_temp = unpack_varlen_hex (p, &pnum);
6049 /* If the first invalid character is the colon, we got a
6050 register number. Otherwise, it's an unknown stop
6054 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6055 cached_reg_t cached_reg;
6058 error (_("Remote sent bad register number %s: %s\n\
6060 hex_string (pnum), p, buf);
6062 cached_reg.num = reg->regnum;
6065 fieldsize = hex2bin (p, cached_reg.data,
6066 register_size (target_gdbarch (),
6069 if (fieldsize < register_size (target_gdbarch (),
6071 warning (_("Remote reply is too short: %s"), buf);
6073 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6077 /* Not a number. Silently skip unknown optional
6079 p = skip_to_semicolon (p1 + 1);
6084 error (_("Remote register badly formatted: %s\nhere: %s"),
6089 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6093 case 'S': /* Old style status, just signal only. */
6097 event->ws.kind = TARGET_WAITKIND_STOPPED;
6098 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6099 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6100 event->ws.value.sig = (enum gdb_signal) sig;
6102 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6105 case 'W': /* Target exited. */
6112 /* GDB used to accept only 2 hex chars here. Stubs should
6113 only send more if they detect GDB supports multi-process
6115 p = unpack_varlen_hex (&buf[1], &value);
6119 /* The remote process exited. */
6120 event->ws.kind = TARGET_WAITKIND_EXITED;
6121 event->ws.value.integer = value;
6125 /* The remote process exited with a signal. */
6126 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6127 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6128 event->ws.value.sig = (enum gdb_signal) value;
6130 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6133 /* If no process is specified, assume inferior_ptid. */
6134 pid = ptid_get_pid (inferior_ptid);
6143 else if (startswith (p, "process:"))
6147 p += sizeof ("process:") - 1;
6148 unpack_varlen_hex (p, &upid);
6152 error (_("unknown stop reply packet: %s"), buf);
6155 error (_("unknown stop reply packet: %s"), buf);
6156 event->ptid = pid_to_ptid (pid);
6161 if (non_stop && ptid_equal (event->ptid, null_ptid))
6162 error (_("No process or thread specified in stop reply: %s"), buf);
6165 /* When the stub wants to tell GDB about a new notification reply, it
6166 sends a notification (%Stop, for example). Those can come it at
6167 any time, hence, we have to make sure that any pending
6168 putpkt/getpkt sequence we're making is finished, before querying
6169 the stub for more events with the corresponding ack command
6170 (vStopped, for example). E.g., if we started a vStopped sequence
6171 immediately upon receiving the notification, something like this
6179 1.6) <-- (registers reply to step #1.3)
6181 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6184 To solve this, whenever we parse a %Stop notification successfully,
6185 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6186 doing whatever we were doing:
6192 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6193 2.5) <-- (registers reply to step #2.3)
6195 Eventualy after step #2.5, we return to the event loop, which
6196 notices there's an event on the
6197 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6198 associated callback --- the function below. At this point, we're
6199 always safe to start a vStopped sequence. :
6202 2.7) <-- T05 thread:2
6208 remote_notif_get_pending_events (struct notif_client *nc)
6210 struct remote_state *rs = get_remote_state ();
6212 if (rs->notif_state->pending_event[nc->id] != NULL)
6215 fprintf_unfiltered (gdb_stdlog,
6216 "notif: process: '%s' ack pending event\n",
6220 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6221 rs->notif_state->pending_event[nc->id] = NULL;
6225 getpkt (&rs->buf, &rs->buf_size, 0);
6226 if (strcmp (rs->buf, "OK") == 0)
6229 remote_notif_ack (nc, rs->buf);
6235 fprintf_unfiltered (gdb_stdlog,
6236 "notif: process: '%s' no pending reply\n",
6241 /* Called when it is decided that STOP_REPLY holds the info of the
6242 event that is to be returned to the core. This function always
6243 destroys STOP_REPLY. */
6246 process_stop_reply (struct stop_reply *stop_reply,
6247 struct target_waitstatus *status)
6251 *status = stop_reply->ws;
6252 ptid = stop_reply->ptid;
6254 /* If no thread/process was reported by the stub, assume the current
6256 if (ptid_equal (ptid, null_ptid))
6257 ptid = inferior_ptid;
6259 if (status->kind != TARGET_WAITKIND_EXITED
6260 && status->kind != TARGET_WAITKIND_SIGNALLED)
6262 struct remote_state *rs = get_remote_state ();
6264 /* Expedited registers. */
6265 if (stop_reply->regcache)
6267 struct regcache *regcache
6268 = get_thread_arch_regcache (ptid, target_gdbarch ());
6273 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6275 regcache_raw_supply (regcache, reg->num, reg->data);
6276 VEC_free (cached_reg_t, stop_reply->regcache);
6279 rs->stop_reason = stop_reply->stop_reason;
6280 rs->remote_watch_data_address = stop_reply->watch_data_address;
6282 remote_notice_new_inferior (ptid, 0);
6283 demand_private_info (ptid)->core = stop_reply->core;
6286 stop_reply_xfree (stop_reply);
6290 /* The non-stop mode version of target_wait. */
6293 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6295 struct remote_state *rs = get_remote_state ();
6296 struct stop_reply *stop_reply;
6300 /* If in non-stop mode, get out of getpkt even if a
6301 notification is received. */
6303 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6304 0 /* forever */, &is_notif);
6307 if (ret != -1 && !is_notif)
6310 case 'E': /* Error of some sort. */
6311 /* We're out of sync with the target now. Did it continue
6312 or not? We can't tell which thread it was in non-stop,
6313 so just ignore this. */
6314 warning (_("Remote failure reply: %s"), rs->buf);
6316 case 'O': /* Console output. */
6317 remote_console_output (rs->buf + 1);
6320 warning (_("Invalid remote reply: %s"), rs->buf);
6324 /* Acknowledge a pending stop reply that may have arrived in the
6326 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6327 remote_notif_get_pending_events (¬if_client_stop);
6329 /* If indeed we noticed a stop reply, we're done. */
6330 stop_reply = queued_stop_reply (ptid);
6331 if (stop_reply != NULL)
6332 return process_stop_reply (stop_reply, status);
6334 /* Still no event. If we're just polling for an event, then
6335 return to the event loop. */
6336 if (options & TARGET_WNOHANG)
6338 status->kind = TARGET_WAITKIND_IGNORE;
6339 return minus_one_ptid;
6342 /* Otherwise do a blocking wait. */
6343 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6344 1 /* forever */, &is_notif);
6348 /* Wait until the remote machine stops, then return, storing status in
6349 STATUS just as `wait' would. */
6352 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6354 struct remote_state *rs = get_remote_state ();
6355 ptid_t event_ptid = null_ptid;
6357 struct stop_reply *stop_reply;
6361 status->kind = TARGET_WAITKIND_IGNORE;
6362 status->value.integer = 0;
6364 stop_reply = queued_stop_reply (ptid);
6365 if (stop_reply != NULL)
6366 return process_stop_reply (stop_reply, status);
6368 if (rs->cached_wait_status)
6369 /* Use the cached wait status, but only once. */
6370 rs->cached_wait_status = 0;
6375 int forever = ((options & TARGET_WNOHANG) == 0
6376 && wait_forever_enabled_p);
6378 if (!rs->waiting_for_stop_reply)
6380 status->kind = TARGET_WAITKIND_NO_RESUMED;
6381 return minus_one_ptid;
6384 if (!target_is_async_p ())
6386 ofunc = signal (SIGINT, sync_remote_interrupt);
6387 /* If the user hit C-c before this packet, or between packets,
6388 pretend that it was hit right here. */
6389 if (check_quit_flag ())
6392 sync_remote_interrupt (SIGINT);
6396 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6397 _never_ wait for ever -> test on target_is_async_p().
6398 However, before we do that we need to ensure that the caller
6399 knows how to take the target into/out of async mode. */
6400 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6401 forever, &is_notif);
6403 if (!target_is_async_p ())
6404 signal (SIGINT, ofunc);
6406 /* GDB gets a notification. Return to core as this event is
6408 if (ret != -1 && is_notif)
6409 return minus_one_ptid;
6411 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6412 return minus_one_ptid;
6417 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6419 /* We got something. */
6420 rs->waiting_for_stop_reply = 0;
6422 /* Assume that the target has acknowledged Ctrl-C unless we receive
6423 an 'F' or 'O' packet. */
6424 if (buf[0] != 'F' && buf[0] != 'O')
6425 rs->ctrlc_pending_p = 0;
6429 case 'E': /* Error of some sort. */
6430 /* We're out of sync with the target now. Did it continue or
6431 not? Not is more likely, so report a stop. */
6432 warning (_("Remote failure reply: %s"), buf);
6433 status->kind = TARGET_WAITKIND_STOPPED;
6434 status->value.sig = GDB_SIGNAL_0;
6436 case 'F': /* File-I/O request. */
6437 remote_fileio_request (buf, rs->ctrlc_pending_p);
6438 rs->ctrlc_pending_p = 0;
6440 case 'T': case 'S': case 'X': case 'W':
6442 struct stop_reply *stop_reply
6443 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6446 event_ptid = process_stop_reply (stop_reply, status);
6449 case 'O': /* Console output. */
6450 remote_console_output (buf + 1);
6452 /* The target didn't really stop; keep waiting. */
6453 rs->waiting_for_stop_reply = 1;
6457 if (rs->last_sent_signal != GDB_SIGNAL_0)
6459 /* Zero length reply means that we tried 'S' or 'C' and the
6460 remote system doesn't support it. */
6461 target_terminal_ours_for_output ();
6463 ("Can't send signals to this remote system. %s not sent.\n",
6464 gdb_signal_to_name (rs->last_sent_signal));
6465 rs->last_sent_signal = GDB_SIGNAL_0;
6466 target_terminal_inferior ();
6468 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6469 putpkt ((char *) buf);
6471 /* We just told the target to resume, so a stop reply is in
6473 rs->waiting_for_stop_reply = 1;
6476 /* else fallthrough */
6478 warning (_("Invalid remote reply: %s"), buf);
6480 rs->waiting_for_stop_reply = 1;
6484 if (status->kind == TARGET_WAITKIND_IGNORE)
6486 /* Nothing interesting happened. If we're doing a non-blocking
6487 poll, we're done. Otherwise, go back to waiting. */
6488 if (options & TARGET_WNOHANG)
6489 return minus_one_ptid;
6493 else if (status->kind != TARGET_WAITKIND_EXITED
6494 && status->kind != TARGET_WAITKIND_SIGNALLED)
6496 if (!ptid_equal (event_ptid, null_ptid))
6497 record_currthread (rs, event_ptid);
6499 event_ptid = inferior_ptid;
6502 /* A process exit. Invalidate our notion of current thread. */
6503 record_currthread (rs, minus_one_ptid);
6508 /* Wait until the remote machine stops, then return, storing status in
6509 STATUS just as `wait' would. */
6512 remote_wait (struct target_ops *ops,
6513 ptid_t ptid, struct target_waitstatus *status, int options)
6518 event_ptid = remote_wait_ns (ptid, status, options);
6520 event_ptid = remote_wait_as (ptid, status, options);
6522 if (target_is_async_p ())
6524 /* If there are are events left in the queue tell the event loop
6526 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6527 mark_async_event_handler (remote_async_inferior_event_token);
6533 /* Fetch a single register using a 'p' packet. */
6536 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6538 struct remote_state *rs = get_remote_state ();
6540 char regp[MAX_REGISTER_SIZE];
6543 if (packet_support (PACKET_p) == PACKET_DISABLE)
6546 if (reg->pnum == -1)
6551 p += hexnumstr (p, reg->pnum);
6554 getpkt (&rs->buf, &rs->buf_size, 0);
6558 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6562 case PACKET_UNKNOWN:
6565 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6566 gdbarch_register_name (get_regcache_arch (regcache),
6571 /* If this register is unfetchable, tell the regcache. */
6574 regcache_raw_supply (regcache, reg->regnum, NULL);
6578 /* Otherwise, parse and supply the value. */
6584 error (_("fetch_register_using_p: early buf termination"));
6586 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6589 regcache_raw_supply (regcache, reg->regnum, regp);
6593 /* Fetch the registers included in the target's 'g' packet. */
6596 send_g_packet (void)
6598 struct remote_state *rs = get_remote_state ();
6601 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6602 remote_send (&rs->buf, &rs->buf_size);
6604 /* We can get out of synch in various cases. If the first character
6605 in the buffer is not a hex character, assume that has happened
6606 and try to fetch another packet to read. */
6607 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6608 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6609 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6610 && rs->buf[0] != 'x') /* New: unavailable register value. */
6613 fprintf_unfiltered (gdb_stdlog,
6614 "Bad register packet; fetching a new packet\n");
6615 getpkt (&rs->buf, &rs->buf_size, 0);
6618 buf_len = strlen (rs->buf);
6620 /* Sanity check the received packet. */
6621 if (buf_len % 2 != 0)
6622 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6628 process_g_packet (struct regcache *regcache)
6630 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6631 struct remote_state *rs = get_remote_state ();
6632 struct remote_arch_state *rsa = get_remote_arch_state ();
6637 buf_len = strlen (rs->buf);
6639 /* Further sanity checks, with knowledge of the architecture. */
6640 if (buf_len > 2 * rsa->sizeof_g_packet)
6641 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6643 /* Save the size of the packet sent to us by the target. It is used
6644 as a heuristic when determining the max size of packets that the
6645 target can safely receive. */
6646 if (rsa->actual_register_packet_size == 0)
6647 rsa->actual_register_packet_size = buf_len;
6649 /* If this is smaller than we guessed the 'g' packet would be,
6650 update our records. A 'g' reply that doesn't include a register's
6651 value implies either that the register is not available, or that
6652 the 'p' packet must be used. */
6653 if (buf_len < 2 * rsa->sizeof_g_packet)
6655 rsa->sizeof_g_packet = buf_len / 2;
6657 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6659 if (rsa->regs[i].pnum == -1)
6662 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6663 rsa->regs[i].in_g_packet = 0;
6665 rsa->regs[i].in_g_packet = 1;
6669 regs = alloca (rsa->sizeof_g_packet);
6671 /* Unimplemented registers read as all bits zero. */
6672 memset (regs, 0, rsa->sizeof_g_packet);
6674 /* Reply describes registers byte by byte, each byte encoded as two
6675 hex characters. Suck them all up, then supply them to the
6676 register cacheing/storage mechanism. */
6679 for (i = 0; i < rsa->sizeof_g_packet; i++)
6681 if (p[0] == 0 || p[1] == 0)
6682 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6683 internal_error (__FILE__, __LINE__,
6684 _("unexpected end of 'g' packet reply"));
6686 if (p[0] == 'x' && p[1] == 'x')
6687 regs[i] = 0; /* 'x' */
6689 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6693 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6695 struct packet_reg *r = &rsa->regs[i];
6699 if (r->offset * 2 >= strlen (rs->buf))
6700 /* This shouldn't happen - we adjusted in_g_packet above. */
6701 internal_error (__FILE__, __LINE__,
6702 _("unexpected end of 'g' packet reply"));
6703 else if (rs->buf[r->offset * 2] == 'x')
6705 gdb_assert (r->offset * 2 < strlen (rs->buf));
6706 /* The register isn't available, mark it as such (at
6707 the same time setting the value to zero). */
6708 regcache_raw_supply (regcache, r->regnum, NULL);
6711 regcache_raw_supply (regcache, r->regnum,
6718 fetch_registers_using_g (struct regcache *regcache)
6721 process_g_packet (regcache);
6724 /* Make the remote selected traceframe match GDB's selected
6728 set_remote_traceframe (void)
6731 struct remote_state *rs = get_remote_state ();
6733 if (rs->remote_traceframe_number == get_traceframe_number ())
6736 /* Avoid recursion, remote_trace_find calls us again. */
6737 rs->remote_traceframe_number = get_traceframe_number ();
6739 newnum = target_trace_find (tfind_number,
6740 get_traceframe_number (), 0, 0, NULL);
6742 /* Should not happen. If it does, all bets are off. */
6743 if (newnum != get_traceframe_number ())
6744 warning (_("could not set remote traceframe"));
6748 remote_fetch_registers (struct target_ops *ops,
6749 struct regcache *regcache, int regnum)
6751 struct remote_arch_state *rsa = get_remote_arch_state ();
6754 set_remote_traceframe ();
6755 set_general_thread (inferior_ptid);
6759 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6761 gdb_assert (reg != NULL);
6763 /* If this register might be in the 'g' packet, try that first -
6764 we are likely to read more than one register. If this is the
6765 first 'g' packet, we might be overly optimistic about its
6766 contents, so fall back to 'p'. */
6767 if (reg->in_g_packet)
6769 fetch_registers_using_g (regcache);
6770 if (reg->in_g_packet)
6774 if (fetch_register_using_p (regcache, reg))
6777 /* This register is not available. */
6778 regcache_raw_supply (regcache, reg->regnum, NULL);
6783 fetch_registers_using_g (regcache);
6785 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6786 if (!rsa->regs[i].in_g_packet)
6787 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6789 /* This register is not available. */
6790 regcache_raw_supply (regcache, i, NULL);
6794 /* Prepare to store registers. Since we may send them all (using a
6795 'G' request), we have to read out the ones we don't want to change
6799 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6801 struct remote_arch_state *rsa = get_remote_arch_state ();
6803 gdb_byte buf[MAX_REGISTER_SIZE];
6805 /* Make sure the entire registers array is valid. */
6806 switch (packet_support (PACKET_P))
6808 case PACKET_DISABLE:
6809 case PACKET_SUPPORT_UNKNOWN:
6810 /* Make sure all the necessary registers are cached. */
6811 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6812 if (rsa->regs[i].in_g_packet)
6813 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6820 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6821 packet was not recognized. */
6824 store_register_using_P (const struct regcache *regcache,
6825 struct packet_reg *reg)
6827 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6828 struct remote_state *rs = get_remote_state ();
6829 /* Try storing a single register. */
6830 char *buf = rs->buf;
6831 gdb_byte regp[MAX_REGISTER_SIZE];
6834 if (packet_support (PACKET_P) == PACKET_DISABLE)
6837 if (reg->pnum == -1)
6840 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6841 p = buf + strlen (buf);
6842 regcache_raw_collect (regcache, reg->regnum, regp);
6843 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6845 getpkt (&rs->buf, &rs->buf_size, 0);
6847 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6852 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6853 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6854 case PACKET_UNKNOWN:
6857 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6861 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6862 contents of the register cache buffer. FIXME: ignores errors. */
6865 store_registers_using_G (const struct regcache *regcache)
6867 struct remote_state *rs = get_remote_state ();
6868 struct remote_arch_state *rsa = get_remote_arch_state ();
6872 /* Extract all the registers in the regcache copying them into a
6877 regs = alloca (rsa->sizeof_g_packet);
6878 memset (regs, 0, rsa->sizeof_g_packet);
6879 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6881 struct packet_reg *r = &rsa->regs[i];
6884 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6888 /* Command describes registers byte by byte,
6889 each byte encoded as two hex characters. */
6892 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6894 bin2hex (regs, p, rsa->sizeof_g_packet);
6896 getpkt (&rs->buf, &rs->buf_size, 0);
6897 if (packet_check_result (rs->buf) == PACKET_ERROR)
6898 error (_("Could not write registers; remote failure reply '%s'"),
6902 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6903 of the register cache buffer. FIXME: ignores errors. */
6906 remote_store_registers (struct target_ops *ops,
6907 struct regcache *regcache, int regnum)
6909 struct remote_arch_state *rsa = get_remote_arch_state ();
6912 set_remote_traceframe ();
6913 set_general_thread (inferior_ptid);
6917 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6919 gdb_assert (reg != NULL);
6921 /* Always prefer to store registers using the 'P' packet if
6922 possible; we often change only a small number of registers.
6923 Sometimes we change a larger number; we'd need help from a
6924 higher layer to know to use 'G'. */
6925 if (store_register_using_P (regcache, reg))
6928 /* For now, don't complain if we have no way to write the
6929 register. GDB loses track of unavailable registers too
6930 easily. Some day, this may be an error. We don't have
6931 any way to read the register, either... */
6932 if (!reg->in_g_packet)
6935 store_registers_using_G (regcache);
6939 store_registers_using_G (regcache);
6941 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6942 if (!rsa->regs[i].in_g_packet)
6943 if (!store_register_using_P (regcache, &rsa->regs[i]))
6944 /* See above for why we do not issue an error here. */
6949 /* Return the number of hex digits in num. */
6952 hexnumlen (ULONGEST num)
6956 for (i = 0; num != 0; i++)
6962 /* Set BUF to the minimum number of hex digits representing NUM. */
6965 hexnumstr (char *buf, ULONGEST num)
6967 int len = hexnumlen (num);
6969 return hexnumnstr (buf, num, len);
6973 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6976 hexnumnstr (char *buf, ULONGEST num, int width)
6982 for (i = width - 1; i >= 0; i--)
6984 buf[i] = "0123456789abcdef"[(num & 0xf)];
6991 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6994 remote_address_masked (CORE_ADDR addr)
6996 unsigned int address_size = remote_address_size;
6998 /* If "remoteaddresssize" was not set, default to target address size. */
7000 address_size = gdbarch_addr_bit (target_gdbarch ());
7002 if (address_size > 0
7003 && address_size < (sizeof (ULONGEST) * 8))
7005 /* Only create a mask when that mask can safely be constructed
7006 in a ULONGEST variable. */
7009 mask = (mask << address_size) - 1;
7015 /* Determine whether the remote target supports binary downloading.
7016 This is accomplished by sending a no-op memory write of zero length
7017 to the target at the specified address. It does not suffice to send
7018 the whole packet, since many stubs strip the eighth bit and
7019 subsequently compute a wrong checksum, which causes real havoc with
7022 NOTE: This can still lose if the serial line is not eight-bit
7023 clean. In cases like this, the user should clear "remote
7027 check_binary_download (CORE_ADDR addr)
7029 struct remote_state *rs = get_remote_state ();
7031 switch (packet_support (PACKET_X))
7033 case PACKET_DISABLE:
7037 case PACKET_SUPPORT_UNKNOWN:
7043 p += hexnumstr (p, (ULONGEST) addr);
7045 p += hexnumstr (p, (ULONGEST) 0);
7049 putpkt_binary (rs->buf, (int) (p - rs->buf));
7050 getpkt (&rs->buf, &rs->buf_size, 0);
7052 if (rs->buf[0] == '\0')
7055 fprintf_unfiltered (gdb_stdlog,
7056 "binary downloading NOT "
7057 "supported by target\n");
7058 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7063 fprintf_unfiltered (gdb_stdlog,
7064 "binary downloading supported by target\n");
7065 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7072 /* Helper function to resize the payload in order to try to get a good
7073 alignment. We try to write an amount of data such that the next write will
7074 start on an address aligned on REMOTE_ALIGN_WRITES. */
7077 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7079 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7082 /* Write memory data directly to the remote machine.
7083 This does not inform the data cache; the data cache uses this.
7084 HEADER is the starting part of the packet.
7085 MEMADDR is the address in the remote memory space.
7086 MYADDR is the address of the buffer in our space.
7087 LEN_UNITS is the number of addressable units to write.
7088 UNIT_SIZE is the length in bytes of an addressable unit.
7089 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7090 should send data as binary ('X'), or hex-encoded ('M').
7092 The function creates packet of the form
7093 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7095 where encoding of <DATA> is terminated by PACKET_FORMAT.
7097 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7100 Return the transferred status, error or OK (an
7101 'enum target_xfer_status' value). Save the number of addressable units
7102 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7104 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7105 exchange between gdb and the stub could look like (?? in place of the
7111 -> $M1000,3:eeeeffffeeee#??
7115 <- eeeeffffeeeedddd */
7117 static enum target_xfer_status
7118 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7119 const gdb_byte *myaddr, ULONGEST len_units,
7120 int unit_size, ULONGEST *xfered_len_units,
7121 char packet_format, int use_length)
7123 struct remote_state *rs = get_remote_state ();
7129 int payload_capacity_bytes;
7130 int payload_length_bytes;
7132 if (packet_format != 'X' && packet_format != 'M')
7133 internal_error (__FILE__, __LINE__,
7134 _("remote_write_bytes_aux: bad packet format"));
7137 return TARGET_XFER_EOF;
7139 payload_capacity_bytes = get_memory_write_packet_size ();
7141 /* The packet buffer will be large enough for the payload;
7142 get_memory_packet_size ensures this. */
7145 /* Compute the size of the actual payload by subtracting out the
7146 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7148 payload_capacity_bytes -= strlen ("$,:#NN");
7150 /* The comma won't be used. */
7151 payload_capacity_bytes += 1;
7152 payload_capacity_bytes -= strlen (header);
7153 payload_capacity_bytes -= hexnumlen (memaddr);
7155 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7157 strcat (rs->buf, header);
7158 p = rs->buf + strlen (header);
7160 /* Compute a best guess of the number of bytes actually transfered. */
7161 if (packet_format == 'X')
7163 /* Best guess at number of bytes that will fit. */
7164 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7166 payload_capacity_bytes -= hexnumlen (todo_units);
7167 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7171 /* Number of bytes that will fit. */
7172 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7174 payload_capacity_bytes -= hexnumlen (todo_units);
7175 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7178 if (todo_units <= 0)
7179 internal_error (__FILE__, __LINE__,
7180 _("minimum packet size too small to write data"));
7182 /* If we already need another packet, then try to align the end
7183 of this packet to a useful boundary. */
7184 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7185 todo_units = align_for_efficient_write (todo_units, memaddr);
7187 /* Append "<memaddr>". */
7188 memaddr = remote_address_masked (memaddr);
7189 p += hexnumstr (p, (ULONGEST) memaddr);
7196 /* Append the length and retain its location and size. It may need to be
7197 adjusted once the packet body has been created. */
7199 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7207 /* Append the packet body. */
7208 if (packet_format == 'X')
7210 /* Binary mode. Send target system values byte by byte, in
7211 increasing byte addresses. Only escape certain critical
7213 payload_length_bytes =
7214 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7215 &units_written, payload_capacity_bytes);
7217 /* If not all TODO units fit, then we'll need another packet. Make
7218 a second try to keep the end of the packet aligned. Don't do
7219 this if the packet is tiny. */
7220 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7224 new_todo_units = align_for_efficient_write (units_written, memaddr);
7226 if (new_todo_units != units_written)
7227 payload_length_bytes =
7228 remote_escape_output (myaddr, new_todo_units, unit_size,
7229 (gdb_byte *) p, &units_written,
7230 payload_capacity_bytes);
7233 p += payload_length_bytes;
7234 if (use_length && units_written < todo_units)
7236 /* Escape chars have filled up the buffer prematurely,
7237 and we have actually sent fewer units than planned.
7238 Fix-up the length field of the packet. Use the same
7239 number of characters as before. */
7240 plen += hexnumnstr (plen, (ULONGEST) units_written,
7242 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7247 /* Normal mode: Send target system values byte by byte, in
7248 increasing byte addresses. Each byte is encoded as a two hex
7250 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7251 units_written = todo_units;
7254 putpkt_binary (rs->buf, (int) (p - rs->buf));
7255 getpkt (&rs->buf, &rs->buf_size, 0);
7257 if (rs->buf[0] == 'E')
7258 return TARGET_XFER_E_IO;
7260 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7261 send fewer units than we'd planned. */
7262 *xfered_len_units = (ULONGEST) units_written;
7263 return TARGET_XFER_OK;
7266 /* Write memory data directly to the remote machine.
7267 This does not inform the data cache; the data cache uses this.
7268 MEMADDR is the address in the remote memory space.
7269 MYADDR is the address of the buffer in our space.
7270 LEN is the number of bytes.
7272 Return the transferred status, error or OK (an
7273 'enum target_xfer_status' value). Save the number of bytes
7274 transferred in *XFERED_LEN. Only transfer a single packet. */
7276 static enum target_xfer_status
7277 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7278 int unit_size, ULONGEST *xfered_len)
7280 char *packet_format = 0;
7282 /* Check whether the target supports binary download. */
7283 check_binary_download (memaddr);
7285 switch (packet_support (PACKET_X))
7288 packet_format = "X";
7290 case PACKET_DISABLE:
7291 packet_format = "M";
7293 case PACKET_SUPPORT_UNKNOWN:
7294 internal_error (__FILE__, __LINE__,
7295 _("remote_write_bytes: bad internal state"));
7297 internal_error (__FILE__, __LINE__, _("bad switch"));
7300 return remote_write_bytes_aux (packet_format,
7301 memaddr, myaddr, len, unit_size, xfered_len,
7302 packet_format[0], 1);
7305 /* Read memory data directly from the remote machine.
7306 This does not use the data cache; the data cache uses this.
7307 MEMADDR is the address in the remote memory space.
7308 MYADDR is the address of the buffer in our space.
7309 LEN_UNITS is the number of addressable memory units to read..
7310 UNIT_SIZE is the length in bytes of an addressable unit.
7312 Return the transferred status, error or OK (an
7313 'enum target_xfer_status' value). Save the number of bytes
7314 transferred in *XFERED_LEN_UNITS.
7316 See the comment of remote_write_bytes_aux for an example of
7317 memory read/write exchange between gdb and the stub. */
7319 static enum target_xfer_status
7320 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7321 int unit_size, ULONGEST *xfered_len_units)
7323 struct remote_state *rs = get_remote_state ();
7324 int buf_size_bytes; /* Max size of packet output buffer. */
7329 buf_size_bytes = get_memory_read_packet_size ();
7330 /* The packet buffer will be large enough for the payload;
7331 get_memory_packet_size ensures this. */
7333 /* Number of units that will fit. */
7334 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7336 /* Construct "m"<memaddr>","<len>". */
7337 memaddr = remote_address_masked (memaddr);
7340 p += hexnumstr (p, (ULONGEST) memaddr);
7342 p += hexnumstr (p, (ULONGEST) todo_units);
7345 getpkt (&rs->buf, &rs->buf_size, 0);
7346 if (rs->buf[0] == 'E'
7347 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7348 && rs->buf[3] == '\0')
7349 return TARGET_XFER_E_IO;
7350 /* Reply describes memory byte by byte, each byte encoded as two hex
7353 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7354 /* Return what we have. Let higher layers handle partial reads. */
7355 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7356 return TARGET_XFER_OK;
7359 /* Using the set of read-only target sections of remote, read live
7362 For interface/parameters/return description see target.h,
7365 static enum target_xfer_status
7366 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7367 ULONGEST memaddr, ULONGEST len,
7368 int unit_size, ULONGEST *xfered_len)
7370 struct target_section *secp;
7371 struct target_section_table *table;
7373 secp = target_section_by_addr (ops, memaddr);
7375 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7376 secp->the_bfd_section)
7379 struct target_section *p;
7380 ULONGEST memend = memaddr + len;
7382 table = target_get_section_table (ops);
7384 for (p = table->sections; p < table->sections_end; p++)
7386 if (memaddr >= p->addr)
7388 if (memend <= p->endaddr)
7390 /* Entire transfer is within this section. */
7391 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7394 else if (memaddr >= p->endaddr)
7396 /* This section ends before the transfer starts. */
7401 /* This section overlaps the transfer. Just do half. */
7402 len = p->endaddr - memaddr;
7403 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7410 return TARGET_XFER_EOF;
7413 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7414 first if the requested memory is unavailable in traceframe.
7415 Otherwise, fall back to remote_read_bytes_1. */
7417 static enum target_xfer_status
7418 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7419 gdb_byte *myaddr, ULONGEST len, int unit_size,
7420 ULONGEST *xfered_len)
7423 return TARGET_XFER_EOF;
7425 if (get_traceframe_number () != -1)
7427 VEC(mem_range_s) *available;
7429 /* If we fail to get the set of available memory, then the
7430 target does not support querying traceframe info, and so we
7431 attempt reading from the traceframe anyway (assuming the
7432 target implements the old QTro packet then). */
7433 if (traceframe_available_memory (&available, memaddr, len))
7435 struct cleanup *old_chain;
7437 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7439 if (VEC_empty (mem_range_s, available)
7440 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7442 enum target_xfer_status res;
7444 /* Don't read into the traceframe's available
7446 if (!VEC_empty (mem_range_s, available))
7448 LONGEST oldlen = len;
7450 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7451 gdb_assert (len <= oldlen);
7454 do_cleanups (old_chain);
7456 /* This goes through the topmost target again. */
7457 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7458 len, unit_size, xfered_len);
7459 if (res == TARGET_XFER_OK)
7460 return TARGET_XFER_OK;
7463 /* No use trying further, we know some memory starting
7464 at MEMADDR isn't available. */
7466 return TARGET_XFER_UNAVAILABLE;
7470 /* Don't try to read more than how much is available, in
7471 case the target implements the deprecated QTro packet to
7472 cater for older GDBs (the target's knowledge of read-only
7473 sections may be outdated by now). */
7474 len = VEC_index (mem_range_s, available, 0)->length;
7476 do_cleanups (old_chain);
7480 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7485 /* Sends a packet with content determined by the printf format string
7486 FORMAT and the remaining arguments, then gets the reply. Returns
7487 whether the packet was a success, a failure, or unknown. */
7489 static enum packet_result remote_send_printf (const char *format, ...)
7490 ATTRIBUTE_PRINTF (1, 2);
7492 static enum packet_result
7493 remote_send_printf (const char *format, ...)
7495 struct remote_state *rs = get_remote_state ();
7496 int max_size = get_remote_packet_size ();
7499 va_start (ap, format);
7502 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7503 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7505 if (putpkt (rs->buf) < 0)
7506 error (_("Communication problem with target."));
7509 getpkt (&rs->buf, &rs->buf_size, 0);
7511 return packet_check_result (rs->buf);
7515 restore_remote_timeout (void *p)
7517 int value = *(int *)p;
7519 remote_timeout = value;
7522 /* Flash writing can take quite some time. We'll set
7523 effectively infinite timeout for flash operations.
7524 In future, we'll need to decide on a better approach. */
7525 static const int remote_flash_timeout = 1000;
7528 remote_flash_erase (struct target_ops *ops,
7529 ULONGEST address, LONGEST length)
7531 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7532 int saved_remote_timeout = remote_timeout;
7533 enum packet_result ret;
7534 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7535 &saved_remote_timeout);
7537 remote_timeout = remote_flash_timeout;
7539 ret = remote_send_printf ("vFlashErase:%s,%s",
7540 phex (address, addr_size),
7544 case PACKET_UNKNOWN:
7545 error (_("Remote target does not support flash erase"));
7547 error (_("Error erasing flash with vFlashErase packet"));
7552 do_cleanups (back_to);
7555 static enum target_xfer_status
7556 remote_flash_write (struct target_ops *ops, ULONGEST address,
7557 ULONGEST length, ULONGEST *xfered_len,
7558 const gdb_byte *data)
7560 int saved_remote_timeout = remote_timeout;
7561 enum target_xfer_status ret;
7562 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7563 &saved_remote_timeout);
7565 remote_timeout = remote_flash_timeout;
7566 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7568 do_cleanups (back_to);
7574 remote_flash_done (struct target_ops *ops)
7576 int saved_remote_timeout = remote_timeout;
7578 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7579 &saved_remote_timeout);
7581 remote_timeout = remote_flash_timeout;
7582 ret = remote_send_printf ("vFlashDone");
7583 do_cleanups (back_to);
7587 case PACKET_UNKNOWN:
7588 error (_("Remote target does not support vFlashDone"));
7590 error (_("Error finishing flash operation"));
7597 remote_files_info (struct target_ops *ignore)
7599 puts_filtered ("Debugging a target over a serial line.\n");
7602 /* Stuff for dealing with the packets which are part of this protocol.
7603 See comment at top of file for details. */
7605 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7606 error to higher layers. Called when a serial error is detected.
7607 The exception message is STRING, followed by a colon and a blank,
7608 the system error message for errno at function entry and final dot
7609 for output compatibility with throw_perror_with_name. */
7612 unpush_and_perror (const char *string)
7614 int saved_errno = errno;
7616 remote_unpush_target ();
7617 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7618 safe_strerror (saved_errno));
7621 /* Read a single character from the remote end. */
7624 readchar (int timeout)
7627 struct remote_state *rs = get_remote_state ();
7629 ch = serial_readchar (rs->remote_desc, timeout);
7634 switch ((enum serial_rc) ch)
7637 remote_unpush_target ();
7638 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7641 unpush_and_perror (_("Remote communication error. "
7642 "Target disconnected."));
7644 case SERIAL_TIMEOUT:
7650 /* Wrapper for serial_write that closes the target and throws if
7654 remote_serial_write (const char *str, int len)
7656 struct remote_state *rs = get_remote_state ();
7658 if (serial_write (rs->remote_desc, str, len))
7660 unpush_and_perror (_("Remote communication error. "
7661 "Target disconnected."));
7665 /* Send the command in *BUF to the remote machine, and read the reply
7666 into *BUF. Report an error if we get an error reply. Resize
7667 *BUF using xrealloc if necessary to hold the result, and update
7671 remote_send (char **buf,
7675 getpkt (buf, sizeof_buf, 0);
7677 if ((*buf)[0] == 'E')
7678 error (_("Remote failure reply: %s"), *buf);
7681 /* Return a pointer to an xmalloc'ed string representing an escaped
7682 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7683 etc. The caller is responsible for releasing the returned
7687 escape_buffer (const char *buf, int n)
7689 struct cleanup *old_chain;
7690 struct ui_file *stb;
7693 stb = mem_fileopen ();
7694 old_chain = make_cleanup_ui_file_delete (stb);
7696 fputstrn_unfiltered (buf, n, '\\', stb);
7697 str = ui_file_xstrdup (stb, NULL);
7698 do_cleanups (old_chain);
7702 /* Display a null-terminated packet on stdout, for debugging, using C
7706 print_packet (const char *buf)
7708 puts_filtered ("\"");
7709 fputstr_filtered (buf, '"', gdb_stdout);
7710 puts_filtered ("\"");
7714 putpkt (const char *buf)
7716 return putpkt_binary (buf, strlen (buf));
7719 /* Send a packet to the remote machine, with error checking. The data
7720 of the packet is in BUF. The string in BUF can be at most
7721 get_remote_packet_size () - 5 to account for the $, # and checksum,
7722 and for a possible /0 if we are debugging (remote_debug) and want
7723 to print the sent packet as a string. */
7726 putpkt_binary (const char *buf, int cnt)
7728 struct remote_state *rs = get_remote_state ();
7730 unsigned char csum = 0;
7731 char *buf2 = alloca (cnt + 6);
7738 /* Catch cases like trying to read memory or listing threads while
7739 we're waiting for a stop reply. The remote server wouldn't be
7740 ready to handle this request, so we'd hang and timeout. We don't
7741 have to worry about this in synchronous mode, because in that
7742 case it's not possible to issue a command while the target is
7743 running. This is not a problem in non-stop mode, because in that
7744 case, the stub is always ready to process serial input. */
7745 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7747 error (_("Cannot execute this command while the target is running.\n"
7748 "Use the \"interrupt\" command to stop the target\n"
7749 "and then try again."));
7752 /* We're sending out a new packet. Make sure we don't look at a
7753 stale cached response. */
7754 rs->cached_wait_status = 0;
7756 /* Copy the packet into buffer BUF2, encapsulating it
7757 and giving it a checksum. */
7762 for (i = 0; i < cnt; i++)
7768 *p++ = tohex ((csum >> 4) & 0xf);
7769 *p++ = tohex (csum & 0xf);
7771 /* Send it over and over until we get a positive ack. */
7775 int started_error_output = 0;
7779 struct cleanup *old_chain;
7783 str = escape_buffer (buf2, p - buf2);
7784 old_chain = make_cleanup (xfree, str);
7785 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7786 gdb_flush (gdb_stdlog);
7787 do_cleanups (old_chain);
7789 remote_serial_write (buf2, p - buf2);
7791 /* If this is a no acks version of the remote protocol, send the
7792 packet and move on. */
7796 /* Read until either a timeout occurs (-2) or '+' is read.
7797 Handle any notification that arrives in the mean time. */
7800 ch = readchar (remote_timeout);
7808 case SERIAL_TIMEOUT:
7811 if (started_error_output)
7813 putchar_unfiltered ('\n');
7814 started_error_output = 0;
7823 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7827 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7829 case SERIAL_TIMEOUT:
7833 break; /* Retransmit buffer. */
7837 fprintf_unfiltered (gdb_stdlog,
7838 "Packet instead of Ack, ignoring it\n");
7839 /* It's probably an old response sent because an ACK
7840 was lost. Gobble up the packet and ack it so it
7841 doesn't get retransmitted when we resend this
7844 remote_serial_write ("+", 1);
7845 continue; /* Now, go look for +. */
7852 /* If we got a notification, handle it, and go back to looking
7854 /* We've found the start of a notification. Now
7855 collect the data. */
7856 val = read_frame (&rs->buf, &rs->buf_size);
7861 struct cleanup *old_chain;
7864 str = escape_buffer (rs->buf, val);
7865 old_chain = make_cleanup (xfree, str);
7866 fprintf_unfiltered (gdb_stdlog,
7867 " Notification received: %s\n",
7869 do_cleanups (old_chain);
7871 handle_notification (rs->notif_state, rs->buf);
7872 /* We're in sync now, rewait for the ack. */
7879 if (!started_error_output)
7881 started_error_output = 1;
7882 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7884 fputc_unfiltered (ch & 0177, gdb_stdlog);
7885 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7894 if (!started_error_output)
7896 started_error_output = 1;
7897 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7899 fputc_unfiltered (ch & 0177, gdb_stdlog);
7903 break; /* Here to retransmit. */
7907 /* This is wrong. If doing a long backtrace, the user should be
7908 able to get out next time we call QUIT, without anything as
7909 violent as interrupt_query. If we want to provide a way out of
7910 here without getting to the next QUIT, it should be based on
7911 hitting ^C twice as in remote_wait. */
7922 /* Come here after finding the start of a frame when we expected an
7923 ack. Do our best to discard the rest of this packet. */
7932 c = readchar (remote_timeout);
7935 case SERIAL_TIMEOUT:
7936 /* Nothing we can do. */
7939 /* Discard the two bytes of checksum and stop. */
7940 c = readchar (remote_timeout);
7942 c = readchar (remote_timeout);
7945 case '*': /* Run length encoding. */
7946 /* Discard the repeat count. */
7947 c = readchar (remote_timeout);
7952 /* A regular character. */
7958 /* Come here after finding the start of the frame. Collect the rest
7959 into *BUF, verifying the checksum, length, and handling run-length
7960 compression. NUL terminate the buffer. If there is not enough room,
7961 expand *BUF using xrealloc.
7963 Returns -1 on error, number of characters in buffer (ignoring the
7964 trailing NULL) on success. (could be extended to return one of the
7965 SERIAL status indications). */
7968 read_frame (char **buf_p,
7975 struct remote_state *rs = get_remote_state ();
7982 c = readchar (remote_timeout);
7985 case SERIAL_TIMEOUT:
7987 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7991 fputs_filtered ("Saw new packet start in middle of old one\n",
7993 return -1; /* Start a new packet, count retries. */
7996 unsigned char pktcsum;
8002 check_0 = readchar (remote_timeout);
8004 check_1 = readchar (remote_timeout);
8006 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8009 fputs_filtered ("Timeout in checksum, retrying\n",
8013 else if (check_0 < 0 || check_1 < 0)
8016 fputs_filtered ("Communication error in checksum\n",
8021 /* Don't recompute the checksum; with no ack packets we
8022 don't have any way to indicate a packet retransmission
8027 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8028 if (csum == pktcsum)
8033 struct cleanup *old_chain;
8036 str = escape_buffer (buf, bc);
8037 old_chain = make_cleanup (xfree, str);
8038 fprintf_unfiltered (gdb_stdlog,
8039 "Bad checksum, sentsum=0x%x, "
8040 "csum=0x%x, buf=%s\n",
8041 pktcsum, csum, str);
8042 do_cleanups (old_chain);
8044 /* Number of characters in buffer ignoring trailing
8048 case '*': /* Run length encoding. */
8053 c = readchar (remote_timeout);
8055 repeat = c - ' ' + 3; /* Compute repeat count. */
8057 /* The character before ``*'' is repeated. */
8059 if (repeat > 0 && repeat <= 255 && bc > 0)
8061 if (bc + repeat - 1 >= *sizeof_buf - 1)
8063 /* Make some more room in the buffer. */
8064 *sizeof_buf += repeat;
8065 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8069 memset (&buf[bc], buf[bc - 1], repeat);
8075 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8079 if (bc >= *sizeof_buf - 1)
8081 /* Make some more room in the buffer. */
8083 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8094 /* Read a packet from the remote machine, with error checking, and
8095 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8096 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8097 rather than timing out; this is used (in synchronous mode) to wait
8098 for a target that is is executing user code to stop. */
8099 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8100 don't have to change all the calls to getpkt to deal with the
8101 return value, because at the moment I don't know what the right
8102 thing to do it for those. */
8110 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8114 /* Read a packet from the remote machine, with error checking, and
8115 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8116 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8117 rather than timing out; this is used (in synchronous mode) to wait
8118 for a target that is is executing user code to stop. If FOREVER ==
8119 0, this function is allowed to time out gracefully and return an
8120 indication of this to the caller. Otherwise return the number of
8121 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8122 enough reason to return to the caller. *IS_NOTIF is an output
8123 boolean that indicates whether *BUF holds a notification or not
8124 (a regular packet). */
8127 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8128 int expecting_notif, int *is_notif)
8130 struct remote_state *rs = get_remote_state ();
8136 /* We're reading a new response. Make sure we don't look at a
8137 previously cached response. */
8138 rs->cached_wait_status = 0;
8140 strcpy (*buf, "timeout");
8143 timeout = watchdog > 0 ? watchdog : -1;
8144 else if (expecting_notif)
8145 timeout = 0; /* There should already be a char in the buffer. If
8148 timeout = remote_timeout;
8152 /* Process any number of notifications, and then return when
8156 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8158 for (tries = 1; tries <= MAX_TRIES; tries++)
8160 /* This can loop forever if the remote side sends us
8161 characters continuously, but if it pauses, we'll get
8162 SERIAL_TIMEOUT from readchar because of timeout. Then
8163 we'll count that as a retry.
8165 Note that even when forever is set, we will only wait
8166 forever prior to the start of a packet. After that, we
8167 expect characters to arrive at a brisk pace. They should
8168 show up within remote_timeout intervals. */
8170 c = readchar (timeout);
8171 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8173 if (c == SERIAL_TIMEOUT)
8175 if (expecting_notif)
8176 return -1; /* Don't complain, it's normal to not get
8177 anything in this case. */
8179 if (forever) /* Watchdog went off? Kill the target. */
8182 remote_unpush_target ();
8183 throw_error (TARGET_CLOSE_ERROR,
8184 _("Watchdog timeout has expired. "
8185 "Target detached."));
8188 fputs_filtered ("Timed out.\n", gdb_stdlog);
8192 /* We've found the start of a packet or notification.
8193 Now collect the data. */
8194 val = read_frame (buf, sizeof_buf);
8199 remote_serial_write ("-", 1);
8202 if (tries > MAX_TRIES)
8204 /* We have tried hard enough, and just can't receive the
8205 packet/notification. Give up. */
8206 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8208 /* Skip the ack char if we're in no-ack mode. */
8209 if (!rs->noack_mode)
8210 remote_serial_write ("+", 1);
8214 /* If we got an ordinary packet, return that to our caller. */
8219 struct cleanup *old_chain;
8222 str = escape_buffer (*buf, val);
8223 old_chain = make_cleanup (xfree, str);
8224 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8225 do_cleanups (old_chain);
8228 /* Skip the ack char if we're in no-ack mode. */
8229 if (!rs->noack_mode)
8230 remote_serial_write ("+", 1);
8231 if (is_notif != NULL)
8236 /* If we got a notification, handle it, and go back to looking
8240 gdb_assert (c == '%');
8244 struct cleanup *old_chain;
8247 str = escape_buffer (*buf, val);
8248 old_chain = make_cleanup (xfree, str);
8249 fprintf_unfiltered (gdb_stdlog,
8250 " Notification received: %s\n",
8252 do_cleanups (old_chain);
8254 if (is_notif != NULL)
8257 handle_notification (rs->notif_state, *buf);
8259 /* Notifications require no acknowledgement. */
8261 if (expecting_notif)
8268 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8270 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8274 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8277 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8281 /* Check whether EVENT is a fork event for the process specified
8282 by the pid passed in DATA, and if it is, kill the fork child. */
8285 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8286 QUEUE_ITER (stop_reply_p) *iter,
8290 struct queue_iter_param *param = data;
8291 int parent_pid = *(int *) param->input;
8293 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8295 struct remote_state *rs = get_remote_state ();
8296 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8299 res = remote_vkill (child_pid, rs);
8301 error (_("Can't kill fork child process %d"), child_pid);
8307 /* Kill any new fork children of process PID that haven't been
8308 processed by follow_fork. */
8311 kill_new_fork_children (int pid, struct remote_state *rs)
8313 struct thread_info *thread;
8314 struct notif_client *notif = ¬if_client_stop;
8315 struct queue_iter_param param;
8317 /* Kill the fork child threads of any threads in process PID
8318 that are stopped at a fork event. */
8319 ALL_NON_EXITED_THREADS (thread)
8321 struct target_waitstatus *ws = &thread->pending_follow;
8323 if (is_pending_fork_parent (ws, pid, thread->ptid))
8325 struct remote_state *rs = get_remote_state ();
8326 int child_pid = ptid_get_pid (ws->value.related_pid);
8329 res = remote_vkill (child_pid, rs);
8331 error (_("Can't kill fork child process %d"), child_pid);
8335 /* Check for any pending fork events (not reported or processed yet)
8336 in process PID and kill those fork child threads as well. */
8337 remote_notif_get_pending_events (notif);
8339 param.output = NULL;
8340 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8341 kill_child_of_pending_fork, ¶m);
8346 remote_kill (struct target_ops *ops)
8349 /* Catch errors so the user can quit from gdb even when we
8350 aren't on speaking terms with the remote system. */
8355 CATCH (ex, RETURN_MASK_ERROR)
8357 if (ex.error == TARGET_CLOSE_ERROR)
8359 /* If we got an (EOF) error that caused the target
8360 to go away, then we're done, that's what we wanted.
8361 "k" is susceptible to cause a premature EOF, given
8362 that the remote server isn't actually required to
8363 reply to "k", and it can happen that it doesn't
8364 even get to reply ACK to the "k". */
8368 /* Otherwise, something went wrong. We didn't actually kill
8369 the target. Just propagate the exception, and let the
8370 user or higher layers decide what to do. */
8371 throw_exception (ex);
8375 /* We've killed the remote end, we get to mourn it. Since this is
8376 target remote, single-process, mourning the inferior also
8377 unpushes remote_ops. */
8378 target_mourn_inferior ();
8382 remote_vkill (int pid, struct remote_state *rs)
8384 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8387 /* Tell the remote target to detach. */
8388 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8390 getpkt (&rs->buf, &rs->buf_size, 0);
8392 switch (packet_ok (rs->buf,
8393 &remote_protocol_packets[PACKET_vKill]))
8399 case PACKET_UNKNOWN:
8402 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8407 extended_remote_kill (struct target_ops *ops)
8410 int pid = ptid_get_pid (inferior_ptid);
8411 struct remote_state *rs = get_remote_state ();
8413 /* If we're stopped while forking and we haven't followed yet, kill the
8414 child task. We need to do this before killing the parent task
8415 because if this is a vfork then the parent will be sleeping. */
8416 kill_new_fork_children (pid, rs);
8418 res = remote_vkill (pid, rs);
8419 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8421 /* Don't try 'k' on a multi-process aware stub -- it has no way
8422 to specify the pid. */
8426 getpkt (&rs->buf, &rs->buf_size, 0);
8427 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8430 /* Don't wait for it to die. I'm not really sure it matters whether
8431 we do or not. For the existing stubs, kill is a noop. */
8437 error (_("Can't kill process"));
8439 target_mourn_inferior ();
8443 remote_mourn (struct target_ops *target)
8445 unpush_target (target);
8447 /* remote_close takes care of doing most of the clean up. */
8448 generic_mourn_inferior ();
8452 extended_remote_mourn (struct target_ops *target)
8454 struct remote_state *rs = get_remote_state ();
8456 /* In case we got here due to an error, but we're going to stay
8458 rs->waiting_for_stop_reply = 0;
8460 /* If the current general thread belonged to the process we just
8461 detached from or has exited, the remote side current general
8462 thread becomes undefined. Considering a case like this:
8464 - We just got here due to a detach.
8465 - The process that we're detaching from happens to immediately
8466 report a global breakpoint being hit in non-stop mode, in the
8467 same thread we had selected before.
8468 - GDB attaches to this process again.
8469 - This event happens to be the next event we handle.
8471 GDB would consider that the current general thread didn't need to
8472 be set on the stub side (with Hg), since for all it knew,
8473 GENERAL_THREAD hadn't changed.
8475 Notice that although in all-stop mode, the remote server always
8476 sets the current thread to the thread reporting the stop event,
8477 that doesn't happen in non-stop mode; in non-stop, the stub *must
8478 not* change the current thread when reporting a breakpoint hit,
8479 due to the decoupling of event reporting and event handling.
8481 To keep things simple, we always invalidate our notion of the
8483 record_currthread (rs, minus_one_ptid);
8485 /* Unlike "target remote", we do not want to unpush the target; then
8486 the next time the user says "run", we won't be connected. */
8488 /* Call common code to mark the inferior as not running. */
8489 generic_mourn_inferior ();
8491 if (!have_inferiors ())
8493 if (!remote_multi_process_p (rs))
8495 /* Check whether the target is running now - some remote stubs
8496 automatically restart after kill. */
8498 getpkt (&rs->buf, &rs->buf_size, 0);
8500 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8502 /* Assume that the target has been restarted. Set
8503 inferior_ptid so that bits of core GDB realizes
8504 there's something here, e.g., so that the user can
8505 say "kill" again. */
8506 inferior_ptid = magic_null_ptid;
8513 extended_remote_supports_disable_randomization (struct target_ops *self)
8515 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8519 extended_remote_disable_randomization (int val)
8521 struct remote_state *rs = get_remote_state ();
8524 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8527 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8529 error (_("Target does not support QDisableRandomization."));
8530 if (strcmp (reply, "OK") != 0)
8531 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8535 extended_remote_run (char *args)
8537 struct remote_state *rs = get_remote_state ();
8540 /* If the user has disabled vRun support, or we have detected that
8541 support is not available, do not try it. */
8542 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8545 strcpy (rs->buf, "vRun;");
8546 len = strlen (rs->buf);
8548 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8549 error (_("Remote file name too long for run packet"));
8550 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8551 strlen (remote_exec_file));
8553 gdb_assert (args != NULL);
8556 struct cleanup *back_to;
8560 argv = gdb_buildargv (args);
8561 back_to = make_cleanup_freeargv (argv);
8562 for (i = 0; argv[i] != NULL; i++)
8564 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8565 error (_("Argument list too long for run packet"));
8566 rs->buf[len++] = ';';
8567 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8570 do_cleanups (back_to);
8573 rs->buf[len++] = '\0';
8576 getpkt (&rs->buf, &rs->buf_size, 0);
8578 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8581 /* We have a wait response. All is well. */
8583 case PACKET_UNKNOWN:
8586 if (remote_exec_file[0] == '\0')
8587 error (_("Running the default executable on the remote target failed; "
8588 "try \"set remote exec-file\"?"));
8590 error (_("Running \"%s\" on the remote target failed"),
8593 gdb_assert_not_reached (_("bad switch"));
8597 /* In the extended protocol we want to be able to do things like
8598 "run" and have them basically work as expected. So we need
8599 a special create_inferior function. We support changing the
8600 executable file and the command line arguments, but not the
8604 extended_remote_create_inferior (struct target_ops *ops,
8605 char *exec_file, char *args,
8606 char **env, int from_tty)
8610 struct remote_state *rs = get_remote_state ();
8612 /* If running asynchronously, register the target file descriptor
8613 with the event loop. */
8614 if (target_can_async_p ())
8617 /* Disable address space randomization if requested (and supported). */
8618 if (extended_remote_supports_disable_randomization (ops))
8619 extended_remote_disable_randomization (disable_randomization);
8621 /* Now restart the remote server. */
8622 run_worked = extended_remote_run (args) != -1;
8625 /* vRun was not supported. Fail if we need it to do what the
8627 if (remote_exec_file[0])
8628 error (_("Remote target does not support \"set remote exec-file\""));
8630 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8632 /* Fall back to "R". */
8633 extended_remote_restart ();
8636 if (!have_inferiors ())
8638 /* Clean up from the last time we ran, before we mark the target
8639 running again. This will mark breakpoints uninserted, and
8640 get_offsets may insert breakpoints. */
8641 init_thread_list ();
8642 init_wait_for_inferior ();
8645 /* vRun's success return is a stop reply. */
8646 stop_reply = run_worked ? rs->buf : NULL;
8647 add_current_inferior_and_thread (stop_reply);
8649 /* Get updated offsets, if the stub uses qOffsets. */
8654 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8655 the list of conditions (in agent expression bytecode format), if any, the
8656 target needs to evaluate. The output is placed into the packet buffer
8657 started from BUF and ended at BUF_END. */
8660 remote_add_target_side_condition (struct gdbarch *gdbarch,
8661 struct bp_target_info *bp_tgt, char *buf,
8664 struct agent_expr *aexpr = NULL;
8667 char *buf_start = buf;
8669 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8672 buf += strlen (buf);
8673 xsnprintf (buf, buf_end - buf, "%s", ";");
8676 /* Send conditions to the target and free the vector. */
8678 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8681 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8682 buf += strlen (buf);
8683 for (i = 0; i < aexpr->len; ++i)
8684 buf = pack_hex_byte (buf, aexpr->buf[i]);
8691 remote_add_target_side_commands (struct gdbarch *gdbarch,
8692 struct bp_target_info *bp_tgt, char *buf)
8694 struct agent_expr *aexpr = NULL;
8697 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8700 buf += strlen (buf);
8702 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8703 buf += strlen (buf);
8705 /* Concatenate all the agent expressions that are commands into the
8708 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8711 sprintf (buf, "X%x,", aexpr->len);
8712 buf += strlen (buf);
8713 for (i = 0; i < aexpr->len; ++i)
8714 buf = pack_hex_byte (buf, aexpr->buf[i]);
8719 /* Insert a breakpoint. On targets that have software breakpoint
8720 support, we ask the remote target to do the work; on targets
8721 which don't, we insert a traditional memory breakpoint. */
8724 remote_insert_breakpoint (struct target_ops *ops,
8725 struct gdbarch *gdbarch,
8726 struct bp_target_info *bp_tgt)
8728 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8729 If it succeeds, then set the support to PACKET_ENABLE. If it
8730 fails, and the user has explicitly requested the Z support then
8731 report an error, otherwise, mark it disabled and go on. */
8733 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8735 CORE_ADDR addr = bp_tgt->reqstd_address;
8736 struct remote_state *rs;
8739 struct condition_list *cond = NULL;
8741 /* Make sure the remote is pointing at the right process, if
8743 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8744 set_general_process ();
8746 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8748 rs = get_remote_state ();
8750 endbuf = rs->buf + get_remote_packet_size ();
8755 addr = (ULONGEST) remote_address_masked (addr);
8756 p += hexnumstr (p, addr);
8757 xsnprintf (p, endbuf - p, ",%d", bpsize);
8759 if (remote_supports_cond_breakpoints (ops))
8760 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8762 if (remote_can_run_breakpoint_commands (ops))
8763 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8766 getpkt (&rs->buf, &rs->buf_size, 0);
8768 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8773 bp_tgt->placed_address = addr;
8774 bp_tgt->placed_size = bpsize;
8776 case PACKET_UNKNOWN:
8781 /* If this breakpoint has target-side commands but this stub doesn't
8782 support Z0 packets, throw error. */
8783 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8784 throw_error (NOT_SUPPORTED_ERROR, _("\
8785 Target doesn't support breakpoints that have target side commands."));
8787 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8791 remote_remove_breakpoint (struct target_ops *ops,
8792 struct gdbarch *gdbarch,
8793 struct bp_target_info *bp_tgt)
8795 CORE_ADDR addr = bp_tgt->placed_address;
8796 struct remote_state *rs = get_remote_state ();
8798 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8801 char *endbuf = rs->buf + get_remote_packet_size ();
8803 /* Make sure the remote is pointing at the right process, if
8805 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8806 set_general_process ();
8812 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8813 p += hexnumstr (p, addr);
8814 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8817 getpkt (&rs->buf, &rs->buf_size, 0);
8819 return (rs->buf[0] == 'E');
8822 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8825 static enum Z_packet_type
8826 watchpoint_to_Z_packet (int type)
8831 return Z_PACKET_WRITE_WP;
8834 return Z_PACKET_READ_WP;
8837 return Z_PACKET_ACCESS_WP;
8840 internal_error (__FILE__, __LINE__,
8841 _("hw_bp_to_z: bad watchpoint type %d"), type);
8846 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8847 enum target_hw_bp_type type, struct expression *cond)
8849 struct remote_state *rs = get_remote_state ();
8850 char *endbuf = rs->buf + get_remote_packet_size ();
8852 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8854 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8857 /* Make sure the remote is pointing at the right process, if
8859 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8860 set_general_process ();
8862 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8863 p = strchr (rs->buf, '\0');
8864 addr = remote_address_masked (addr);
8865 p += hexnumstr (p, (ULONGEST) addr);
8866 xsnprintf (p, endbuf - p, ",%x", len);
8869 getpkt (&rs->buf, &rs->buf_size, 0);
8871 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8875 case PACKET_UNKNOWN:
8880 internal_error (__FILE__, __LINE__,
8881 _("remote_insert_watchpoint: reached end of function"));
8885 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8886 CORE_ADDR start, int length)
8888 CORE_ADDR diff = remote_address_masked (addr - start);
8890 return diff < length;
8895 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8896 enum target_hw_bp_type type, struct expression *cond)
8898 struct remote_state *rs = get_remote_state ();
8899 char *endbuf = rs->buf + get_remote_packet_size ();
8901 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8903 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8906 /* Make sure the remote is pointing at the right process, if
8908 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8909 set_general_process ();
8911 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8912 p = strchr (rs->buf, '\0');
8913 addr = remote_address_masked (addr);
8914 p += hexnumstr (p, (ULONGEST) addr);
8915 xsnprintf (p, endbuf - p, ",%x", len);
8917 getpkt (&rs->buf, &rs->buf_size, 0);
8919 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8922 case PACKET_UNKNOWN:
8927 internal_error (__FILE__, __LINE__,
8928 _("remote_remove_watchpoint: reached end of function"));
8932 int remote_hw_watchpoint_limit = -1;
8933 int remote_hw_watchpoint_length_limit = -1;
8934 int remote_hw_breakpoint_limit = -1;
8937 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8938 CORE_ADDR addr, int len)
8940 if (remote_hw_watchpoint_length_limit == 0)
8942 else if (remote_hw_watchpoint_length_limit < 0)
8944 else if (len <= remote_hw_watchpoint_length_limit)
8951 remote_check_watch_resources (struct target_ops *self,
8952 enum bptype type, int cnt, int ot)
8954 if (type == bp_hardware_breakpoint)
8956 if (remote_hw_breakpoint_limit == 0)
8958 else if (remote_hw_breakpoint_limit < 0)
8960 else if (cnt <= remote_hw_breakpoint_limit)
8965 if (remote_hw_watchpoint_limit == 0)
8967 else if (remote_hw_watchpoint_limit < 0)
8971 else if (cnt <= remote_hw_watchpoint_limit)
8977 /* The to_stopped_by_sw_breakpoint method of target remote. */
8980 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8982 struct remote_state *rs = get_remote_state ();
8984 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8987 /* The to_supports_stopped_by_sw_breakpoint method of target
8991 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8993 struct remote_state *rs = get_remote_state ();
8995 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8998 /* The to_stopped_by_hw_breakpoint method of target remote. */
9001 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9003 struct remote_state *rs = get_remote_state ();
9005 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9008 /* The to_supports_stopped_by_hw_breakpoint method of target
9012 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9014 struct remote_state *rs = get_remote_state ();
9016 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9020 remote_stopped_by_watchpoint (struct target_ops *ops)
9022 struct remote_state *rs = get_remote_state ();
9024 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
9028 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9030 struct remote_state *rs = get_remote_state ();
9033 if (remote_stopped_by_watchpoint (target))
9035 *addr_p = rs->remote_watch_data_address;
9044 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9045 struct bp_target_info *bp_tgt)
9047 CORE_ADDR addr = bp_tgt->reqstd_address;
9048 struct remote_state *rs;
9053 /* The length field should be set to the size of a breakpoint
9054 instruction, even though we aren't inserting one ourselves. */
9056 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9058 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9061 /* Make sure the remote is pointing at the right process, if
9063 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9064 set_general_process ();
9066 rs = get_remote_state ();
9068 endbuf = rs->buf + get_remote_packet_size ();
9074 addr = remote_address_masked (addr);
9075 p += hexnumstr (p, (ULONGEST) addr);
9076 xsnprintf (p, endbuf - p, ",%x", bpsize);
9078 if (remote_supports_cond_breakpoints (self))
9079 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9081 if (remote_can_run_breakpoint_commands (self))
9082 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9085 getpkt (&rs->buf, &rs->buf_size, 0);
9087 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9090 if (rs->buf[1] == '.')
9092 message = strchr (rs->buf + 2, '.');
9094 error (_("Remote failure reply: %s"), message + 1);
9097 case PACKET_UNKNOWN:
9100 bp_tgt->placed_address = addr;
9101 bp_tgt->placed_size = bpsize;
9104 internal_error (__FILE__, __LINE__,
9105 _("remote_insert_hw_breakpoint: reached end of function"));
9110 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9111 struct bp_target_info *bp_tgt)
9114 struct remote_state *rs = get_remote_state ();
9116 char *endbuf = rs->buf + get_remote_packet_size ();
9118 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9121 /* Make sure the remote is pointing at the right process, if
9123 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9124 set_general_process ();
9130 addr = remote_address_masked (bp_tgt->placed_address);
9131 p += hexnumstr (p, (ULONGEST) addr);
9132 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9135 getpkt (&rs->buf, &rs->buf_size, 0);
9137 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9140 case PACKET_UNKNOWN:
9145 internal_error (__FILE__, __LINE__,
9146 _("remote_remove_hw_breakpoint: reached end of function"));
9149 /* Verify memory using the "qCRC:" request. */
9152 remote_verify_memory (struct target_ops *ops,
9153 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9155 struct remote_state *rs = get_remote_state ();
9156 unsigned long host_crc, target_crc;
9159 /* It doesn't make sense to use qCRC if the remote target is
9160 connected but not running. */
9161 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9163 enum packet_result result;
9165 /* Make sure the remote is pointing at the right process. */
9166 set_general_process ();
9168 /* FIXME: assumes lma can fit into long. */
9169 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9170 (long) lma, (long) size);
9173 /* Be clever; compute the host_crc before waiting for target
9175 host_crc = xcrc32 (data, size, 0xffffffff);
9177 getpkt (&rs->buf, &rs->buf_size, 0);
9179 result = packet_ok (rs->buf,
9180 &remote_protocol_packets[PACKET_qCRC]);
9181 if (result == PACKET_ERROR)
9183 else if (result == PACKET_OK)
9185 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9186 target_crc = target_crc * 16 + fromhex (*tmp);
9188 return (host_crc == target_crc);
9192 return simple_verify_memory (ops, data, lma, size);
9195 /* compare-sections command
9197 With no arguments, compares each loadable section in the exec bfd
9198 with the same memory range on the target, and reports mismatches.
9199 Useful for verifying the image on the target against the exec file. */
9202 compare_sections_command (char *args, int from_tty)
9205 struct cleanup *old_chain;
9207 const char *sectname;
9216 error (_("command cannot be used without an exec file"));
9218 /* Make sure the remote is pointing at the right process. */
9219 set_general_process ();
9221 if (args != NULL && strcmp (args, "-r") == 0)
9227 for (s = exec_bfd->sections; s; s = s->next)
9229 if (!(s->flags & SEC_LOAD))
9230 continue; /* Skip non-loadable section. */
9232 if (read_only && (s->flags & SEC_READONLY) == 0)
9233 continue; /* Skip writeable sections */
9235 size = bfd_get_section_size (s);
9237 continue; /* Skip zero-length section. */
9239 sectname = bfd_get_section_name (exec_bfd, s);
9240 if (args && strcmp (args, sectname) != 0)
9241 continue; /* Not the section selected by user. */
9243 matched = 1; /* Do this section. */
9246 sectdata = xmalloc (size);
9247 old_chain = make_cleanup (xfree, sectdata);
9248 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9250 res = target_verify_memory (sectdata, lma, size);
9253 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9254 paddress (target_gdbarch (), lma),
9255 paddress (target_gdbarch (), lma + size));
9257 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9258 paddress (target_gdbarch (), lma),
9259 paddress (target_gdbarch (), lma + size));
9261 printf_filtered ("matched.\n");
9264 printf_filtered ("MIS-MATCHED!\n");
9268 do_cleanups (old_chain);
9271 warning (_("One or more sections of the target image does not match\n\
9272 the loaded file\n"));
9273 if (args && !matched)
9274 printf_filtered (_("No loaded section named '%s'.\n"), args);
9277 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9278 into remote target. The number of bytes written to the remote
9279 target is returned, or -1 for error. */
9281 static enum target_xfer_status
9282 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9283 const char *annex, const gdb_byte *writebuf,
9284 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9285 struct packet_config *packet)
9289 struct remote_state *rs = get_remote_state ();
9290 int max_size = get_memory_write_packet_size ();
9292 if (packet->support == PACKET_DISABLE)
9293 return TARGET_XFER_E_IO;
9295 /* Insert header. */
9296 i = snprintf (rs->buf, max_size,
9297 "qXfer:%s:write:%s:%s:",
9298 object_name, annex ? annex : "",
9299 phex_nz (offset, sizeof offset));
9300 max_size -= (i + 1);
9302 /* Escape as much data as fits into rs->buf. */
9303 buf_len = remote_escape_output
9304 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9306 if (putpkt_binary (rs->buf, i + buf_len) < 0
9307 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9308 || packet_ok (rs->buf, packet) != PACKET_OK)
9309 return TARGET_XFER_E_IO;
9311 unpack_varlen_hex (rs->buf, &n);
9314 return TARGET_XFER_OK;
9317 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9318 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9319 number of bytes read is returned, or 0 for EOF, or -1 for error.
9320 The number of bytes read may be less than LEN without indicating an
9321 EOF. PACKET is checked and updated to indicate whether the remote
9322 target supports this object. */
9324 static enum target_xfer_status
9325 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9327 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9328 ULONGEST *xfered_len,
9329 struct packet_config *packet)
9331 struct remote_state *rs = get_remote_state ();
9332 LONGEST i, n, packet_len;
9334 if (packet->support == PACKET_DISABLE)
9335 return TARGET_XFER_E_IO;
9337 /* Check whether we've cached an end-of-object packet that matches
9339 if (rs->finished_object)
9341 if (strcmp (object_name, rs->finished_object) == 0
9342 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9343 && offset == rs->finished_offset)
9344 return TARGET_XFER_EOF;
9347 /* Otherwise, we're now reading something different. Discard
9349 xfree (rs->finished_object);
9350 xfree (rs->finished_annex);
9351 rs->finished_object = NULL;
9352 rs->finished_annex = NULL;
9355 /* Request only enough to fit in a single packet. The actual data
9356 may not, since we don't know how much of it will need to be escaped;
9357 the target is free to respond with slightly less data. We subtract
9358 five to account for the response type and the protocol frame. */
9359 n = min (get_remote_packet_size () - 5, len);
9360 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9361 object_name, annex ? annex : "",
9362 phex_nz (offset, sizeof offset),
9363 phex_nz (n, sizeof n));
9364 i = putpkt (rs->buf);
9366 return TARGET_XFER_E_IO;
9369 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9370 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9371 return TARGET_XFER_E_IO;
9373 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9374 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9376 /* 'm' means there is (or at least might be) more data after this
9377 batch. That does not make sense unless there's at least one byte
9378 of data in this reply. */
9379 if (rs->buf[0] == 'm' && packet_len == 1)
9380 error (_("Remote qXfer reply contained no data."));
9382 /* Got some data. */
9383 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9384 packet_len - 1, readbuf, n);
9386 /* 'l' is an EOF marker, possibly including a final block of data,
9387 or possibly empty. If we have the final block of a non-empty
9388 object, record this fact to bypass a subsequent partial read. */
9389 if (rs->buf[0] == 'l' && offset + i > 0)
9391 rs->finished_object = xstrdup (object_name);
9392 rs->finished_annex = xstrdup (annex ? annex : "");
9393 rs->finished_offset = offset + i;
9397 return TARGET_XFER_EOF;
9401 return TARGET_XFER_OK;
9405 static enum target_xfer_status
9406 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9407 const char *annex, gdb_byte *readbuf,
9408 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9409 ULONGEST *xfered_len)
9411 struct remote_state *rs;
9415 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9417 set_remote_traceframe ();
9418 set_general_thread (inferior_ptid);
9420 rs = get_remote_state ();
9422 /* Handle memory using the standard memory routines. */
9423 if (object == TARGET_OBJECT_MEMORY)
9425 /* If the remote target is connected but not running, we should
9426 pass this request down to a lower stratum (e.g. the executable
9428 if (!target_has_execution)
9429 return TARGET_XFER_EOF;
9431 if (writebuf != NULL)
9432 return remote_write_bytes (offset, writebuf, len, unit_size,
9435 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9439 /* Handle SPU memory using qxfer packets. */
9440 if (object == TARGET_OBJECT_SPU)
9443 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9444 xfered_len, &remote_protocol_packets
9445 [PACKET_qXfer_spu_read]);
9447 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9448 xfered_len, &remote_protocol_packets
9449 [PACKET_qXfer_spu_write]);
9452 /* Handle extra signal info using qxfer packets. */
9453 if (object == TARGET_OBJECT_SIGNAL_INFO)
9456 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9457 xfered_len, &remote_protocol_packets
9458 [PACKET_qXfer_siginfo_read]);
9460 return remote_write_qxfer (ops, "siginfo", annex,
9461 writebuf, offset, len, xfered_len,
9462 &remote_protocol_packets
9463 [PACKET_qXfer_siginfo_write]);
9466 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9469 return remote_read_qxfer (ops, "statictrace", annex,
9470 readbuf, offset, len, xfered_len,
9471 &remote_protocol_packets
9472 [PACKET_qXfer_statictrace_read]);
9474 return TARGET_XFER_E_IO;
9477 /* Only handle flash writes. */
9478 if (writebuf != NULL)
9484 case TARGET_OBJECT_FLASH:
9485 return remote_flash_write (ops, offset, len, xfered_len,
9489 return TARGET_XFER_E_IO;
9493 /* Map pre-existing objects onto letters. DO NOT do this for new
9494 objects!!! Instead specify new query packets. */
9497 case TARGET_OBJECT_AVR:
9501 case TARGET_OBJECT_AUXV:
9502 gdb_assert (annex == NULL);
9503 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9505 &remote_protocol_packets[PACKET_qXfer_auxv]);
9507 case TARGET_OBJECT_AVAILABLE_FEATURES:
9508 return remote_read_qxfer
9509 (ops, "features", annex, readbuf, offset, len, xfered_len,
9510 &remote_protocol_packets[PACKET_qXfer_features]);
9512 case TARGET_OBJECT_LIBRARIES:
9513 return remote_read_qxfer
9514 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9515 &remote_protocol_packets[PACKET_qXfer_libraries]);
9517 case TARGET_OBJECT_LIBRARIES_SVR4:
9518 return remote_read_qxfer
9519 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9520 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9522 case TARGET_OBJECT_MEMORY_MAP:
9523 gdb_assert (annex == NULL);
9524 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9526 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9528 case TARGET_OBJECT_OSDATA:
9529 /* Should only get here if we're connected. */
9530 gdb_assert (rs->remote_desc);
9531 return remote_read_qxfer
9532 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9533 &remote_protocol_packets[PACKET_qXfer_osdata]);
9535 case TARGET_OBJECT_THREADS:
9536 gdb_assert (annex == NULL);
9537 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9539 &remote_protocol_packets[PACKET_qXfer_threads]);
9541 case TARGET_OBJECT_TRACEFRAME_INFO:
9542 gdb_assert (annex == NULL);
9543 return remote_read_qxfer
9544 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9545 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9547 case TARGET_OBJECT_FDPIC:
9548 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9550 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9552 case TARGET_OBJECT_OPENVMS_UIB:
9553 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9555 &remote_protocol_packets[PACKET_qXfer_uib]);
9557 case TARGET_OBJECT_BTRACE:
9558 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9560 &remote_protocol_packets[PACKET_qXfer_btrace]);
9562 case TARGET_OBJECT_BTRACE_CONF:
9563 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9565 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9567 case TARGET_OBJECT_EXEC_FILE:
9568 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9570 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9573 return TARGET_XFER_E_IO;
9576 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9577 large enough let the caller deal with it. */
9578 if (len < get_remote_packet_size ())
9579 return TARGET_XFER_E_IO;
9580 len = get_remote_packet_size ();
9582 /* Except for querying the minimum buffer size, target must be open. */
9583 if (!rs->remote_desc)
9584 error (_("remote query is only available after target open"));
9586 gdb_assert (annex != NULL);
9587 gdb_assert (readbuf != NULL);
9593 /* We used one buffer char for the remote protocol q command and
9594 another for the query type. As the remote protocol encapsulation
9595 uses 4 chars plus one extra in case we are debugging
9596 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9599 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9601 /* Bad caller may have sent forbidden characters. */
9602 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9607 gdb_assert (annex[i] == '\0');
9609 i = putpkt (rs->buf);
9611 return TARGET_XFER_E_IO;
9613 getpkt (&rs->buf, &rs->buf_size, 0);
9614 strcpy ((char *) readbuf, rs->buf);
9616 *xfered_len = strlen ((char *) readbuf);
9617 return TARGET_XFER_OK;
9621 remote_search_memory (struct target_ops* ops,
9622 CORE_ADDR start_addr, ULONGEST search_space_len,
9623 const gdb_byte *pattern, ULONGEST pattern_len,
9624 CORE_ADDR *found_addrp)
9626 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9627 struct remote_state *rs = get_remote_state ();
9628 int max_size = get_memory_write_packet_size ();
9629 struct packet_config *packet =
9630 &remote_protocol_packets[PACKET_qSearch_memory];
9631 /* Number of packet bytes used to encode the pattern;
9632 this could be more than PATTERN_LEN due to escape characters. */
9633 int escaped_pattern_len;
9634 /* Amount of pattern that was encodable in the packet. */
9635 int used_pattern_len;
9638 ULONGEST found_addr;
9640 /* Don't go to the target if we don't have to.
9641 This is done before checking packet->support to avoid the possibility that
9642 a success for this edge case means the facility works in general. */
9643 if (pattern_len > search_space_len)
9645 if (pattern_len == 0)
9647 *found_addrp = start_addr;
9651 /* If we already know the packet isn't supported, fall back to the simple
9652 way of searching memory. */
9654 if (packet_config_support (packet) == PACKET_DISABLE)
9656 /* Target doesn't provided special support, fall back and use the
9657 standard support (copy memory and do the search here). */
9658 return simple_search_memory (ops, start_addr, search_space_len,
9659 pattern, pattern_len, found_addrp);
9662 /* Make sure the remote is pointing at the right process. */
9663 set_general_process ();
9665 /* Insert header. */
9666 i = snprintf (rs->buf, max_size,
9667 "qSearch:memory:%s;%s;",
9668 phex_nz (start_addr, addr_size),
9669 phex_nz (search_space_len, sizeof (search_space_len)));
9670 max_size -= (i + 1);
9672 /* Escape as much data as fits into rs->buf. */
9673 escaped_pattern_len =
9674 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
9675 &used_pattern_len, max_size);
9677 /* Bail if the pattern is too large. */
9678 if (used_pattern_len != pattern_len)
9679 error (_("Pattern is too large to transmit to remote target."));
9681 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9682 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9683 || packet_ok (rs->buf, packet) != PACKET_OK)
9685 /* The request may not have worked because the command is not
9686 supported. If so, fall back to the simple way. */
9687 if (packet->support == PACKET_DISABLE)
9689 return simple_search_memory (ops, start_addr, search_space_len,
9690 pattern, pattern_len, found_addrp);
9695 if (rs->buf[0] == '0')
9697 else if (rs->buf[0] == '1')
9700 if (rs->buf[1] != ',')
9701 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9702 unpack_varlen_hex (rs->buf + 2, &found_addr);
9703 *found_addrp = found_addr;
9706 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9712 remote_rcmd (struct target_ops *self, const char *command,
9713 struct ui_file *outbuf)
9715 struct remote_state *rs = get_remote_state ();
9718 if (!rs->remote_desc)
9719 error (_("remote rcmd is only available after target open"));
9721 /* Send a NULL command across as an empty command. */
9722 if (command == NULL)
9725 /* The query prefix. */
9726 strcpy (rs->buf, "qRcmd,");
9727 p = strchr (rs->buf, '\0');
9729 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9730 > get_remote_packet_size ())
9731 error (_("\"monitor\" command ``%s'' is too long."), command);
9733 /* Encode the actual command. */
9734 bin2hex ((const gdb_byte *) command, p, strlen (command));
9736 if (putpkt (rs->buf) < 0)
9737 error (_("Communication problem with target."));
9739 /* get/display the response */
9744 /* XXX - see also remote_get_noisy_reply(). */
9745 QUIT; /* Allow user to bail out with ^C. */
9747 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9749 /* Timeout. Continue to (try to) read responses.
9750 This is better than stopping with an error, assuming the stub
9751 is still executing the (long) monitor command.
9752 If needed, the user can interrupt gdb using C-c, obtaining
9753 an effect similar to stop on timeout. */
9758 error (_("Target does not support this command."));
9759 if (buf[0] == 'O' && buf[1] != 'K')
9761 remote_console_output (buf + 1); /* 'O' message from stub. */
9764 if (strcmp (buf, "OK") == 0)
9766 if (strlen (buf) == 3 && buf[0] == 'E'
9767 && isdigit (buf[1]) && isdigit (buf[2]))
9769 error (_("Protocol error with Rcmd"));
9771 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9773 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9775 fputc_unfiltered (c, outbuf);
9781 static VEC(mem_region_s) *
9782 remote_memory_map (struct target_ops *ops)
9784 VEC(mem_region_s) *result = NULL;
9785 char *text = target_read_stralloc (¤t_target,
9786 TARGET_OBJECT_MEMORY_MAP, NULL);
9790 struct cleanup *back_to = make_cleanup (xfree, text);
9792 result = parse_memory_map (text);
9793 do_cleanups (back_to);
9800 packet_command (char *args, int from_tty)
9802 struct remote_state *rs = get_remote_state ();
9804 if (!rs->remote_desc)
9805 error (_("command can only be used with remote target"));
9808 error (_("remote-packet command requires packet text as argument"));
9810 puts_filtered ("sending: ");
9811 print_packet (args);
9812 puts_filtered ("\n");
9815 getpkt (&rs->buf, &rs->buf_size, 0);
9816 puts_filtered ("received: ");
9817 print_packet (rs->buf);
9818 puts_filtered ("\n");
9822 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9824 static void display_thread_info (struct gdb_ext_thread_info *info);
9826 static void threadset_test_cmd (char *cmd, int tty);
9828 static void threadalive_test (char *cmd, int tty);
9830 static void threadlist_test_cmd (char *cmd, int tty);
9832 int get_and_display_threadinfo (threadref *ref);
9834 static void threadinfo_test_cmd (char *cmd, int tty);
9836 static int thread_display_step (threadref *ref, void *context);
9838 static void threadlist_update_test_cmd (char *cmd, int tty);
9840 static void init_remote_threadtests (void);
9842 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9845 threadset_test_cmd (char *cmd, int tty)
9847 int sample_thread = SAMPLE_THREAD;
9849 printf_filtered (_("Remote threadset test\n"));
9850 set_general_thread (sample_thread);
9855 threadalive_test (char *cmd, int tty)
9857 int sample_thread = SAMPLE_THREAD;
9858 int pid = ptid_get_pid (inferior_ptid);
9859 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9861 if (remote_thread_alive (ptid))
9862 printf_filtered ("PASS: Thread alive test\n");
9864 printf_filtered ("FAIL: Thread alive test\n");
9867 void output_threadid (char *title, threadref *ref);
9870 output_threadid (char *title, threadref *ref)
9874 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9876 printf_filtered ("%s %s\n", title, (&hexid[0]));
9880 threadlist_test_cmd (char *cmd, int tty)
9883 threadref nextthread;
9884 int done, result_count;
9885 threadref threadlist[3];
9887 printf_filtered ("Remote Threadlist test\n");
9888 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9889 &result_count, &threadlist[0]))
9890 printf_filtered ("FAIL: threadlist test\n");
9893 threadref *scan = threadlist;
9894 threadref *limit = scan + result_count;
9896 while (scan < limit)
9897 output_threadid (" thread ", scan++);
9902 display_thread_info (struct gdb_ext_thread_info *info)
9904 output_threadid ("Threadid: ", &info->threadid);
9905 printf_filtered ("Name: %s\n ", info->shortname);
9906 printf_filtered ("State: %s\n", info->display);
9907 printf_filtered ("other: %s\n\n", info->more_display);
9911 get_and_display_threadinfo (threadref *ref)
9915 struct gdb_ext_thread_info threadinfo;
9917 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9918 | TAG_MOREDISPLAY | TAG_DISPLAY;
9919 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9920 display_thread_info (&threadinfo);
9925 threadinfo_test_cmd (char *cmd, int tty)
9927 int athread = SAMPLE_THREAD;
9931 int_to_threadref (&thread, athread);
9932 printf_filtered ("Remote Threadinfo test\n");
9933 if (!get_and_display_threadinfo (&thread))
9934 printf_filtered ("FAIL cannot get thread info\n");
9938 thread_display_step (threadref *ref, void *context)
9940 /* output_threadid(" threadstep ",ref); *//* simple test */
9941 return get_and_display_threadinfo (ref);
9945 threadlist_update_test_cmd (char *cmd, int tty)
9947 printf_filtered ("Remote Threadlist update test\n");
9948 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9952 init_remote_threadtests (void)
9954 add_com ("tlist", class_obscure, threadlist_test_cmd,
9955 _("Fetch and print the remote list of "
9956 "thread identifiers, one pkt only"));
9957 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9958 _("Fetch and display info about one thread"));
9959 add_com ("tset", class_obscure, threadset_test_cmd,
9960 _("Test setting to a different thread"));
9961 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9962 _("Iterate through updating all remote thread info"));
9963 add_com ("talive", class_obscure, threadalive_test,
9964 _(" Remote thread alive test "));
9969 /* Convert a thread ID to a string. Returns the string in a static
9973 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9975 static char buf[64];
9976 struct remote_state *rs = get_remote_state ();
9978 if (ptid_equal (ptid, null_ptid))
9979 return normal_pid_to_str (ptid);
9980 else if (ptid_is_pid (ptid))
9982 /* Printing an inferior target id. */
9984 /* When multi-process extensions are off, there's no way in the
9985 remote protocol to know the remote process id, if there's any
9986 at all. There's one exception --- when we're connected with
9987 target extended-remote, and we manually attached to a process
9988 with "attach PID". We don't record anywhere a flag that
9989 allows us to distinguish that case from the case of
9990 connecting with extended-remote and the stub already being
9991 attached to a process, and reporting yes to qAttached, hence
9992 no smart special casing here. */
9993 if (!remote_multi_process_p (rs))
9995 xsnprintf (buf, sizeof buf, "Remote target");
9999 return normal_pid_to_str (ptid);
10003 if (ptid_equal (magic_null_ptid, ptid))
10004 xsnprintf (buf, sizeof buf, "Thread <main>");
10005 else if (rs->extended && remote_multi_process_p (rs))
10006 if (ptid_get_lwp (ptid) == 0)
10007 return normal_pid_to_str (ptid);
10009 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10010 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10012 xsnprintf (buf, sizeof buf, "Thread %ld",
10013 ptid_get_lwp (ptid));
10018 /* Get the address of the thread local variable in OBJFILE which is
10019 stored at OFFSET within the thread local storage for thread PTID. */
10022 remote_get_thread_local_address (struct target_ops *ops,
10023 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10025 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10027 struct remote_state *rs = get_remote_state ();
10029 char *endp = rs->buf + get_remote_packet_size ();
10030 enum packet_result result;
10032 strcpy (p, "qGetTLSAddr:");
10034 p = write_ptid (p, endp, ptid);
10036 p += hexnumstr (p, offset);
10038 p += hexnumstr (p, lm);
10042 getpkt (&rs->buf, &rs->buf_size, 0);
10043 result = packet_ok (rs->buf,
10044 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10045 if (result == PACKET_OK)
10049 unpack_varlen_hex (rs->buf, &result);
10052 else if (result == PACKET_UNKNOWN)
10053 throw_error (TLS_GENERIC_ERROR,
10054 _("Remote target doesn't support qGetTLSAddr packet"));
10056 throw_error (TLS_GENERIC_ERROR,
10057 _("Remote target failed to process qGetTLSAddr request"));
10060 throw_error (TLS_GENERIC_ERROR,
10061 _("TLS not supported or disabled on this target"));
10066 /* Provide thread local base, i.e. Thread Information Block address.
10067 Returns 1 if ptid is found and thread_local_base is non zero. */
10070 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10072 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10074 struct remote_state *rs = get_remote_state ();
10076 char *endp = rs->buf + get_remote_packet_size ();
10077 enum packet_result result;
10079 strcpy (p, "qGetTIBAddr:");
10081 p = write_ptid (p, endp, ptid);
10085 getpkt (&rs->buf, &rs->buf_size, 0);
10086 result = packet_ok (rs->buf,
10087 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10088 if (result == PACKET_OK)
10092 unpack_varlen_hex (rs->buf, &result);
10094 *addr = (CORE_ADDR) result;
10097 else if (result == PACKET_UNKNOWN)
10098 error (_("Remote target doesn't support qGetTIBAddr packet"));
10100 error (_("Remote target failed to process qGetTIBAddr request"));
10103 error (_("qGetTIBAddr not supported or disabled on this target"));
10108 /* Support for inferring a target description based on the current
10109 architecture and the size of a 'g' packet. While the 'g' packet
10110 can have any size (since optional registers can be left off the
10111 end), some sizes are easily recognizable given knowledge of the
10112 approximate architecture. */
10114 struct remote_g_packet_guess
10117 const struct target_desc *tdesc;
10119 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10120 DEF_VEC_O(remote_g_packet_guess_s);
10122 struct remote_g_packet_data
10124 VEC(remote_g_packet_guess_s) *guesses;
10127 static struct gdbarch_data *remote_g_packet_data_handle;
10130 remote_g_packet_data_init (struct obstack *obstack)
10132 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10136 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10137 const struct target_desc *tdesc)
10139 struct remote_g_packet_data *data
10140 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10141 struct remote_g_packet_guess new_guess, *guess;
10144 gdb_assert (tdesc != NULL);
10147 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10149 if (guess->bytes == bytes)
10150 internal_error (__FILE__, __LINE__,
10151 _("Duplicate g packet description added for size %d"),
10154 new_guess.bytes = bytes;
10155 new_guess.tdesc = tdesc;
10156 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10159 /* Return 1 if remote_read_description would do anything on this target
10160 and architecture, 0 otherwise. */
10163 remote_read_description_p (struct target_ops *target)
10165 struct remote_g_packet_data *data
10166 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10168 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10174 static const struct target_desc *
10175 remote_read_description (struct target_ops *target)
10177 struct remote_g_packet_data *data
10178 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10180 /* Do not try this during initial connection, when we do not know
10181 whether there is a running but stopped thread. */
10182 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10183 return target->beneath->to_read_description (target->beneath);
10185 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10187 struct remote_g_packet_guess *guess;
10189 int bytes = send_g_packet ();
10192 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10194 if (guess->bytes == bytes)
10195 return guess->tdesc;
10197 /* We discard the g packet. A minor optimization would be to
10198 hold on to it, and fill the register cache once we have selected
10199 an architecture, but it's too tricky to do safely. */
10202 return target->beneath->to_read_description (target->beneath);
10205 /* Remote file transfer support. This is host-initiated I/O, not
10206 target-initiated; for target-initiated, see remote-fileio.c. */
10208 /* If *LEFT is at least the length of STRING, copy STRING to
10209 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10210 decrease *LEFT. Otherwise raise an error. */
10213 remote_buffer_add_string (char **buffer, int *left, char *string)
10215 int len = strlen (string);
10218 error (_("Packet too long for target."));
10220 memcpy (*buffer, string, len);
10224 /* NUL-terminate the buffer as a convenience, if there is
10230 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10231 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10232 decrease *LEFT. Otherwise raise an error. */
10235 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10238 if (2 * len > *left)
10239 error (_("Packet too long for target."));
10241 bin2hex (bytes, *buffer, len);
10242 *buffer += 2 * len;
10245 /* NUL-terminate the buffer as a convenience, if there is
10251 /* If *LEFT is large enough, convert VALUE to hex and add it to
10252 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10253 decrease *LEFT. Otherwise raise an error. */
10256 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10258 int len = hexnumlen (value);
10261 error (_("Packet too long for target."));
10263 hexnumstr (*buffer, value);
10267 /* NUL-terminate the buffer as a convenience, if there is
10273 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10274 value, *REMOTE_ERRNO to the remote error number or zero if none
10275 was included, and *ATTACHMENT to point to the start of the annex
10276 if any. The length of the packet isn't needed here; there may
10277 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10279 Return 0 if the packet could be parsed, -1 if it could not. If
10280 -1 is returned, the other variables may not be initialized. */
10283 remote_hostio_parse_result (char *buffer, int *retcode,
10284 int *remote_errno, char **attachment)
10289 *attachment = NULL;
10291 if (buffer[0] != 'F')
10295 *retcode = strtol (&buffer[1], &p, 16);
10296 if (errno != 0 || p == &buffer[1])
10299 /* Check for ",errno". */
10303 *remote_errno = strtol (p + 1, &p2, 16);
10304 if (errno != 0 || p + 1 == p2)
10309 /* Check for ";attachment". If there is no attachment, the
10310 packet should end here. */
10313 *attachment = p + 1;
10316 else if (*p == '\0')
10322 /* Send a prepared I/O packet to the target and read its response.
10323 The prepared packet is in the global RS->BUF before this function
10324 is called, and the answer is there when we return.
10326 COMMAND_BYTES is the length of the request to send, which may include
10327 binary data. WHICH_PACKET is the packet configuration to check
10328 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10329 is set to the error number and -1 is returned. Otherwise the value
10330 returned by the function is returned.
10332 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10333 attachment is expected; an error will be reported if there's a
10334 mismatch. If one is found, *ATTACHMENT will be set to point into
10335 the packet buffer and *ATTACHMENT_LEN will be set to the
10336 attachment's length. */
10339 remote_hostio_send_command (int command_bytes, int which_packet,
10340 int *remote_errno, char **attachment,
10341 int *attachment_len)
10343 struct remote_state *rs = get_remote_state ();
10344 int ret, bytes_read;
10345 char *attachment_tmp;
10347 if (!rs->remote_desc
10348 || packet_support (which_packet) == PACKET_DISABLE)
10350 *remote_errno = FILEIO_ENOSYS;
10354 putpkt_binary (rs->buf, command_bytes);
10355 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10357 /* If it timed out, something is wrong. Don't try to parse the
10359 if (bytes_read < 0)
10361 *remote_errno = FILEIO_EINVAL;
10365 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10368 *remote_errno = FILEIO_EINVAL;
10370 case PACKET_UNKNOWN:
10371 *remote_errno = FILEIO_ENOSYS;
10377 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10380 *remote_errno = FILEIO_EINVAL;
10384 /* Make sure we saw an attachment if and only if we expected one. */
10385 if ((attachment_tmp == NULL && attachment != NULL)
10386 || (attachment_tmp != NULL && attachment == NULL))
10388 *remote_errno = FILEIO_EINVAL;
10392 /* If an attachment was found, it must point into the packet buffer;
10393 work out how many bytes there were. */
10394 if (attachment_tmp != NULL)
10396 *attachment = attachment_tmp;
10397 *attachment_len = bytes_read - (*attachment - rs->buf);
10403 /* Set the filesystem remote_hostio functions that take FILENAME
10404 arguments will use. Return 0 on success, or -1 if an error
10405 occurs (and set *REMOTE_ERRNO). */
10408 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10410 struct remote_state *rs = get_remote_state ();
10411 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10413 int left = get_remote_packet_size () - 1;
10417 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10420 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10423 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10425 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10426 remote_buffer_add_string (&p, &left, arg);
10428 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10429 remote_errno, NULL, NULL);
10431 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10435 rs->fs_pid = required_pid;
10440 /* Implementation of to_fileio_open. */
10443 remote_hostio_open (struct target_ops *self,
10444 struct inferior *inf, const char *filename,
10445 int flags, int mode, int *remote_errno)
10447 struct remote_state *rs = get_remote_state ();
10449 int left = get_remote_packet_size () - 1;
10451 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10454 remote_buffer_add_string (&p, &left, "vFile:open:");
10456 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10457 strlen (filename));
10458 remote_buffer_add_string (&p, &left, ",");
10460 remote_buffer_add_int (&p, &left, flags);
10461 remote_buffer_add_string (&p, &left, ",");
10463 remote_buffer_add_int (&p, &left, mode);
10465 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10466 remote_errno, NULL, NULL);
10469 /* Implementation of to_fileio_pwrite. */
10472 remote_hostio_pwrite (struct target_ops *self,
10473 int fd, const gdb_byte *write_buf, int len,
10474 ULONGEST offset, int *remote_errno)
10476 struct remote_state *rs = get_remote_state ();
10478 int left = get_remote_packet_size ();
10481 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10483 remote_buffer_add_int (&p, &left, fd);
10484 remote_buffer_add_string (&p, &left, ",");
10486 remote_buffer_add_int (&p, &left, offset);
10487 remote_buffer_add_string (&p, &left, ",");
10489 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10490 get_remote_packet_size () - (p - rs->buf));
10492 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10493 remote_errno, NULL, NULL);
10496 /* Implementation of to_fileio_pread. */
10499 remote_hostio_pread (struct target_ops *self,
10500 int fd, gdb_byte *read_buf, int len,
10501 ULONGEST offset, int *remote_errno)
10503 struct remote_state *rs = get_remote_state ();
10506 int left = get_remote_packet_size ();
10507 int ret, attachment_len;
10510 remote_buffer_add_string (&p, &left, "vFile:pread:");
10512 remote_buffer_add_int (&p, &left, fd);
10513 remote_buffer_add_string (&p, &left, ",");
10515 remote_buffer_add_int (&p, &left, len);
10516 remote_buffer_add_string (&p, &left, ",");
10518 remote_buffer_add_int (&p, &left, offset);
10520 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10521 remote_errno, &attachment,
10527 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10529 if (read_len != ret)
10530 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10535 /* Implementation of to_fileio_close. */
10538 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
10540 struct remote_state *rs = get_remote_state ();
10542 int left = get_remote_packet_size () - 1;
10544 remote_buffer_add_string (&p, &left, "vFile:close:");
10546 remote_buffer_add_int (&p, &left, fd);
10548 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10549 remote_errno, NULL, NULL);
10552 /* Implementation of to_fileio_unlink. */
10555 remote_hostio_unlink (struct target_ops *self,
10556 struct inferior *inf, const char *filename,
10559 struct remote_state *rs = get_remote_state ();
10561 int left = get_remote_packet_size () - 1;
10563 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10566 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10568 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10569 strlen (filename));
10571 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10572 remote_errno, NULL, NULL);
10575 /* Implementation of to_fileio_readlink. */
10578 remote_hostio_readlink (struct target_ops *self,
10579 struct inferior *inf, const char *filename,
10582 struct remote_state *rs = get_remote_state ();
10585 int left = get_remote_packet_size ();
10586 int len, attachment_len;
10590 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10593 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10595 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10596 strlen (filename));
10598 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10599 remote_errno, &attachment,
10605 ret = xmalloc (len + 1);
10607 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10608 (gdb_byte *) ret, len);
10609 if (read_len != len)
10610 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10616 /* Implementation of to_fileio_fstat. */
10619 remote_hostio_fstat (struct target_ops *self,
10620 int fd, struct stat *st,
10623 struct remote_state *rs = get_remote_state ();
10625 int left = get_remote_packet_size ();
10626 int attachment_len, ret;
10628 struct fio_stat fst;
10631 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10633 remote_buffer_add_int (&p, &left, fd);
10635 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10636 remote_errno, &attachment,
10640 if (*remote_errno != FILEIO_ENOSYS)
10643 /* Strictly we should return -1, ENOSYS here, but when
10644 "set sysroot remote:" was implemented in August 2008
10645 BFD's need for a stat function was sidestepped with
10646 this hack. This was not remedied until March 2015
10647 so we retain the previous behavior to avoid breaking
10650 Note that the memset is a March 2015 addition; older
10651 GDBs set st_size *and nothing else* so the structure
10652 would have garbage in all other fields. This might
10653 break something but retaining the previous behavior
10654 here would be just too wrong. */
10656 memset (st, 0, sizeof (struct stat));
10657 st->st_size = INT_MAX;
10661 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10662 (gdb_byte *) &fst, sizeof (fst));
10664 if (read_len != ret)
10665 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10667 if (read_len != sizeof (fst))
10668 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10669 read_len, (int) sizeof (fst));
10671 remote_fileio_to_host_stat (&fst, st);
10676 /* Implementation of to_filesystem_is_local. */
10679 remote_filesystem_is_local (struct target_ops *self)
10681 /* Valgrind GDB presents itself as a remote target but works
10682 on the local filesystem: it does not implement remote get
10683 and users are not expected to set a sysroot. To handle
10684 this case we treat the remote filesystem as local if the
10685 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10686 does not support vFile:open. */
10687 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
10689 enum packet_support ps = packet_support (PACKET_vFile_open);
10691 if (ps == PACKET_SUPPORT_UNKNOWN)
10693 int fd, remote_errno;
10695 /* Try opening a file to probe support. The supplied
10696 filename is irrelevant, we only care about whether
10697 the stub recognizes the packet or not. */
10698 fd = remote_hostio_open (self, NULL, "just probing",
10699 FILEIO_O_RDONLY, 0700,
10703 remote_hostio_close (self, fd, &remote_errno);
10705 ps = packet_support (PACKET_vFile_open);
10708 if (ps == PACKET_DISABLE)
10710 static int warning_issued = 0;
10712 if (!warning_issued)
10714 warning (_("remote target does not support file"
10715 " transfer, attempting to access files"
10716 " from local filesystem."));
10717 warning_issued = 1;
10728 remote_fileio_errno_to_host (int errnum)
10734 case FILEIO_ENOENT:
10742 case FILEIO_EACCES:
10744 case FILEIO_EFAULT:
10748 case FILEIO_EEXIST:
10750 case FILEIO_ENODEV:
10752 case FILEIO_ENOTDIR:
10754 case FILEIO_EISDIR:
10756 case FILEIO_EINVAL:
10758 case FILEIO_ENFILE:
10760 case FILEIO_EMFILE:
10764 case FILEIO_ENOSPC:
10766 case FILEIO_ESPIPE:
10770 case FILEIO_ENOSYS:
10772 case FILEIO_ENAMETOOLONG:
10773 return ENAMETOOLONG;
10779 remote_hostio_error (int errnum)
10781 int host_error = remote_fileio_errno_to_host (errnum);
10783 if (host_error == -1)
10784 error (_("Unknown remote I/O error %d"), errnum);
10786 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10790 remote_hostio_close_cleanup (void *opaque)
10792 int fd = *(int *) opaque;
10795 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10799 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10801 struct cleanup *back_to, *close_cleanup;
10802 int retcode, fd, remote_errno, bytes, io_size;
10805 int bytes_in_buffer;
10808 struct remote_state *rs = get_remote_state ();
10810 if (!rs->remote_desc)
10811 error (_("command can only be used with remote target"));
10813 file = gdb_fopen_cloexec (local_file, "rb");
10815 perror_with_name (local_file);
10816 back_to = make_cleanup_fclose (file);
10818 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
10819 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10821 0700, &remote_errno);
10823 remote_hostio_error (remote_errno);
10825 /* Send up to this many bytes at once. They won't all fit in the
10826 remote packet limit, so we'll transfer slightly fewer. */
10827 io_size = get_remote_packet_size ();
10828 buffer = xmalloc (io_size);
10829 make_cleanup (xfree, buffer);
10831 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10833 bytes_in_buffer = 0;
10836 while (bytes_in_buffer || !saw_eof)
10840 bytes = fread (buffer + bytes_in_buffer, 1,
10841 io_size - bytes_in_buffer,
10846 error (_("Error reading %s."), local_file);
10849 /* EOF. Unless there is something still in the
10850 buffer from the last iteration, we are done. */
10852 if (bytes_in_buffer == 0)
10860 bytes += bytes_in_buffer;
10861 bytes_in_buffer = 0;
10863 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10865 offset, &remote_errno);
10868 remote_hostio_error (remote_errno);
10869 else if (retcode == 0)
10870 error (_("Remote write of %d bytes returned 0!"), bytes);
10871 else if (retcode < bytes)
10873 /* Short write. Save the rest of the read data for the next
10875 bytes_in_buffer = bytes - retcode;
10876 memmove (buffer, buffer + retcode, bytes_in_buffer);
10882 discard_cleanups (close_cleanup);
10883 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10884 remote_hostio_error (remote_errno);
10887 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10888 do_cleanups (back_to);
10892 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10894 struct cleanup *back_to, *close_cleanup;
10895 int fd, remote_errno, bytes, io_size;
10899 struct remote_state *rs = get_remote_state ();
10901 if (!rs->remote_desc)
10902 error (_("command can only be used with remote target"));
10904 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
10905 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10907 remote_hostio_error (remote_errno);
10909 file = gdb_fopen_cloexec (local_file, "wb");
10911 perror_with_name (local_file);
10912 back_to = make_cleanup_fclose (file);
10914 /* Send up to this many bytes at once. They won't all fit in the
10915 remote packet limit, so we'll transfer slightly fewer. */
10916 io_size = get_remote_packet_size ();
10917 buffer = xmalloc (io_size);
10918 make_cleanup (xfree, buffer);
10920 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10925 bytes = remote_hostio_pread (find_target_at (process_stratum),
10926 fd, buffer, io_size, offset, &remote_errno);
10928 /* Success, but no bytes, means end-of-file. */
10931 remote_hostio_error (remote_errno);
10935 bytes = fwrite (buffer, 1, bytes, file);
10937 perror_with_name (local_file);
10940 discard_cleanups (close_cleanup);
10941 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10942 remote_hostio_error (remote_errno);
10945 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10946 do_cleanups (back_to);
10950 remote_file_delete (const char *remote_file, int from_tty)
10952 int retcode, remote_errno;
10953 struct remote_state *rs = get_remote_state ();
10955 if (!rs->remote_desc)
10956 error (_("command can only be used with remote target"));
10958 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10959 NULL, remote_file, &remote_errno);
10961 remote_hostio_error (remote_errno);
10964 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10968 remote_put_command (char *args, int from_tty)
10970 struct cleanup *back_to;
10974 error_no_arg (_("file to put"));
10976 argv = gdb_buildargv (args);
10977 back_to = make_cleanup_freeargv (argv);
10978 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10979 error (_("Invalid parameters to remote put"));
10981 remote_file_put (argv[0], argv[1], from_tty);
10983 do_cleanups (back_to);
10987 remote_get_command (char *args, int from_tty)
10989 struct cleanup *back_to;
10993 error_no_arg (_("file to get"));
10995 argv = gdb_buildargv (args);
10996 back_to = make_cleanup_freeargv (argv);
10997 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10998 error (_("Invalid parameters to remote get"));
11000 remote_file_get (argv[0], argv[1], from_tty);
11002 do_cleanups (back_to);
11006 remote_delete_command (char *args, int from_tty)
11008 struct cleanup *back_to;
11012 error_no_arg (_("file to delete"));
11014 argv = gdb_buildargv (args);
11015 back_to = make_cleanup_freeargv (argv);
11016 if (argv[0] == NULL || argv[1] != NULL)
11017 error (_("Invalid parameters to remote delete"));
11019 remote_file_delete (argv[0], from_tty);
11021 do_cleanups (back_to);
11025 remote_command (char *args, int from_tty)
11027 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11031 remote_can_execute_reverse (struct target_ops *self)
11033 if (packet_support (PACKET_bs) == PACKET_ENABLE
11034 || packet_support (PACKET_bc) == PACKET_ENABLE)
11041 remote_supports_non_stop (struct target_ops *self)
11047 remote_supports_disable_randomization (struct target_ops *self)
11049 /* Only supported in extended mode. */
11054 remote_supports_multi_process (struct target_ops *self)
11056 struct remote_state *rs = get_remote_state ();
11058 /* Only extended-remote handles being attached to multiple
11059 processes, even though plain remote can use the multi-process
11060 thread id extensions, so that GDB knows the target process's
11062 return rs->extended && remote_multi_process_p (rs);
11066 remote_supports_cond_tracepoints (void)
11068 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11072 remote_supports_cond_breakpoints (struct target_ops *self)
11074 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11078 remote_supports_fast_tracepoints (void)
11080 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11084 remote_supports_static_tracepoints (void)
11086 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11090 remote_supports_install_in_trace (void)
11092 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11096 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11098 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11103 remote_supports_string_tracing (struct target_ops *self)
11105 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11109 remote_can_run_breakpoint_commands (struct target_ops *self)
11111 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11115 remote_trace_init (struct target_ops *self)
11118 remote_get_noisy_reply (&target_buf, &target_buf_size);
11119 if (strcmp (target_buf, "OK") != 0)
11120 error (_("Target does not support this command."));
11123 static void free_actions_list (char **actions_list);
11124 static void free_actions_list_cleanup_wrapper (void *);
11126 free_actions_list_cleanup_wrapper (void *al)
11128 free_actions_list (al);
11132 free_actions_list (char **actions_list)
11136 if (actions_list == 0)
11139 for (ndx = 0; actions_list[ndx]; ndx++)
11140 xfree (actions_list[ndx]);
11142 xfree (actions_list);
11145 /* Recursive routine to walk through command list including loops, and
11146 download packets for each command. */
11149 remote_download_command_source (int num, ULONGEST addr,
11150 struct command_line *cmds)
11152 struct remote_state *rs = get_remote_state ();
11153 struct command_line *cmd;
11155 for (cmd = cmds; cmd; cmd = cmd->next)
11157 QUIT; /* Allow user to bail out with ^C. */
11158 strcpy (rs->buf, "QTDPsrc:");
11159 encode_source_string (num, addr, "cmd", cmd->line,
11160 rs->buf + strlen (rs->buf),
11161 rs->buf_size - strlen (rs->buf));
11163 remote_get_noisy_reply (&target_buf, &target_buf_size);
11164 if (strcmp (target_buf, "OK"))
11165 warning (_("Target does not support source download."));
11167 if (cmd->control_type == while_control
11168 || cmd->control_type == while_stepping_control)
11170 remote_download_command_source (num, addr, *cmd->body_list);
11172 QUIT; /* Allow user to bail out with ^C. */
11173 strcpy (rs->buf, "QTDPsrc:");
11174 encode_source_string (num, addr, "cmd", "end",
11175 rs->buf + strlen (rs->buf),
11176 rs->buf_size - strlen (rs->buf));
11178 remote_get_noisy_reply (&target_buf, &target_buf_size);
11179 if (strcmp (target_buf, "OK"))
11180 warning (_("Target does not support source download."));
11186 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11188 #define BUF_SIZE 2048
11192 char buf[BUF_SIZE];
11193 char **tdp_actions;
11194 char **stepping_actions;
11196 struct cleanup *old_chain = NULL;
11197 struct agent_expr *aexpr;
11198 struct cleanup *aexpr_chain = NULL;
11200 struct breakpoint *b = loc->owner;
11201 struct tracepoint *t = (struct tracepoint *) b;
11203 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11204 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11206 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11209 tpaddr = loc->address;
11210 sprintf_vma (addrbuf, tpaddr);
11211 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11212 addrbuf, /* address */
11213 (b->enable_state == bp_enabled ? 'E' : 'D'),
11214 t->step_count, t->pass_count);
11215 /* Fast tracepoints are mostly handled by the target, but we can
11216 tell the target how big of an instruction block should be moved
11218 if (b->type == bp_fast_tracepoint)
11220 /* Only test for support at download time; we may not know
11221 target capabilities at definition time. */
11222 if (remote_supports_fast_tracepoints ())
11224 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11226 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11227 gdb_insn_length (loc->gdbarch, tpaddr));
11229 /* If it passed validation at definition but fails now,
11230 something is very wrong. */
11231 internal_error (__FILE__, __LINE__,
11232 _("Fast tracepoint not "
11233 "valid during download"));
11236 /* Fast tracepoints are functionally identical to regular
11237 tracepoints, so don't take lack of support as a reason to
11238 give up on the trace run. */
11239 warning (_("Target does not support fast tracepoints, "
11240 "downloading %d as regular tracepoint"), b->number);
11242 else if (b->type == bp_static_tracepoint)
11244 /* Only test for support at download time; we may not know
11245 target capabilities at definition time. */
11246 if (remote_supports_static_tracepoints ())
11248 struct static_tracepoint_marker marker;
11250 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11251 strcat (buf, ":S");
11253 error (_("Static tracepoint not valid during download"));
11256 /* Fast tracepoints are functionally identical to regular
11257 tracepoints, so don't take lack of support as a reason
11258 to give up on the trace run. */
11259 error (_("Target does not support static tracepoints"));
11261 /* If the tracepoint has a conditional, make it into an agent
11262 expression and append to the definition. */
11265 /* Only test support at download time, we may not know target
11266 capabilities at definition time. */
11267 if (remote_supports_cond_tracepoints ())
11269 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11270 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11271 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11273 pkt = buf + strlen (buf);
11274 for (ndx = 0; ndx < aexpr->len; ++ndx)
11275 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11277 do_cleanups (aexpr_chain);
11280 warning (_("Target does not support conditional tracepoints, "
11281 "ignoring tp %d cond"), b->number);
11284 if (b->commands || *default_collect)
11287 remote_get_noisy_reply (&target_buf, &target_buf_size);
11288 if (strcmp (target_buf, "OK"))
11289 error (_("Target does not support tracepoints."));
11291 /* do_single_steps (t); */
11294 for (ndx = 0; tdp_actions[ndx]; ndx++)
11296 QUIT; /* Allow user to bail out with ^C. */
11297 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11298 b->number, addrbuf, /* address */
11300 ((tdp_actions[ndx + 1] || stepping_actions)
11303 remote_get_noisy_reply (&target_buf,
11305 if (strcmp (target_buf, "OK"))
11306 error (_("Error on target while setting tracepoints."));
11309 if (stepping_actions)
11311 for (ndx = 0; stepping_actions[ndx]; ndx++)
11313 QUIT; /* Allow user to bail out with ^C. */
11314 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11315 b->number, addrbuf, /* address */
11316 ((ndx == 0) ? "S" : ""),
11317 stepping_actions[ndx],
11318 (stepping_actions[ndx + 1] ? "-" : ""));
11320 remote_get_noisy_reply (&target_buf,
11322 if (strcmp (target_buf, "OK"))
11323 error (_("Error on target while setting tracepoints."));
11327 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11329 if (b->location != NULL)
11331 strcpy (buf, "QTDPsrc:");
11332 encode_source_string (b->number, loc->address, "at",
11333 event_location_to_string (b->location),
11334 buf + strlen (buf), 2048 - strlen (buf));
11336 remote_get_noisy_reply (&target_buf, &target_buf_size);
11337 if (strcmp (target_buf, "OK"))
11338 warning (_("Target does not support source download."));
11340 if (b->cond_string)
11342 strcpy (buf, "QTDPsrc:");
11343 encode_source_string (b->number, loc->address,
11344 "cond", b->cond_string, buf + strlen (buf),
11345 2048 - strlen (buf));
11347 remote_get_noisy_reply (&target_buf, &target_buf_size);
11348 if (strcmp (target_buf, "OK"))
11349 warning (_("Target does not support source download."));
11351 remote_download_command_source (b->number, loc->address,
11352 breakpoint_commands (b));
11355 do_cleanups (old_chain);
11359 remote_can_download_tracepoint (struct target_ops *self)
11361 struct remote_state *rs = get_remote_state ();
11362 struct trace_status *ts;
11365 /* Don't try to install tracepoints until we've relocated our
11366 symbols, and fetched and merged the target's tracepoint list with
11368 if (rs->starting_up)
11371 ts = current_trace_status ();
11372 status = remote_get_trace_status (self, ts);
11374 if (status == -1 || !ts->running_known || !ts->running)
11377 /* If we are in a tracing experiment, but remote stub doesn't support
11378 installing tracepoint in trace, we have to return. */
11379 if (!remote_supports_install_in_trace ())
11387 remote_download_trace_state_variable (struct target_ops *self,
11388 struct trace_state_variable *tsv)
11390 struct remote_state *rs = get_remote_state ();
11393 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11394 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11396 p = rs->buf + strlen (rs->buf);
11397 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11398 error (_("Trace state variable name too long for tsv definition packet"));
11399 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11402 remote_get_noisy_reply (&target_buf, &target_buf_size);
11403 if (*target_buf == '\0')
11404 error (_("Target does not support this command."));
11405 if (strcmp (target_buf, "OK") != 0)
11406 error (_("Error on target while downloading trace state variable."));
11410 remote_enable_tracepoint (struct target_ops *self,
11411 struct bp_location *location)
11413 struct remote_state *rs = get_remote_state ();
11416 sprintf_vma (addr_buf, location->address);
11417 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11418 location->owner->number, addr_buf);
11420 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11421 if (*rs->buf == '\0')
11422 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11423 if (strcmp (rs->buf, "OK") != 0)
11424 error (_("Error on target while enabling tracepoint."));
11428 remote_disable_tracepoint (struct target_ops *self,
11429 struct bp_location *location)
11431 struct remote_state *rs = get_remote_state ();
11434 sprintf_vma (addr_buf, location->address);
11435 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11436 location->owner->number, addr_buf);
11438 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11439 if (*rs->buf == '\0')
11440 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11441 if (strcmp (rs->buf, "OK") != 0)
11442 error (_("Error on target while disabling tracepoint."));
11446 remote_trace_set_readonly_regions (struct target_ops *self)
11450 bfd_size_type size;
11456 return; /* No information to give. */
11458 strcpy (target_buf, "QTro");
11459 offset = strlen (target_buf);
11460 for (s = exec_bfd->sections; s; s = s->next)
11462 char tmp1[40], tmp2[40];
11465 if ((s->flags & SEC_LOAD) == 0 ||
11466 /* (s->flags & SEC_CODE) == 0 || */
11467 (s->flags & SEC_READONLY) == 0)
11471 vma = bfd_get_section_vma (abfd, s);
11472 size = bfd_get_section_size (s);
11473 sprintf_vma (tmp1, vma);
11474 sprintf_vma (tmp2, vma + size);
11475 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11476 if (offset + sec_length + 1 > target_buf_size)
11478 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
11480 Too many sections for read-only sections definition packet."));
11483 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11485 offset += sec_length;
11489 putpkt (target_buf);
11490 getpkt (&target_buf, &target_buf_size, 0);
11495 remote_trace_start (struct target_ops *self)
11497 putpkt ("QTStart");
11498 remote_get_noisy_reply (&target_buf, &target_buf_size);
11499 if (*target_buf == '\0')
11500 error (_("Target does not support this command."));
11501 if (strcmp (target_buf, "OK") != 0)
11502 error (_("Bogus reply from target: %s"), target_buf);
11506 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11508 /* Initialize it just to avoid a GCC false warning. */
11510 /* FIXME we need to get register block size some other way. */
11511 extern int trace_regblock_size;
11512 enum packet_result result;
11514 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11517 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11519 putpkt ("qTStatus");
11523 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11525 CATCH (ex, RETURN_MASK_ERROR)
11527 if (ex.error != TARGET_CLOSE_ERROR)
11529 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11532 throw_exception (ex);
11536 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11538 /* If the remote target doesn't do tracing, flag it. */
11539 if (result == PACKET_UNKNOWN)
11542 /* We're working with a live target. */
11543 ts->filename = NULL;
11546 error (_("Bogus trace status reply from target: %s"), target_buf);
11548 /* Function 'parse_trace_status' sets default value of each field of
11549 'ts' at first, so we don't have to do it here. */
11550 parse_trace_status (p, ts);
11552 return ts->running;
11556 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
11557 struct uploaded_tp *utp)
11559 struct remote_state *rs = get_remote_state ();
11561 struct bp_location *loc;
11562 struct tracepoint *tp = (struct tracepoint *) bp;
11563 size_t size = get_remote_packet_size ();
11567 tp->base.hit_count = 0;
11568 tp->traceframe_usage = 0;
11569 for (loc = tp->base.loc; loc; loc = loc->next)
11571 /* If the tracepoint was never downloaded, don't go asking for
11573 if (tp->number_on_target == 0)
11575 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11576 phex_nz (loc->address, 0));
11578 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11579 if (reply && *reply)
11582 parse_tracepoint_status (reply + 1, bp, utp);
11588 utp->hit_count = 0;
11589 utp->traceframe_usage = 0;
11590 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11591 phex_nz (utp->addr, 0));
11593 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11594 if (reply && *reply)
11597 parse_tracepoint_status (reply + 1, bp, utp);
11603 remote_trace_stop (struct target_ops *self)
11606 remote_get_noisy_reply (&target_buf, &target_buf_size);
11607 if (*target_buf == '\0')
11608 error (_("Target does not support this command."));
11609 if (strcmp (target_buf, "OK") != 0)
11610 error (_("Bogus reply from target: %s"), target_buf);
11614 remote_trace_find (struct target_ops *self,
11615 enum trace_find_type type, int num,
11616 CORE_ADDR addr1, CORE_ADDR addr2,
11619 struct remote_state *rs = get_remote_state ();
11620 char *endbuf = rs->buf + get_remote_packet_size ();
11622 int target_frameno = -1, target_tracept = -1;
11624 /* Lookups other than by absolute frame number depend on the current
11625 trace selected, so make sure it is correct on the remote end
11627 if (type != tfind_number)
11628 set_remote_traceframe ();
11631 strcpy (p, "QTFrame:");
11632 p = strchr (p, '\0');
11636 xsnprintf (p, endbuf - p, "%x", num);
11639 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11642 xsnprintf (p, endbuf - p, "tdp:%x", num);
11645 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11646 phex_nz (addr2, 0));
11648 case tfind_outside:
11649 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11650 phex_nz (addr2, 0));
11653 error (_("Unknown trace find type %d"), type);
11657 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11658 if (*reply == '\0')
11659 error (_("Target does not support this command."));
11661 while (reply && *reply)
11666 target_frameno = (int) strtol (p, &reply, 16);
11668 error (_("Unable to parse trace frame number"));
11669 /* Don't update our remote traceframe number cache on failure
11670 to select a remote traceframe. */
11671 if (target_frameno == -1)
11676 target_tracept = (int) strtol (p, &reply, 16);
11678 error (_("Unable to parse tracepoint number"));
11680 case 'O': /* "OK"? */
11681 if (reply[1] == 'K' && reply[2] == '\0')
11684 error (_("Bogus reply from target: %s"), reply);
11687 error (_("Bogus reply from target: %s"), reply);
11690 *tpp = target_tracept;
11692 rs->remote_traceframe_number = target_frameno;
11693 return target_frameno;
11697 remote_get_trace_state_variable_value (struct target_ops *self,
11698 int tsvnum, LONGEST *val)
11700 struct remote_state *rs = get_remote_state ();
11704 set_remote_traceframe ();
11706 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11708 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11709 if (reply && *reply)
11713 unpack_varlen_hex (reply + 1, &uval);
11714 *val = (LONGEST) uval;
11722 remote_save_trace_data (struct target_ops *self, const char *filename)
11724 struct remote_state *rs = get_remote_state ();
11728 strcpy (p, "QTSave:");
11730 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11731 error (_("Remote file name too long for trace save packet"));
11732 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11735 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11736 if (*reply == '\0')
11737 error (_("Target does not support this command."));
11738 if (strcmp (reply, "OK") != 0)
11739 error (_("Bogus reply from target: %s"), reply);
11743 /* This is basically a memory transfer, but needs to be its own packet
11744 because we don't know how the target actually organizes its trace
11745 memory, plus we want to be able to ask for as much as possible, but
11746 not be unhappy if we don't get as much as we ask for. */
11749 remote_get_raw_trace_data (struct target_ops *self,
11750 gdb_byte *buf, ULONGEST offset, LONGEST len)
11752 struct remote_state *rs = get_remote_state ();
11758 strcpy (p, "qTBuffer:");
11760 p += hexnumstr (p, offset);
11762 p += hexnumstr (p, len);
11766 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11767 if (reply && *reply)
11769 /* 'l' by itself means we're at the end of the buffer and
11770 there is nothing more to get. */
11774 /* Convert the reply into binary. Limit the number of bytes to
11775 convert according to our passed-in buffer size, rather than
11776 what was returned in the packet; if the target is
11777 unexpectedly generous and gives us a bigger reply than we
11778 asked for, we don't want to crash. */
11779 rslt = hex2bin (target_buf, buf, len);
11783 /* Something went wrong, flag as an error. */
11788 remote_set_disconnected_tracing (struct target_ops *self, int val)
11790 struct remote_state *rs = get_remote_state ();
11792 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11796 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11798 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11799 if (*reply == '\0')
11800 error (_("Target does not support this command."));
11801 if (strcmp (reply, "OK") != 0)
11802 error (_("Bogus reply from target: %s"), reply);
11805 warning (_("Target does not support disconnected tracing."));
11809 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11811 struct thread_info *info = find_thread_ptid (ptid);
11813 if (info && info->priv)
11814 return info->priv->core;
11819 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11821 struct remote_state *rs = get_remote_state ();
11824 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11826 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11827 if (*reply == '\0')
11828 error (_("Target does not support this command."));
11829 if (strcmp (reply, "OK") != 0)
11830 error (_("Bogus reply from target: %s"), reply);
11833 static struct traceframe_info *
11834 remote_traceframe_info (struct target_ops *self)
11838 text = target_read_stralloc (¤t_target,
11839 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11842 struct traceframe_info *info;
11843 struct cleanup *back_to = make_cleanup (xfree, text);
11845 info = parse_traceframe_info (text);
11846 do_cleanups (back_to);
11853 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11854 instruction on which a fast tracepoint may be placed. Returns -1
11855 if the packet is not supported, and 0 if the minimum instruction
11856 length is unknown. */
11859 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11861 struct remote_state *rs = get_remote_state ();
11864 /* If we're not debugging a process yet, the IPA can't be
11866 if (!target_has_execution)
11869 /* Make sure the remote is pointing at the right process. */
11870 set_general_process ();
11872 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11874 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11875 if (*reply == '\0')
11879 ULONGEST min_insn_len;
11881 unpack_varlen_hex (reply, &min_insn_len);
11883 return (int) min_insn_len;
11888 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11890 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11892 struct remote_state *rs = get_remote_state ();
11893 char *buf = rs->buf;
11894 char *endbuf = rs->buf + get_remote_packet_size ();
11895 enum packet_result result;
11897 gdb_assert (val >= 0 || val == -1);
11898 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11899 /* Send -1 as literal "-1" to avoid host size dependency. */
11903 buf += hexnumstr (buf, (ULONGEST) -val);
11906 buf += hexnumstr (buf, (ULONGEST) val);
11909 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11910 result = packet_ok (rs->buf,
11911 &remote_protocol_packets[PACKET_QTBuffer_size]);
11913 if (result != PACKET_OK)
11914 warning (_("Bogus reply from target: %s"), rs->buf);
11919 remote_set_trace_notes (struct target_ops *self,
11920 const char *user, const char *notes,
11921 const char *stop_notes)
11923 struct remote_state *rs = get_remote_state ();
11925 char *buf = rs->buf;
11926 char *endbuf = rs->buf + get_remote_packet_size ();
11929 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11932 buf += xsnprintf (buf, endbuf - buf, "user:");
11933 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11939 buf += xsnprintf (buf, endbuf - buf, "notes:");
11940 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11946 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11947 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11951 /* Ensure the buffer is terminated. */
11955 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11956 if (*reply == '\0')
11959 if (strcmp (reply, "OK") != 0)
11960 error (_("Bogus reply from target: %s"), reply);
11966 remote_use_agent (struct target_ops *self, int use)
11968 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11970 struct remote_state *rs = get_remote_state ();
11972 /* If the stub supports QAgent. */
11973 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11975 getpkt (&rs->buf, &rs->buf_size, 0);
11977 if (strcmp (rs->buf, "OK") == 0)
11988 remote_can_use_agent (struct target_ops *self)
11990 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11993 struct btrace_target_info
11995 /* The ptid of the traced thread. */
11998 /* The obtained branch trace configuration. */
11999 struct btrace_config conf;
12002 /* Reset our idea of our target's btrace configuration. */
12005 remote_btrace_reset (void)
12007 struct remote_state *rs = get_remote_state ();
12009 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12012 /* Check whether the target supports branch tracing. */
12015 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12017 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12019 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12024 case BTRACE_FORMAT_NONE:
12027 case BTRACE_FORMAT_BTS:
12028 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12030 case BTRACE_FORMAT_PT:
12031 /* The trace is decoded on the host. Even if our target supports it,
12032 we still need to have libipt to decode the trace. */
12033 #if defined (HAVE_LIBIPT)
12034 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12035 #else /* !defined (HAVE_LIBIPT) */
12037 #endif /* !defined (HAVE_LIBIPT) */
12040 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12043 /* Synchronize the configuration with the target. */
12046 btrace_sync_conf (const struct btrace_config *conf)
12048 struct packet_config *packet;
12049 struct remote_state *rs;
12050 char *buf, *pos, *endbuf;
12052 rs = get_remote_state ();
12054 endbuf = buf + get_remote_packet_size ();
12056 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12057 if (packet_config_support (packet) == PACKET_ENABLE
12058 && conf->bts.size != rs->btrace_config.bts.size)
12061 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12065 getpkt (&buf, &rs->buf_size, 0);
12067 if (packet_ok (buf, packet) == PACKET_ERROR)
12069 if (buf[0] == 'E' && buf[1] == '.')
12070 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12072 error (_("Failed to configure the BTS buffer size."));
12075 rs->btrace_config.bts.size = conf->bts.size;
12078 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12079 if (packet_config_support (packet) == PACKET_ENABLE
12080 && conf->pt.size != rs->btrace_config.pt.size)
12083 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12087 getpkt (&buf, &rs->buf_size, 0);
12089 if (packet_ok (buf, packet) == PACKET_ERROR)
12091 if (buf[0] == 'E' && buf[1] == '.')
12092 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12094 error (_("Failed to configure the trace buffer size."));
12097 rs->btrace_config.pt.size = conf->pt.size;
12101 /* Read the current thread's btrace configuration from the target and
12102 store it into CONF. */
12105 btrace_read_config (struct btrace_config *conf)
12109 xml = target_read_stralloc (¤t_target,
12110 TARGET_OBJECT_BTRACE_CONF, "");
12113 struct cleanup *cleanup;
12115 cleanup = make_cleanup (xfree, xml);
12116 parse_xml_btrace_conf (conf, xml);
12117 do_cleanups (cleanup);
12121 /* Enable branch tracing. */
12123 static struct btrace_target_info *
12124 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12125 const struct btrace_config *conf)
12127 struct btrace_target_info *tinfo = NULL;
12128 struct packet_config *packet = NULL;
12129 struct remote_state *rs = get_remote_state ();
12130 char *buf = rs->buf;
12131 char *endbuf = rs->buf + get_remote_packet_size ();
12133 switch (conf->format)
12135 case BTRACE_FORMAT_BTS:
12136 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12139 case BTRACE_FORMAT_PT:
12140 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12144 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12145 error (_("Target does not support branch tracing."));
12147 btrace_sync_conf (conf);
12149 set_general_thread (ptid);
12151 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12153 getpkt (&rs->buf, &rs->buf_size, 0);
12155 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12157 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12158 error (_("Could not enable branch tracing for %s: %s"),
12159 target_pid_to_str (ptid), rs->buf + 2);
12161 error (_("Could not enable branch tracing for %s."),
12162 target_pid_to_str (ptid));
12165 tinfo = xzalloc (sizeof (*tinfo));
12166 tinfo->ptid = ptid;
12168 /* If we fail to read the configuration, we lose some information, but the
12169 tracing itself is not impacted. */
12172 btrace_read_config (&tinfo->conf);
12174 CATCH (err, RETURN_MASK_ERROR)
12176 if (err.message != NULL)
12177 warning ("%s", err.message);
12184 /* Disable branch tracing. */
12187 remote_disable_btrace (struct target_ops *self,
12188 struct btrace_target_info *tinfo)
12190 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12191 struct remote_state *rs = get_remote_state ();
12192 char *buf = rs->buf;
12193 char *endbuf = rs->buf + get_remote_packet_size ();
12195 if (packet_config_support (packet) != PACKET_ENABLE)
12196 error (_("Target does not support branch tracing."));
12198 set_general_thread (tinfo->ptid);
12200 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12202 getpkt (&rs->buf, &rs->buf_size, 0);
12204 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12206 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12207 error (_("Could not disable branch tracing for %s: %s"),
12208 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12210 error (_("Could not disable branch tracing for %s."),
12211 target_pid_to_str (tinfo->ptid));
12217 /* Teardown branch tracing. */
12220 remote_teardown_btrace (struct target_ops *self,
12221 struct btrace_target_info *tinfo)
12223 /* We must not talk to the target during teardown. */
12227 /* Read the branch trace. */
12229 static enum btrace_error
12230 remote_read_btrace (struct target_ops *self,
12231 struct btrace_data *btrace,
12232 struct btrace_target_info *tinfo,
12233 enum btrace_read_type type)
12235 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12236 struct remote_state *rs = get_remote_state ();
12237 struct cleanup *cleanup;
12241 if (packet_config_support (packet) != PACKET_ENABLE)
12242 error (_("Target does not support branch tracing."));
12244 #if !defined(HAVE_LIBEXPAT)
12245 error (_("Cannot process branch tracing result. XML parsing not supported."));
12250 case BTRACE_READ_ALL:
12253 case BTRACE_READ_NEW:
12256 case BTRACE_READ_DELTA:
12260 internal_error (__FILE__, __LINE__,
12261 _("Bad branch tracing read type: %u."),
12262 (unsigned int) type);
12265 xml = target_read_stralloc (¤t_target,
12266 TARGET_OBJECT_BTRACE, annex);
12268 return BTRACE_ERR_UNKNOWN;
12270 cleanup = make_cleanup (xfree, xml);
12271 parse_xml_btrace (btrace, xml);
12272 do_cleanups (cleanup);
12274 return BTRACE_ERR_NONE;
12277 static const struct btrace_config *
12278 remote_btrace_conf (struct target_ops *self,
12279 const struct btrace_target_info *tinfo)
12281 return &tinfo->conf;
12285 remote_augmented_libraries_svr4_read (struct target_ops *self)
12287 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12291 /* Implementation of to_load. */
12294 remote_load (struct target_ops *self, const char *name, int from_tty)
12296 generic_load (name, from_tty);
12299 /* Accepts an integer PID; returns a string representing a file that
12300 can be opened on the remote side to get the symbols for the child
12301 process. Returns NULL if the operation is not supported. */
12304 remote_pid_to_exec_file (struct target_ops *self, int pid)
12306 static char *filename = NULL;
12307 struct inferior *inf;
12308 char *annex = NULL;
12310 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12313 if (filename != NULL)
12316 inf = find_inferior_pid (pid);
12318 internal_error (__FILE__, __LINE__,
12319 _("not currently attached to process %d"), pid);
12321 if (!inf->fake_pid_p)
12323 const int annex_size = 9;
12325 annex = alloca (annex_size);
12326 xsnprintf (annex, annex_size, "%x", pid);
12329 filename = target_read_stralloc (¤t_target,
12330 TARGET_OBJECT_EXEC_FILE, annex);
12336 init_remote_ops (void)
12338 remote_ops.to_shortname = "remote";
12339 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12340 remote_ops.to_doc =
12341 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12342 Specify the serial device it is connected to\n\
12343 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12344 remote_ops.to_open = remote_open;
12345 remote_ops.to_close = remote_close;
12346 remote_ops.to_detach = remote_detach;
12347 remote_ops.to_disconnect = remote_disconnect;
12348 remote_ops.to_resume = remote_resume;
12349 remote_ops.to_wait = remote_wait;
12350 remote_ops.to_fetch_registers = remote_fetch_registers;
12351 remote_ops.to_store_registers = remote_store_registers;
12352 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12353 remote_ops.to_files_info = remote_files_info;
12354 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12355 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12356 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12357 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12358 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12359 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12360 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12361 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12362 remote_ops.to_watchpoint_addr_within_range =
12363 remote_watchpoint_addr_within_range;
12364 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12365 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12366 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12367 remote_ops.to_region_ok_for_hw_watchpoint
12368 = remote_region_ok_for_hw_watchpoint;
12369 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12370 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12371 remote_ops.to_kill = remote_kill;
12372 remote_ops.to_load = remote_load;
12373 remote_ops.to_mourn_inferior = remote_mourn;
12374 remote_ops.to_pass_signals = remote_pass_signals;
12375 remote_ops.to_program_signals = remote_program_signals;
12376 remote_ops.to_thread_alive = remote_thread_alive;
12377 remote_ops.to_update_thread_list = remote_update_thread_list;
12378 remote_ops.to_pid_to_str = remote_pid_to_str;
12379 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12380 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12381 remote_ops.to_stop = remote_stop;
12382 remote_ops.to_interrupt = remote_interrupt;
12383 remote_ops.to_xfer_partial = remote_xfer_partial;
12384 remote_ops.to_rcmd = remote_rcmd;
12385 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12386 remote_ops.to_log_command = serial_log_command;
12387 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12388 remote_ops.to_stratum = process_stratum;
12389 remote_ops.to_has_all_memory = default_child_has_all_memory;
12390 remote_ops.to_has_memory = default_child_has_memory;
12391 remote_ops.to_has_stack = default_child_has_stack;
12392 remote_ops.to_has_registers = default_child_has_registers;
12393 remote_ops.to_has_execution = default_child_has_execution;
12394 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12395 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12396 remote_ops.to_magic = OPS_MAGIC;
12397 remote_ops.to_memory_map = remote_memory_map;
12398 remote_ops.to_flash_erase = remote_flash_erase;
12399 remote_ops.to_flash_done = remote_flash_done;
12400 remote_ops.to_read_description = remote_read_description;
12401 remote_ops.to_search_memory = remote_search_memory;
12402 remote_ops.to_can_async_p = remote_can_async_p;
12403 remote_ops.to_is_async_p = remote_is_async_p;
12404 remote_ops.to_async = remote_async;
12405 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12406 remote_ops.to_terminal_ours = remote_terminal_ours;
12407 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12408 remote_ops.to_supports_multi_process = remote_supports_multi_process;
12409 remote_ops.to_supports_disable_randomization
12410 = remote_supports_disable_randomization;
12411 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12412 remote_ops.to_fileio_open = remote_hostio_open;
12413 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12414 remote_ops.to_fileio_pread = remote_hostio_pread;
12415 remote_ops.to_fileio_fstat = remote_hostio_fstat;
12416 remote_ops.to_fileio_close = remote_hostio_close;
12417 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12418 remote_ops.to_fileio_readlink = remote_hostio_readlink;
12419 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12420 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12421 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12422 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12423 remote_ops.to_trace_init = remote_trace_init;
12424 remote_ops.to_download_tracepoint = remote_download_tracepoint;
12425 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12426 remote_ops.to_download_trace_state_variable
12427 = remote_download_trace_state_variable;
12428 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12429 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12430 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12431 remote_ops.to_trace_start = remote_trace_start;
12432 remote_ops.to_get_trace_status = remote_get_trace_status;
12433 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12434 remote_ops.to_trace_stop = remote_trace_stop;
12435 remote_ops.to_trace_find = remote_trace_find;
12436 remote_ops.to_get_trace_state_variable_value
12437 = remote_get_trace_state_variable_value;
12438 remote_ops.to_save_trace_data = remote_save_trace_data;
12439 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
12440 remote_ops.to_upload_trace_state_variables
12441 = remote_upload_trace_state_variables;
12442 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
12443 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
12444 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12445 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
12446 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
12447 remote_ops.to_set_trace_notes = remote_set_trace_notes;
12448 remote_ops.to_core_of_thread = remote_core_of_thread;
12449 remote_ops.to_verify_memory = remote_verify_memory;
12450 remote_ops.to_get_tib_address = remote_get_tib_address;
12451 remote_ops.to_set_permissions = remote_set_permissions;
12452 remote_ops.to_static_tracepoint_marker_at
12453 = remote_static_tracepoint_marker_at;
12454 remote_ops.to_static_tracepoint_markers_by_strid
12455 = remote_static_tracepoint_markers_by_strid;
12456 remote_ops.to_traceframe_info = remote_traceframe_info;
12457 remote_ops.to_use_agent = remote_use_agent;
12458 remote_ops.to_can_use_agent = remote_can_use_agent;
12459 remote_ops.to_supports_btrace = remote_supports_btrace;
12460 remote_ops.to_enable_btrace = remote_enable_btrace;
12461 remote_ops.to_disable_btrace = remote_disable_btrace;
12462 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12463 remote_ops.to_read_btrace = remote_read_btrace;
12464 remote_ops.to_btrace_conf = remote_btrace_conf;
12465 remote_ops.to_augmented_libraries_svr4_read =
12466 remote_augmented_libraries_svr4_read;
12469 /* Set up the extended remote vector by making a copy of the standard
12470 remote vector and adding to it. */
12473 init_extended_remote_ops (void)
12475 extended_remote_ops = remote_ops;
12477 extended_remote_ops.to_shortname = "extended-remote";
12478 extended_remote_ops.to_longname =
12479 "Extended remote serial target in gdb-specific protocol";
12480 extended_remote_ops.to_doc =
12481 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12482 Specify the serial device it is connected to (e.g. /dev/ttya).";
12483 extended_remote_ops.to_open = extended_remote_open;
12484 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12485 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
12486 extended_remote_ops.to_detach = extended_remote_detach;
12487 extended_remote_ops.to_attach = extended_remote_attach;
12488 extended_remote_ops.to_post_attach = extended_remote_post_attach;
12489 extended_remote_ops.to_kill = extended_remote_kill;
12490 extended_remote_ops.to_supports_disable_randomization
12491 = extended_remote_supports_disable_randomization;
12492 extended_remote_ops.to_follow_fork = remote_follow_fork;
12493 extended_remote_ops.to_insert_fork_catchpoint
12494 = remote_insert_fork_catchpoint;
12495 extended_remote_ops.to_remove_fork_catchpoint
12496 = remote_remove_fork_catchpoint;
12497 extended_remote_ops.to_insert_vfork_catchpoint
12498 = remote_insert_vfork_catchpoint;
12499 extended_remote_ops.to_remove_vfork_catchpoint
12500 = remote_remove_vfork_catchpoint;
12504 remote_can_async_p (struct target_ops *ops)
12506 struct remote_state *rs = get_remote_state ();
12508 if (!target_async_permitted)
12509 /* We only enable async when the user specifically asks for it. */
12512 /* We're async whenever the serial device is. */
12513 return serial_can_async_p (rs->remote_desc);
12517 remote_is_async_p (struct target_ops *ops)
12519 struct remote_state *rs = get_remote_state ();
12521 if (!target_async_permitted)
12522 /* We only enable async when the user specifically asks for it. */
12525 /* We're async whenever the serial device is. */
12526 return serial_is_async_p (rs->remote_desc);
12529 /* Pass the SERIAL event on and up to the client. One day this code
12530 will be able to delay notifying the client of an event until the
12531 point where an entire packet has been received. */
12533 static serial_event_ftype remote_async_serial_handler;
12536 remote_async_serial_handler (struct serial *scb, void *context)
12538 struct remote_state *rs = context;
12540 /* Don't propogate error information up to the client. Instead let
12541 the client find out about the error by querying the target. */
12542 inferior_event_handler (INF_REG_EVENT, NULL);
12546 remote_async_inferior_event_handler (gdb_client_data data)
12548 inferior_event_handler (INF_REG_EVENT, NULL);
12552 remote_async (struct target_ops *ops, int enable)
12554 struct remote_state *rs = get_remote_state ();
12558 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
12560 /* If there are pending events in the stop reply queue tell the
12561 event loop to process them. */
12562 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12563 mark_async_event_handler (remote_async_inferior_event_token);
12567 serial_async (rs->remote_desc, NULL, NULL);
12568 clear_async_event_handler (remote_async_inferior_event_token);
12573 set_remote_cmd (char *args, int from_tty)
12575 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
12579 show_remote_cmd (char *args, int from_tty)
12581 /* We can't just use cmd_show_list here, because we want to skip
12582 the redundant "show remote Z-packet" and the legacy aliases. */
12583 struct cleanup *showlist_chain;
12584 struct cmd_list_element *list = remote_show_cmdlist;
12585 struct ui_out *uiout = current_uiout;
12587 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12588 for (; list != NULL; list = list->next)
12589 if (strcmp (list->name, "Z-packet") == 0)
12591 else if (list->type == not_set_cmd)
12592 /* Alias commands are exactly like the original, except they
12593 don't have the normal type. */
12597 struct cleanup *option_chain
12598 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
12600 ui_out_field_string (uiout, "name", list->name);
12601 ui_out_text (uiout, ": ");
12602 if (list->type == show_cmd)
12603 do_show_command ((char *) NULL, from_tty, list);
12605 cmd_func (list, NULL, from_tty);
12606 /* Close the tuple. */
12607 do_cleanups (option_chain);
12610 /* Close the tuple. */
12611 do_cleanups (showlist_chain);
12615 /* Function to be called whenever a new objfile (shlib) is detected. */
12617 remote_new_objfile (struct objfile *objfile)
12619 struct remote_state *rs = get_remote_state ();
12621 if (rs->remote_desc != 0) /* Have a remote connection. */
12622 remote_check_symbols ();
12625 /* Pull all the tracepoints defined on the target and create local
12626 data structures representing them. We don't want to create real
12627 tracepoints yet, we don't want to mess up the user's existing
12631 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
12633 struct remote_state *rs = get_remote_state ();
12636 /* Ask for a first packet of tracepoint definition. */
12638 getpkt (&rs->buf, &rs->buf_size, 0);
12640 while (*p && *p != 'l')
12642 parse_tracepoint_definition (p, utpp);
12643 /* Ask for another packet of tracepoint definition. */
12645 getpkt (&rs->buf, &rs->buf_size, 0);
12652 remote_upload_trace_state_variables (struct target_ops *self,
12653 struct uploaded_tsv **utsvp)
12655 struct remote_state *rs = get_remote_state ();
12658 /* Ask for a first packet of variable definition. */
12660 getpkt (&rs->buf, &rs->buf_size, 0);
12662 while (*p && *p != 'l')
12664 parse_tsv_definition (p, utsvp);
12665 /* Ask for another packet of variable definition. */
12667 getpkt (&rs->buf, &rs->buf_size, 0);
12673 /* The "set/show range-stepping" show hook. */
12676 show_range_stepping (struct ui_file *file, int from_tty,
12677 struct cmd_list_element *c,
12680 fprintf_filtered (file,
12681 _("Debugger's willingness to use range stepping "
12682 "is %s.\n"), value);
12685 /* The "set/show range-stepping" set hook. */
12688 set_range_stepping (char *ignore_args, int from_tty,
12689 struct cmd_list_element *c)
12691 struct remote_state *rs = get_remote_state ();
12693 /* Whene enabling, check whether range stepping is actually
12694 supported by the target, and warn if not. */
12695 if (use_range_stepping)
12697 if (rs->remote_desc != NULL)
12699 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12700 remote_vcont_probe (rs);
12702 if (packet_support (PACKET_vCont) == PACKET_ENABLE
12703 && rs->supports_vCont.r)
12707 warning (_("Range stepping is not supported by the current target"));
12712 _initialize_remote (void)
12714 struct remote_state *rs;
12715 struct cmd_list_element *cmd;
12716 const char *cmd_name;
12718 /* architecture specific data */
12719 remote_gdbarch_data_handle =
12720 gdbarch_data_register_post_init (init_remote_state);
12721 remote_g_packet_data_handle =
12722 gdbarch_data_register_pre_init (remote_g_packet_data_init);
12724 /* Initialize the per-target state. At the moment there is only one
12725 of these, not one per target. Only one target is active at a
12727 remote_state = new_remote_state ();
12729 init_remote_ops ();
12730 add_target (&remote_ops);
12732 init_extended_remote_ops ();
12733 add_target (&extended_remote_ops);
12735 /* Hook into new objfile notification. */
12736 observer_attach_new_objfile (remote_new_objfile);
12737 /* We're no longer interested in notification events of an inferior
12739 observer_attach_inferior_exit (discard_pending_stop_replies);
12741 /* Set up signal handlers. */
12742 async_sigint_remote_token =
12743 create_async_signal_handler (async_remote_interrupt, NULL);
12744 async_sigint_remote_twice_token =
12745 create_async_signal_handler (async_remote_interrupt_twice, NULL);
12748 init_remote_threadtests ();
12751 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
12752 /* set/show remote ... */
12754 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12755 Remote protocol specific variables\n\
12756 Configure various remote-protocol specific variables such as\n\
12757 the packets being used"),
12758 &remote_set_cmdlist, "set remote ",
12759 0 /* allow-unknown */, &setlist);
12760 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12761 Remote protocol specific variables\n\
12762 Configure various remote-protocol specific variables such as\n\
12763 the packets being used"),
12764 &remote_show_cmdlist, "show remote ",
12765 0 /* allow-unknown */, &showlist);
12767 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12768 Compare section data on target to the exec file.\n\
12769 Argument is a single section name (default: all loaded sections).\n\
12770 To compare only read-only loaded sections, specify the -r option."),
12773 add_cmd ("packet", class_maintenance, packet_command, _("\
12774 Send an arbitrary packet to a remote target.\n\
12775 maintenance packet TEXT\n\
12776 If GDB is talking to an inferior via the GDB serial protocol, then\n\
12777 this command sends the string TEXT to the inferior, and displays the\n\
12778 response packet. GDB supplies the initial `$' character, and the\n\
12779 terminating `#' character and checksum."),
12782 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12783 Set whether to send break if interrupted."), _("\
12784 Show whether to send break if interrupted."), _("\
12785 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12786 set_remotebreak, show_remotebreak,
12787 &setlist, &showlist);
12788 cmd_name = "remotebreak";
12789 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12790 deprecate_cmd (cmd, "set remote interrupt-sequence");
12791 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12792 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12793 deprecate_cmd (cmd, "show remote interrupt-sequence");
12795 add_setshow_enum_cmd ("interrupt-sequence", class_support,
12796 interrupt_sequence_modes, &interrupt_sequence_mode,
12798 Set interrupt sequence to remote target."), _("\
12799 Show interrupt sequence to remote target."), _("\
12800 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12801 NULL, show_interrupt_sequence,
12802 &remote_set_cmdlist,
12803 &remote_show_cmdlist);
12805 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12806 &interrupt_on_connect, _("\
12807 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12808 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12809 If set, interrupt sequence is sent to remote target."),
12811 &remote_set_cmdlist, &remote_show_cmdlist);
12813 /* Install commands for configuring memory read/write packets. */
12815 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12816 Set the maximum number of bytes per memory write packet (deprecated)."),
12818 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12819 Show the maximum number of bytes per memory write packet (deprecated)."),
12821 add_cmd ("memory-write-packet-size", no_class,
12822 set_memory_write_packet_size, _("\
12823 Set the maximum number of bytes per memory-write packet.\n\
12824 Specify the number of bytes in a packet or 0 (zero) for the\n\
12825 default packet size. The actual limit is further reduced\n\
12826 dependent on the target. Specify ``fixed'' to disable the\n\
12827 further restriction and ``limit'' to enable that restriction."),
12828 &remote_set_cmdlist);
12829 add_cmd ("memory-read-packet-size", no_class,
12830 set_memory_read_packet_size, _("\
12831 Set the maximum number of bytes per memory-read packet.\n\
12832 Specify the number of bytes in a packet or 0 (zero) for the\n\
12833 default packet size. The actual limit is further reduced\n\
12834 dependent on the target. Specify ``fixed'' to disable the\n\
12835 further restriction and ``limit'' to enable that restriction."),
12836 &remote_set_cmdlist);
12837 add_cmd ("memory-write-packet-size", no_class,
12838 show_memory_write_packet_size,
12839 _("Show the maximum number of bytes per memory-write packet."),
12840 &remote_show_cmdlist);
12841 add_cmd ("memory-read-packet-size", no_class,
12842 show_memory_read_packet_size,
12843 _("Show the maximum number of bytes per memory-read packet."),
12844 &remote_show_cmdlist);
12846 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12847 &remote_hw_watchpoint_limit, _("\
12848 Set the maximum number of target hardware watchpoints."), _("\
12849 Show the maximum number of target hardware watchpoints."), _("\
12850 Specify a negative limit for unlimited."),
12851 NULL, NULL, /* FIXME: i18n: The maximum
12852 number of target hardware
12853 watchpoints is %s. */
12854 &remote_set_cmdlist, &remote_show_cmdlist);
12855 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12856 &remote_hw_watchpoint_length_limit, _("\
12857 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12858 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12859 Specify a negative limit for unlimited."),
12860 NULL, NULL, /* FIXME: i18n: The maximum
12861 length (in bytes) of a target
12862 hardware watchpoint is %s. */
12863 &remote_set_cmdlist, &remote_show_cmdlist);
12864 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12865 &remote_hw_breakpoint_limit, _("\
12866 Set the maximum number of target hardware breakpoints."), _("\
12867 Show the maximum number of target hardware breakpoints."), _("\
12868 Specify a negative limit for unlimited."),
12869 NULL, NULL, /* FIXME: i18n: The maximum
12870 number of target hardware
12871 breakpoints is %s. */
12872 &remote_set_cmdlist, &remote_show_cmdlist);
12874 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12875 &remote_address_size, _("\
12876 Set the maximum size of the address (in bits) in a memory packet."), _("\
12877 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12879 NULL, /* FIXME: i18n: */
12880 &setlist, &showlist);
12882 init_all_packet_configs ();
12884 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12885 "X", "binary-download", 1);
12887 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12888 "vCont", "verbose-resume", 0);
12890 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12891 "QPassSignals", "pass-signals", 0);
12893 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12894 "QProgramSignals", "program-signals", 0);
12896 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12897 "qSymbol", "symbol-lookup", 0);
12899 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12900 "P", "set-register", 1);
12902 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12903 "p", "fetch-register", 1);
12905 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12906 "Z0", "software-breakpoint", 0);
12908 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12909 "Z1", "hardware-breakpoint", 0);
12911 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12912 "Z2", "write-watchpoint", 0);
12914 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12915 "Z3", "read-watchpoint", 0);
12917 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12918 "Z4", "access-watchpoint", 0);
12920 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12921 "qXfer:auxv:read", "read-aux-vector", 0);
12923 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
12924 "qXfer:exec-file:read", "pid-to-exec-file", 0);
12926 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12927 "qXfer:features:read", "target-features", 0);
12929 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12930 "qXfer:libraries:read", "library-info", 0);
12932 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12933 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12935 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12936 "qXfer:memory-map:read", "memory-map", 0);
12938 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12939 "qXfer:spu:read", "read-spu-object", 0);
12941 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12942 "qXfer:spu:write", "write-spu-object", 0);
12944 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12945 "qXfer:osdata:read", "osdata", 0);
12947 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12948 "qXfer:threads:read", "threads", 0);
12950 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12951 "qXfer:siginfo:read", "read-siginfo-object", 0);
12953 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12954 "qXfer:siginfo:write", "write-siginfo-object", 0);
12956 add_packet_config_cmd
12957 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12958 "qXfer:traceframe-info:read", "traceframe-info", 0);
12960 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12961 "qXfer:uib:read", "unwind-info-block", 0);
12963 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12964 "qGetTLSAddr", "get-thread-local-storage-address",
12967 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12968 "qGetTIBAddr", "get-thread-information-block-address",
12971 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12972 "bc", "reverse-continue", 0);
12974 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12975 "bs", "reverse-step", 0);
12977 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12978 "qSupported", "supported-packets", 0);
12980 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12981 "qSearch:memory", "search-memory", 0);
12983 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12984 "qTStatus", "trace-status", 0);
12986 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
12987 "vFile:setfs", "hostio-setfs", 0);
12989 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12990 "vFile:open", "hostio-open", 0);
12992 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12993 "vFile:pread", "hostio-pread", 0);
12995 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12996 "vFile:pwrite", "hostio-pwrite", 0);
12998 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12999 "vFile:close", "hostio-close", 0);
13001 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13002 "vFile:unlink", "hostio-unlink", 0);
13004 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13005 "vFile:readlink", "hostio-readlink", 0);
13007 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13008 "vFile:fstat", "hostio-fstat", 0);
13010 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13011 "vAttach", "attach", 0);
13013 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13016 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13017 "QStartNoAckMode", "noack", 0);
13019 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13020 "vKill", "kill", 0);
13022 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13023 "qAttached", "query-attached", 0);
13025 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13026 "ConditionalTracepoints",
13027 "conditional-tracepoints", 0);
13029 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13030 "ConditionalBreakpoints",
13031 "conditional-breakpoints", 0);
13033 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13034 "BreakpointCommands",
13035 "breakpoint-commands", 0);
13037 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13038 "FastTracepoints", "fast-tracepoints", 0);
13040 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13041 "TracepointSource", "TracepointSource", 0);
13043 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13044 "QAllow", "allow", 0);
13046 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13047 "StaticTracepoints", "static-tracepoints", 0);
13049 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13050 "InstallInTrace", "install-in-trace", 0);
13052 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13053 "qXfer:statictrace:read", "read-sdata-object", 0);
13055 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13056 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13058 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13059 "QDisableRandomization", "disable-randomization", 0);
13061 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13062 "QAgent", "agent", 0);
13064 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13065 "QTBuffer:size", "trace-buffer-size", 0);
13067 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13068 "Qbtrace:off", "disable-btrace", 0);
13070 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13071 "Qbtrace:bts", "enable-btrace-bts", 0);
13073 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13074 "Qbtrace:pt", "enable-btrace-pt", 0);
13076 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13077 "qXfer:btrace", "read-btrace", 0);
13079 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13080 "qXfer:btrace-conf", "read-btrace-conf", 0);
13082 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13083 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13085 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13086 "swbreak-feature", "swbreak-feature", 0);
13088 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13089 "hwbreak-feature", "hwbreak-feature", 0);
13091 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13092 "fork-event-feature", "fork-event-feature", 0);
13094 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13095 "vfork-event-feature", "vfork-event-feature", 0);
13097 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13098 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13100 /* Assert that we've registered "set remote foo-packet" commands
13101 for all packet configs. */
13105 for (i = 0; i < PACKET_MAX; i++)
13107 /* Ideally all configs would have a command associated. Some
13108 still don't though. */
13113 case PACKET_QNonStop:
13114 case PACKET_multiprocess_feature:
13115 case PACKET_EnableDisableTracepoints_feature:
13116 case PACKET_tracenz_feature:
13117 case PACKET_DisconnectedTracing_feature:
13118 case PACKET_augmented_libraries_svr4_read_feature:
13120 /* Additions to this list need to be well justified:
13121 pre-existing packets are OK; new packets are not. */
13129 /* This catches both forgetting to add a config command, and
13130 forgetting to remove a packet from the exception list. */
13131 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13135 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13136 Z sub-packet has its own set and show commands, but users may
13137 have sets to this variable in their .gdbinit files (or in their
13139 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13140 &remote_Z_packet_detect, _("\
13141 Set use of remote protocol `Z' packets"), _("\
13142 Show use of remote protocol `Z' packets "), _("\
13143 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13145 set_remote_protocol_Z_packet_cmd,
13146 show_remote_protocol_Z_packet_cmd,
13147 /* FIXME: i18n: Use of remote protocol
13148 `Z' packets is %s. */
13149 &remote_set_cmdlist, &remote_show_cmdlist);
13151 add_prefix_cmd ("remote", class_files, remote_command, _("\
13152 Manipulate files on the remote system\n\
13153 Transfer files to and from the remote target system."),
13154 &remote_cmdlist, "remote ",
13155 0 /* allow-unknown */, &cmdlist);
13157 add_cmd ("put", class_files, remote_put_command,
13158 _("Copy a local file to the remote system."),
13161 add_cmd ("get", class_files, remote_get_command,
13162 _("Copy a remote file to the local system."),
13165 add_cmd ("delete", class_files, remote_delete_command,
13166 _("Delete a remote file."),
13169 remote_exec_file = xstrdup ("");
13170 add_setshow_string_noescape_cmd ("exec-file", class_files,
13171 &remote_exec_file, _("\
13172 Set the remote pathname for \"run\""), _("\
13173 Show the remote pathname for \"run\""), NULL, NULL, NULL,
13174 &remote_set_cmdlist, &remote_show_cmdlist);
13176 add_setshow_boolean_cmd ("range-stepping", class_run,
13177 &use_range_stepping, _("\
13178 Enable or disable range stepping."), _("\
13179 Show whether target-assisted range stepping is enabled."), _("\
13180 If on, and the target supports it, when stepping a source line, GDB\n\
13181 tells the target to step the corresponding range of addresses itself instead\n\
13182 of issuing multiple single-steps. This speeds up source level\n\
13183 stepping. If off, GDB always issues single-steps, even if range\n\
13184 stepping is supported by the target. The default is on."),
13185 set_range_stepping,
13186 show_range_stepping,
13190 /* Eventually initialize fileio. See fileio.c */
13191 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13193 /* Take advantage of the fact that the TID field is not used, to tag
13194 special ptids with it set to != 0. */
13195 magic_null_ptid = ptid_build (42000, -1, 1);
13196 not_sent_ptid = ptid_build (42000, -2, 1);
13197 any_thread_ptid = ptid_build (42000, 0, 1);
13199 target_buf_size = 2048;
13200 target_buf = xmalloc (target_buf_size);