1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
30 /*#include "terminal.h" */
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
36 #include "remote-notif.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
50 #include "gdb_sys_time.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);
231 static void readahead_cache_invalidate (void);
235 static struct cmd_list_element *remote_cmdlist;
237 /* For "set remote" and "show remote". */
239 static struct cmd_list_element *remote_set_cmdlist;
240 static struct cmd_list_element *remote_show_cmdlist;
242 /* Stub vCont actions support.
244 Each field is a boolean flag indicating whether the stub reports
245 support for the corresponding action. */
247 struct vCont_action_support
256 /* Controls whether GDB is willing to use range stepping. */
258 static int use_range_stepping = 1;
260 #define OPAQUETHREADBYTES 8
262 /* a 64 bit opaque identifier */
263 typedef unsigned char threadref[OPAQUETHREADBYTES];
265 /* About this many threadisds fit in a packet. */
267 #define MAXTHREADLISTRESULTS 32
269 /* Data for the vFile:pread readahead cache. */
271 struct readahead_cache
273 /* The file descriptor for the file that is being cached. -1 if the
277 /* The offset into the file that the cache buffer corresponds
281 /* The buffer holding the cache contents. */
283 /* The buffer's size. We try to read as much as fits into a packet
287 /* Cache hit and miss counters. */
292 /* Description of the remote protocol state for the currently
293 connected target. This is per-target state, and independent of the
294 selected architecture. */
298 /* A buffer to use for incoming packets, and its current size. The
299 buffer is grown dynamically for larger incoming packets.
300 Outgoing packets may also be constructed in this buffer.
301 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
302 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
307 /* True if we're going through initial connection setup (finding out
308 about the remote side's threads, relocating symbols, etc.). */
311 /* If we negotiated packet size explicitly (and thus can bypass
312 heuristics for the largest packet size that will not overflow
313 a buffer in the stub), this will be set to that packet size.
314 Otherwise zero, meaning to use the guessed size. */
315 long explicit_packet_size;
317 /* remote_wait is normally called when the target is running and
318 waits for a stop reply packet. But sometimes we need to call it
319 when the target is already stopped. We can send a "?" packet
320 and have remote_wait read the response. Or, if we already have
321 the response, we can stash it in BUF and tell remote_wait to
322 skip calling getpkt. This flag is set when BUF contains a
323 stop reply packet and the target is not waiting. */
324 int cached_wait_status;
326 /* True, if in no ack mode. That is, neither GDB nor the stub will
327 expect acks from each other. The connection is assumed to be
331 /* True if we're connected in extended remote mode. */
334 /* True if we resumed the target and we're waiting for the target to
335 stop. In the mean time, we can't start another command/query.
336 The remote server wouldn't be ready to process it, so we'd
337 timeout waiting for a reply that would never come and eventually
338 we'd close the connection. This can happen in asynchronous mode
339 because we allow GDB commands while the target is running. */
340 int waiting_for_stop_reply;
342 /* The status of the stub support for the various vCont actions. */
343 struct vCont_action_support supports_vCont;
345 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
346 responded to that. */
349 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
350 remote_open knows that we don't have a file open when the program
352 struct serial *remote_desc;
354 /* These are the threads which we last sent to the remote system. The
355 TID member will be -1 for all or -2 for not sent yet. */
356 ptid_t general_thread;
357 ptid_t continue_thread;
359 /* This is the traceframe which we last selected on the remote system.
360 It will be -1 if no traceframe is selected. */
361 int remote_traceframe_number;
363 char *last_pass_packet;
365 /* The last QProgramSignals packet sent to the target. We bypass
366 sending a new program signals list down to the target if the new
367 packet is exactly the same as the last we sent. IOW, we only let
368 the target know about program signals list changes. */
369 char *last_program_signals_packet;
371 enum gdb_signal last_sent_signal;
375 char *finished_object;
376 char *finished_annex;
377 ULONGEST finished_offset;
379 /* Should we try the 'ThreadInfo' query packet?
381 This variable (NOT available to the user: auto-detect only!)
382 determines whether GDB will use the new, simpler "ThreadInfo"
383 query or the older, more complex syntax for thread queries.
384 This is an auto-detect variable (set to true at each connect,
385 and set to false when the target fails to recognize it). */
386 int use_threadinfo_query;
387 int use_threadextra_query;
389 /* This is set to the data address of the access causing the target
390 to stop for a watchpoint. */
391 CORE_ADDR remote_watch_data_address;
393 /* Whether the target stopped for a breakpoint/watchpoint. */
394 enum target_stop_reason stop_reason;
396 threadref echo_nextthread;
397 threadref nextthread;
398 threadref resultthreadlist[MAXTHREADLISTRESULTS];
400 /* The state of remote notification. */
401 struct remote_notif_state *notif_state;
403 /* The branch trace configuration. */
404 struct btrace_config btrace_config;
406 /* The argument to the last "vFile:setfs:" packet we sent, used
407 to avoid sending repeated unnecessary "vFile:setfs:" packets.
408 Initialized to -1 to indicate that no "vFile:setfs:" packet
409 has yet been sent. */
412 /* A readahead cache for vFile:pread. Often, reading a binary
413 involves a sequence of small reads. E.g., when parsing an ELF
414 file. A readahead cache helps mostly the case of remote
415 debugging on a connection with higher latency, due to the
416 request/reply nature of the RSP. We only cache data for a single
417 file descriptor at a time. */
418 struct readahead_cache readahead_cache;
421 /* Private data that we'll store in (struct thread_info)->private. */
422 struct private_thread_info
429 free_private_thread_info (struct private_thread_info *info)
435 /* This data could be associated with a target, but we do not always
436 have access to the current target when we need it, so for now it is
437 static. This will be fine for as long as only one target is in use
439 static struct remote_state *remote_state;
441 static struct remote_state *
442 get_remote_state_raw (void)
447 /* Allocate a new struct remote_state with xmalloc, initialize it, and
450 static struct remote_state *
451 new_remote_state (void)
453 struct remote_state *result = XCNEW (struct remote_state);
455 /* The default buffer size is unimportant; it will be expanded
456 whenever a larger buffer is needed. */
457 result->buf_size = 400;
458 result->buf = xmalloc (result->buf_size);
459 result->remote_traceframe_number = -1;
460 result->last_sent_signal = GDB_SIGNAL_0;
466 /* Description of the remote protocol for a given architecture. */
470 long offset; /* Offset into G packet. */
471 long regnum; /* GDB's internal register number. */
472 LONGEST pnum; /* Remote protocol register number. */
473 int in_g_packet; /* Always part of G packet. */
474 /* long size in bytes; == register_size (target_gdbarch (), regnum);
476 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
480 struct remote_arch_state
482 /* Description of the remote protocol registers. */
483 long sizeof_g_packet;
485 /* Description of the remote protocol registers indexed by REGNUM
486 (making an array gdbarch_num_regs in size). */
487 struct packet_reg *regs;
489 /* This is the size (in chars) of the first response to the ``g''
490 packet. It is used as a heuristic when determining the maximum
491 size of memory-read and memory-write packets. A target will
492 typically only reserve a buffer large enough to hold the ``g''
493 packet. The size does not include packet overhead (headers and
495 long actual_register_packet_size;
497 /* This is the maximum size (in chars) of a non read/write packet.
498 It is also used as a cap on the size of read/write packets. */
499 long remote_packet_size;
502 /* Utility: generate error from an incoming stub packet. */
504 trace_error (char *buf)
507 return; /* not an error msg */
510 case '1': /* malformed packet error */
511 if (*++buf == '0') /* general case: */
512 error (_("remote.c: error in outgoing packet."));
514 error (_("remote.c: error in outgoing packet at field #%ld."),
515 strtol (buf, NULL, 16));
517 error (_("Target returns error code '%s'."), buf);
521 /* Utility: wait for reply from stub, while accepting "O" packets. */
523 remote_get_noisy_reply (char **buf_p,
526 do /* Loop on reply from remote stub. */
530 QUIT; /* Allow user to bail out with ^C. */
531 getpkt (buf_p, sizeof_buf, 0);
535 else if (startswith (buf, "qRelocInsn:"))
538 CORE_ADDR from, to, org_to;
540 int adjusted_size = 0;
543 p = buf + strlen ("qRelocInsn:");
544 pp = unpack_varlen_hex (p, &ul);
546 error (_("invalid qRelocInsn packet: %s"), buf);
550 unpack_varlen_hex (p, &ul);
557 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
560 CATCH (ex, RETURN_MASK_ALL)
562 if (ex.error == MEMORY_ERROR)
564 /* Propagate memory errors silently back to the
565 target. The stub may have limited the range of
566 addresses we can write to, for example. */
570 /* Something unexpectedly bad happened. Be verbose
571 so we can tell what, and propagate the error back
572 to the stub, so it doesn't get stuck waiting for
574 exception_fprintf (gdb_stderr, ex,
575 _("warning: relocating instruction: "));
583 adjusted_size = to - org_to;
585 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
589 else if (buf[0] == 'O' && buf[1] != 'K')
590 remote_console_output (buf + 1); /* 'O' message from stub */
592 return buf; /* Here's the actual reply. */
597 /* Handle for retreving the remote protocol data from gdbarch. */
598 static struct gdbarch_data *remote_gdbarch_data_handle;
600 static struct remote_arch_state *
601 get_remote_arch_state (void)
603 gdb_assert (target_gdbarch () != NULL);
604 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
607 /* Fetch the global remote target state. */
609 static struct remote_state *
610 get_remote_state (void)
612 /* Make sure that the remote architecture state has been
613 initialized, because doing so might reallocate rs->buf. Any
614 function which calls getpkt also needs to be mindful of changes
615 to rs->buf, but this call limits the number of places which run
617 get_remote_arch_state ();
619 return get_remote_state_raw ();
623 compare_pnums (const void *lhs_, const void *rhs_)
625 const struct packet_reg * const *lhs = lhs_;
626 const struct packet_reg * const *rhs = rhs_;
628 if ((*lhs)->pnum < (*rhs)->pnum)
630 else if ((*lhs)->pnum == (*rhs)->pnum)
637 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
639 int regnum, num_remote_regs, offset;
640 struct packet_reg **remote_regs;
642 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
644 struct packet_reg *r = ®s[regnum];
646 if (register_size (gdbarch, regnum) == 0)
647 /* Do not try to fetch zero-sized (placeholder) registers. */
650 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
655 /* Define the g/G packet format as the contents of each register
656 with a remote protocol number, in order of ascending protocol
659 remote_regs = alloca (gdbarch_num_regs (gdbarch)
660 * sizeof (struct packet_reg *));
661 for (num_remote_regs = 0, regnum = 0;
662 regnum < gdbarch_num_regs (gdbarch);
664 if (regs[regnum].pnum != -1)
665 remote_regs[num_remote_regs++] = ®s[regnum];
667 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
670 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
672 remote_regs[regnum]->in_g_packet = 1;
673 remote_regs[regnum]->offset = offset;
674 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
680 /* Given the architecture described by GDBARCH, return the remote
681 protocol register's number and the register's offset in the g/G
682 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
683 If the target does not have a mapping for REGNUM, return false,
684 otherwise, return true. */
687 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
688 int *pnum, int *poffset)
691 struct packet_reg *regs;
692 struct cleanup *old_chain;
694 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
696 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
697 old_chain = make_cleanup (xfree, regs);
699 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
701 *pnum = regs[regnum].pnum;
702 *poffset = regs[regnum].offset;
704 do_cleanups (old_chain);
710 init_remote_state (struct gdbarch *gdbarch)
712 struct remote_state *rs = get_remote_state_raw ();
713 struct remote_arch_state *rsa;
715 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
717 /* Use the architecture to build a regnum<->pnum table, which will be
718 1:1 unless a feature set specifies otherwise. */
719 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
720 gdbarch_num_regs (gdbarch),
723 /* Record the maximum possible size of the g packet - it may turn out
725 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
727 /* Default maximum number of characters in a packet body. Many
728 remote stubs have a hardwired buffer size of 400 bytes
729 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
730 as the maximum packet-size to ensure that the packet and an extra
731 NUL character can always fit in the buffer. This stops GDB
732 trashing stubs that try to squeeze an extra NUL into what is
733 already a full buffer (As of 1999-12-04 that was most stubs). */
734 rsa->remote_packet_size = 400 - 1;
736 /* This one is filled in when a ``g'' packet is received. */
737 rsa->actual_register_packet_size = 0;
739 /* Should rsa->sizeof_g_packet needs more space than the
740 default, adjust the size accordingly. Remember that each byte is
741 encoded as two characters. 32 is the overhead for the packet
742 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
743 (``$NN:G...#NN'') is a better guess, the below has been padded a
745 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
746 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
748 /* Make sure that the packet buffer is plenty big enough for
749 this architecture. */
750 if (rs->buf_size < rsa->remote_packet_size)
752 rs->buf_size = 2 * rsa->remote_packet_size;
753 rs->buf = xrealloc (rs->buf, rs->buf_size);
759 /* Return the current allowed size of a remote packet. This is
760 inferred from the current architecture, and should be used to
761 limit the length of outgoing packets. */
763 get_remote_packet_size (void)
765 struct remote_state *rs = get_remote_state ();
766 struct remote_arch_state *rsa = get_remote_arch_state ();
768 if (rs->explicit_packet_size)
769 return rs->explicit_packet_size;
771 return rsa->remote_packet_size;
774 static struct packet_reg *
775 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
777 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
781 struct packet_reg *r = &rsa->regs[regnum];
783 gdb_assert (r->regnum == regnum);
788 static struct packet_reg *
789 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
793 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
795 struct packet_reg *r = &rsa->regs[i];
803 static struct target_ops remote_ops;
805 static struct target_ops extended_remote_ops;
807 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
808 ``forever'' still use the normal timeout mechanism. This is
809 currently used by the ASYNC code to guarentee that target reads
810 during the initial connect always time-out. Once getpkt has been
811 modified to return a timeout indication and, in turn
812 remote_wait()/wait_for_inferior() have gained a timeout parameter
814 static int wait_forever_enabled_p = 1;
816 /* Allow the user to specify what sequence to send to the remote
817 when he requests a program interruption: Although ^C is usually
818 what remote systems expect (this is the default, here), it is
819 sometimes preferable to send a break. On other systems such
820 as the Linux kernel, a break followed by g, which is Magic SysRq g
821 is required in order to interrupt the execution. */
822 const char interrupt_sequence_control_c[] = "Ctrl-C";
823 const char interrupt_sequence_break[] = "BREAK";
824 const char interrupt_sequence_break_g[] = "BREAK-g";
825 static const char *const interrupt_sequence_modes[] =
827 interrupt_sequence_control_c,
828 interrupt_sequence_break,
829 interrupt_sequence_break_g,
832 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
835 show_interrupt_sequence (struct ui_file *file, int from_tty,
836 struct cmd_list_element *c,
839 if (interrupt_sequence_mode == interrupt_sequence_control_c)
840 fprintf_filtered (file,
841 _("Send the ASCII ETX character (Ctrl-c) "
842 "to the remote target to interrupt the "
843 "execution of the program.\n"));
844 else if (interrupt_sequence_mode == interrupt_sequence_break)
845 fprintf_filtered (file,
846 _("send a break signal to the remote target "
847 "to interrupt the execution of the program.\n"));
848 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
849 fprintf_filtered (file,
850 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
851 "the remote target to interrupt the execution "
852 "of Linux kernel.\n"));
854 internal_error (__FILE__, __LINE__,
855 _("Invalid value for interrupt_sequence_mode: %s."),
856 interrupt_sequence_mode);
859 /* This boolean variable specifies whether interrupt_sequence is sent
860 to the remote target when gdb connects to it.
861 This is mostly needed when you debug the Linux kernel: The Linux kernel
862 expects BREAK g which is Magic SysRq g for connecting gdb. */
863 static int interrupt_on_connect = 0;
865 /* This variable is used to implement the "set/show remotebreak" commands.
866 Since these commands are now deprecated in favor of "set/show remote
867 interrupt-sequence", it no longer has any effect on the code. */
868 static int remote_break;
871 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
874 interrupt_sequence_mode = interrupt_sequence_break;
876 interrupt_sequence_mode = interrupt_sequence_control_c;
880 show_remotebreak (struct ui_file *file, int from_tty,
881 struct cmd_list_element *c,
886 /* This variable sets the number of bits in an address that are to be
887 sent in a memory ("M" or "m") packet. Normally, after stripping
888 leading zeros, the entire address would be sent. This variable
889 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
890 initial implementation of remote.c restricted the address sent in
891 memory packets to ``host::sizeof long'' bytes - (typically 32
892 bits). Consequently, for 64 bit targets, the upper 32 bits of an
893 address was never sent. Since fixing this bug may cause a break in
894 some remote targets this variable is principly provided to
895 facilitate backward compatibility. */
897 static unsigned int remote_address_size;
899 /* Temporary to track who currently owns the terminal. See
900 remote_terminal_* for more details. */
902 static int remote_async_terminal_ours_p;
904 /* The executable file to use for "run" on the remote side. */
906 static char *remote_exec_file = "";
909 /* User configurable variables for the number of characters in a
910 memory read/write packet. MIN (rsa->remote_packet_size,
911 rsa->sizeof_g_packet) is the default. Some targets need smaller
912 values (fifo overruns, et.al.) and some users need larger values
913 (speed up transfers). The variables ``preferred_*'' (the user
914 request), ``current_*'' (what was actually set) and ``forced_*''
915 (Positive - a soft limit, negative - a hard limit). */
917 struct memory_packet_config
924 /* The default max memory-write-packet-size. The 16k is historical.
925 (It came from older GDB's using alloca for buffers and the
926 knowledge (folklore?) that some hosts don't cope very well with
927 large alloca calls.) */
928 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
930 /* The minimum remote packet size for memory transfers. Ensures we
931 can write at least one byte. */
932 #define MIN_MEMORY_PACKET_SIZE 20
934 /* Compute the current size of a read/write packet. Since this makes
935 use of ``actual_register_packet_size'' the computation is dynamic. */
938 get_memory_packet_size (struct memory_packet_config *config)
940 struct remote_state *rs = get_remote_state ();
941 struct remote_arch_state *rsa = get_remote_arch_state ();
946 if (config->size <= 0)
947 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
949 what_they_get = config->size;
953 what_they_get = get_remote_packet_size ();
954 /* Limit the packet to the size specified by the user. */
956 && what_they_get > config->size)
957 what_they_get = config->size;
959 /* Limit it to the size of the targets ``g'' response unless we have
960 permission from the stub to use a larger packet size. */
961 if (rs->explicit_packet_size == 0
962 && rsa->actual_register_packet_size > 0
963 && what_they_get > rsa->actual_register_packet_size)
964 what_they_get = rsa->actual_register_packet_size;
966 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
967 what_they_get = MIN_MEMORY_PACKET_SIZE;
969 /* Make sure there is room in the global buffer for this packet
970 (including its trailing NUL byte). */
971 if (rs->buf_size < what_they_get + 1)
973 rs->buf_size = 2 * what_they_get;
974 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
977 return what_they_get;
980 /* Update the size of a read/write packet. If they user wants
981 something really big then do a sanity check. */
984 set_memory_packet_size (char *args, struct memory_packet_config *config)
986 int fixed_p = config->fixed_p;
987 long size = config->size;
990 error (_("Argument required (integer, `fixed' or `limited')."));
991 else if (strcmp (args, "hard") == 0
992 || strcmp (args, "fixed") == 0)
994 else if (strcmp (args, "soft") == 0
995 || strcmp (args, "limit") == 0)
1001 size = strtoul (args, &end, 0);
1003 error (_("Invalid %s (bad syntax)."), config->name);
1005 /* Instead of explicitly capping the size of a packet to or
1006 disallowing it, the user is allowed to set the size to
1007 something arbitrarily large. */
1010 /* So that the query shows the correct value. */
1012 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1015 if (fixed_p && !config->fixed_p)
1017 if (! query (_("The target may not be able to correctly handle a %s\n"
1018 "of %ld bytes. Change the packet size? "),
1019 config->name, size))
1020 error (_("Packet size not changed."));
1022 /* Update the config. */
1023 config->fixed_p = fixed_p;
1024 config->size = size;
1028 show_memory_packet_size (struct memory_packet_config *config)
1030 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1031 if (config->fixed_p)
1032 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1033 get_memory_packet_size (config));
1035 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1036 get_memory_packet_size (config));
1039 static struct memory_packet_config memory_write_packet_config =
1041 "memory-write-packet-size",
1045 set_memory_write_packet_size (char *args, int from_tty)
1047 set_memory_packet_size (args, &memory_write_packet_config);
1051 show_memory_write_packet_size (char *args, int from_tty)
1053 show_memory_packet_size (&memory_write_packet_config);
1057 get_memory_write_packet_size (void)
1059 return get_memory_packet_size (&memory_write_packet_config);
1062 static struct memory_packet_config memory_read_packet_config =
1064 "memory-read-packet-size",
1068 set_memory_read_packet_size (char *args, int from_tty)
1070 set_memory_packet_size (args, &memory_read_packet_config);
1074 show_memory_read_packet_size (char *args, int from_tty)
1076 show_memory_packet_size (&memory_read_packet_config);
1080 get_memory_read_packet_size (void)
1082 long size = get_memory_packet_size (&memory_read_packet_config);
1084 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1085 extra buffer size argument before the memory read size can be
1086 increased beyond this. */
1087 if (size > get_remote_packet_size ())
1088 size = get_remote_packet_size ();
1093 /* Generic configuration support for packets the stub optionally
1094 supports. Allows the user to specify the use of the packet as well
1095 as allowing GDB to auto-detect support in the remote stub. */
1099 PACKET_SUPPORT_UNKNOWN = 0,
1104 struct packet_config
1109 /* If auto, GDB auto-detects support for this packet or feature,
1110 either through qSupported, or by trying the packet and looking
1111 at the response. If true, GDB assumes the target supports this
1112 packet. If false, the packet is disabled. Configs that don't
1113 have an associated command always have this set to auto. */
1114 enum auto_boolean detect;
1116 /* Does the target support this packet? */
1117 enum packet_support support;
1120 /* Analyze a packet's return value and update the packet config
1130 static enum packet_support packet_config_support (struct packet_config *config);
1131 static enum packet_support packet_support (int packet);
1134 show_packet_config_cmd (struct packet_config *config)
1136 char *support = "internal-error";
1138 switch (packet_config_support (config))
1141 support = "enabled";
1143 case PACKET_DISABLE:
1144 support = "disabled";
1146 case PACKET_SUPPORT_UNKNOWN:
1147 support = "unknown";
1150 switch (config->detect)
1152 case AUTO_BOOLEAN_AUTO:
1153 printf_filtered (_("Support for the `%s' packet "
1154 "is auto-detected, currently %s.\n"),
1155 config->name, support);
1157 case AUTO_BOOLEAN_TRUE:
1158 case AUTO_BOOLEAN_FALSE:
1159 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1160 config->name, support);
1166 add_packet_config_cmd (struct packet_config *config, const char *name,
1167 const char *title, int legacy)
1173 config->name = name;
1174 config->title = title;
1175 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1177 show_doc = xstrprintf ("Show current use of remote "
1178 "protocol `%s' (%s) packet",
1180 /* set/show TITLE-packet {auto,on,off} */
1181 cmd_name = xstrprintf ("%s-packet", title);
1182 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1183 &config->detect, set_doc,
1184 show_doc, NULL, /* help_doc */
1186 show_remote_protocol_packet_cmd,
1187 &remote_set_cmdlist, &remote_show_cmdlist);
1188 /* The command code copies the documentation strings. */
1191 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1196 legacy_name = xstrprintf ("%s-packet", name);
1197 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1198 &remote_set_cmdlist);
1199 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1200 &remote_show_cmdlist);
1204 static enum packet_result
1205 packet_check_result (const char *buf)
1209 /* The stub recognized the packet request. Check that the
1210 operation succeeded. */
1212 && isxdigit (buf[1]) && isxdigit (buf[2])
1214 /* "Enn" - definitly an error. */
1215 return PACKET_ERROR;
1217 /* Always treat "E." as an error. This will be used for
1218 more verbose error messages, such as E.memtypes. */
1219 if (buf[0] == 'E' && buf[1] == '.')
1220 return PACKET_ERROR;
1222 /* The packet may or may not be OK. Just assume it is. */
1226 /* The stub does not support the packet. */
1227 return PACKET_UNKNOWN;
1230 static enum packet_result
1231 packet_ok (const char *buf, struct packet_config *config)
1233 enum packet_result result;
1235 if (config->detect != AUTO_BOOLEAN_TRUE
1236 && config->support == PACKET_DISABLE)
1237 internal_error (__FILE__, __LINE__,
1238 _("packet_ok: attempt to use a disabled packet"));
1240 result = packet_check_result (buf);
1245 /* The stub recognized the packet request. */
1246 if (config->support == PACKET_SUPPORT_UNKNOWN)
1249 fprintf_unfiltered (gdb_stdlog,
1250 "Packet %s (%s) is supported\n",
1251 config->name, config->title);
1252 config->support = PACKET_ENABLE;
1255 case PACKET_UNKNOWN:
1256 /* The stub does not support the packet. */
1257 if (config->detect == AUTO_BOOLEAN_AUTO
1258 && config->support == PACKET_ENABLE)
1260 /* If the stub previously indicated that the packet was
1261 supported then there is a protocol error. */
1262 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1263 config->name, config->title);
1265 else if (config->detect == AUTO_BOOLEAN_TRUE)
1267 /* The user set it wrong. */
1268 error (_("Enabled packet %s (%s) not recognized by stub"),
1269 config->name, config->title);
1273 fprintf_unfiltered (gdb_stdlog,
1274 "Packet %s (%s) is NOT supported\n",
1275 config->name, config->title);
1276 config->support = PACKET_DISABLE;
1297 PACKET_vFile_pwrite,
1299 PACKET_vFile_unlink,
1300 PACKET_vFile_readlink,
1303 PACKET_qXfer_features,
1304 PACKET_qXfer_exec_file,
1305 PACKET_qXfer_libraries,
1306 PACKET_qXfer_libraries_svr4,
1307 PACKET_qXfer_memory_map,
1308 PACKET_qXfer_spu_read,
1309 PACKET_qXfer_spu_write,
1310 PACKET_qXfer_osdata,
1311 PACKET_qXfer_threads,
1312 PACKET_qXfer_statictrace_read,
1313 PACKET_qXfer_traceframe_info,
1319 PACKET_QPassSignals,
1320 PACKET_QProgramSignals,
1322 PACKET_qSearch_memory,
1325 PACKET_QStartNoAckMode,
1327 PACKET_qXfer_siginfo_read,
1328 PACKET_qXfer_siginfo_write,
1331 /* Support for conditional tracepoints. */
1332 PACKET_ConditionalTracepoints,
1334 /* Support for target-side breakpoint conditions. */
1335 PACKET_ConditionalBreakpoints,
1337 /* Support for target-side breakpoint commands. */
1338 PACKET_BreakpointCommands,
1340 /* Support for fast tracepoints. */
1341 PACKET_FastTracepoints,
1343 /* Support for static tracepoints. */
1344 PACKET_StaticTracepoints,
1346 /* Support for installing tracepoints while a trace experiment is
1348 PACKET_InstallInTrace,
1352 PACKET_TracepointSource,
1355 PACKET_QDisableRandomization,
1357 PACKET_QTBuffer_size,
1361 PACKET_qXfer_btrace,
1363 /* Support for the QNonStop packet. */
1366 /* Support for multi-process extensions. */
1367 PACKET_multiprocess_feature,
1369 /* Support for enabling and disabling tracepoints while a trace
1370 experiment is running. */
1371 PACKET_EnableDisableTracepoints_feature,
1373 /* Support for collecting strings using the tracenz bytecode. */
1374 PACKET_tracenz_feature,
1376 /* Support for continuing to run a trace experiment while GDB is
1378 PACKET_DisconnectedTracing_feature,
1380 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1381 PACKET_augmented_libraries_svr4_read_feature,
1383 /* Support for the qXfer:btrace-conf:read packet. */
1384 PACKET_qXfer_btrace_conf,
1386 /* Support for the Qbtrace-conf:bts:size packet. */
1387 PACKET_Qbtrace_conf_bts_size,
1389 /* Support for swbreak+ feature. */
1390 PACKET_swbreak_feature,
1392 /* Support for hwbreak+ feature. */
1393 PACKET_hwbreak_feature,
1395 /* Support for fork events. */
1396 PACKET_fork_event_feature,
1398 /* Support for vfork events. */
1399 PACKET_vfork_event_feature,
1401 /* Support for the Qbtrace-conf:pt:size packet. */
1402 PACKET_Qbtrace_conf_pt_size,
1407 static struct packet_config remote_protocol_packets[PACKET_MAX];
1409 /* Returns the packet's corresponding "set remote foo-packet" command
1410 state. See struct packet_config for more details. */
1412 static enum auto_boolean
1413 packet_set_cmd_state (int packet)
1415 return remote_protocol_packets[packet].detect;
1418 /* Returns whether a given packet or feature is supported. This takes
1419 into account the state of the corresponding "set remote foo-packet"
1420 command, which may be used to bypass auto-detection. */
1422 static enum packet_support
1423 packet_config_support (struct packet_config *config)
1425 switch (config->detect)
1427 case AUTO_BOOLEAN_TRUE:
1428 return PACKET_ENABLE;
1429 case AUTO_BOOLEAN_FALSE:
1430 return PACKET_DISABLE;
1431 case AUTO_BOOLEAN_AUTO:
1432 return config->support;
1434 gdb_assert_not_reached (_("bad switch"));
1438 /* Same as packet_config_support, but takes the packet's enum value as
1441 static enum packet_support
1442 packet_support (int packet)
1444 struct packet_config *config = &remote_protocol_packets[packet];
1446 return packet_config_support (config);
1450 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1451 struct cmd_list_element *c,
1454 struct packet_config *packet;
1456 for (packet = remote_protocol_packets;
1457 packet < &remote_protocol_packets[PACKET_MAX];
1460 if (&packet->detect == c->var)
1462 show_packet_config_cmd (packet);
1466 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1470 /* Should we try one of the 'Z' requests? */
1474 Z_PACKET_SOFTWARE_BP,
1475 Z_PACKET_HARDWARE_BP,
1482 /* For compatibility with older distributions. Provide a ``set remote
1483 Z-packet ...'' command that updates all the Z packet types. */
1485 static enum auto_boolean remote_Z_packet_detect;
1488 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1489 struct cmd_list_element *c)
1493 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1494 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1498 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1499 struct cmd_list_element *c,
1504 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1506 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1510 /* Returns true if the multi-process extensions are in effect. */
1513 remote_multi_process_p (struct remote_state *rs)
1515 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1518 /* Returns true if fork events are supported. */
1521 remote_fork_event_p (struct remote_state *rs)
1523 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1526 /* Returns true if vfork events are supported. */
1529 remote_vfork_event_p (struct remote_state *rs)
1531 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1534 /* Insert fork catchpoint target routine. If fork events are enabled
1535 then return success, nothing more to do. */
1538 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1540 struct remote_state *rs = get_remote_state ();
1542 return !remote_fork_event_p (rs);
1545 /* Remove fork catchpoint target routine. Nothing to do, just
1549 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1554 /* Insert vfork catchpoint target routine. If vfork events are enabled
1555 then return success, nothing more to do. */
1558 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1560 struct remote_state *rs = get_remote_state ();
1562 return !remote_vfork_event_p (rs);
1565 /* Remove vfork catchpoint target routine. Nothing to do, just
1569 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1574 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1575 static struct async_signal_handler *async_sigint_remote_twice_token;
1576 static struct async_signal_handler *async_sigint_remote_token;
1579 /* Asynchronous signal handle registered as event loop source for
1580 when we have pending events ready to be passed to the core. */
1582 static struct async_event_handler *remote_async_inferior_event_token;
1586 static ptid_t magic_null_ptid;
1587 static ptid_t not_sent_ptid;
1588 static ptid_t any_thread_ptid;
1590 /* Find out if the stub attached to PID (and hence GDB should offer to
1591 detach instead of killing it when bailing out). */
1594 remote_query_attached (int pid)
1596 struct remote_state *rs = get_remote_state ();
1597 size_t size = get_remote_packet_size ();
1599 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1602 if (remote_multi_process_p (rs))
1603 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1605 xsnprintf (rs->buf, size, "qAttached");
1608 getpkt (&rs->buf, &rs->buf_size, 0);
1610 switch (packet_ok (rs->buf,
1611 &remote_protocol_packets[PACKET_qAttached]))
1614 if (strcmp (rs->buf, "1") == 0)
1618 warning (_("Remote failure reply: %s"), rs->buf);
1620 case PACKET_UNKNOWN:
1627 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1628 has been invented by GDB, instead of reported by the target. Since
1629 we can be connected to a remote system before before knowing about
1630 any inferior, mark the target with execution when we find the first
1631 inferior. If ATTACHED is 1, then we had just attached to this
1632 inferior. If it is 0, then we just created this inferior. If it
1633 is -1, then try querying the remote stub to find out if it had
1634 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1635 attempt to open this inferior's executable as the main executable
1636 if no main executable is open already. */
1638 static struct inferior *
1639 remote_add_inferior (int fake_pid_p, int pid, int attached,
1642 struct inferior *inf;
1644 /* Check whether this process we're learning about is to be
1645 considered attached, or if is to be considered to have been
1646 spawned by the stub. */
1648 attached = remote_query_attached (pid);
1650 if (gdbarch_has_global_solist (target_gdbarch ()))
1652 /* If the target shares code across all inferiors, then every
1653 attach adds a new inferior. */
1654 inf = add_inferior (pid);
1656 /* ... and every inferior is bound to the same program space.
1657 However, each inferior may still have its own address
1659 inf->aspace = maybe_new_address_space ();
1660 inf->pspace = current_program_space;
1664 /* In the traditional debugging scenario, there's a 1-1 match
1665 between program/address spaces. We simply bind the inferior
1666 to the program space's address space. */
1667 inf = current_inferior ();
1668 inferior_appeared (inf, pid);
1671 inf->attach_flag = attached;
1672 inf->fake_pid_p = fake_pid_p;
1674 /* If no main executable is currently open then attempt to
1675 open the file that was executed to create this inferior. */
1676 if (try_open_exec && get_exec_file (0) == NULL)
1677 exec_file_locate_attach (pid, 1);
1682 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1683 according to RUNNING. */
1686 remote_add_thread (ptid_t ptid, int running)
1688 struct remote_state *rs = get_remote_state ();
1690 /* GDB historically didn't pull threads in the initial connection
1691 setup. If the remote target doesn't even have a concept of
1692 threads (e.g., a bare-metal target), even if internally we
1693 consider that a single-threaded target, mentioning a new thread
1694 might be confusing to the user. Be silent then, preserving the
1695 age old behavior. */
1696 if (rs->starting_up)
1697 add_thread_silent (ptid);
1701 set_executing (ptid, running);
1702 set_running (ptid, running);
1705 /* Come here when we learn about a thread id from the remote target.
1706 It may be the first time we hear about such thread, so take the
1707 opportunity to add it to GDB's thread list. In case this is the
1708 first time we're noticing its corresponding inferior, add it to
1709 GDB's inferior list as well. */
1712 remote_notice_new_inferior (ptid_t currthread, int running)
1714 /* If this is a new thread, add it to GDB's thread list.
1715 If we leave it up to WFI to do this, bad things will happen. */
1717 if (in_thread_list (currthread) && is_exited (currthread))
1719 /* We're seeing an event on a thread id we knew had exited.
1720 This has to be a new thread reusing the old id. Add it. */
1721 remote_add_thread (currthread, running);
1725 if (!in_thread_list (currthread))
1727 struct inferior *inf = NULL;
1728 int pid = ptid_get_pid (currthread);
1730 if (ptid_is_pid (inferior_ptid)
1731 && pid == ptid_get_pid (inferior_ptid))
1733 /* inferior_ptid has no thread member yet. This can happen
1734 with the vAttach -> remote_wait,"TAAthread:" path if the
1735 stub doesn't support qC. This is the first stop reported
1736 after an attach, so this is the main thread. Update the
1737 ptid in the thread list. */
1738 if (in_thread_list (pid_to_ptid (pid)))
1739 thread_change_ptid (inferior_ptid, currthread);
1742 remote_add_thread (currthread, running);
1743 inferior_ptid = currthread;
1748 if (ptid_equal (magic_null_ptid, inferior_ptid))
1750 /* inferior_ptid is not set yet. This can happen with the
1751 vRun -> remote_wait,"TAAthread:" path if the stub
1752 doesn't support qC. This is the first stop reported
1753 after an attach, so this is the main thread. Update the
1754 ptid in the thread list. */
1755 thread_change_ptid (inferior_ptid, currthread);
1759 /* When connecting to a target remote, or to a target
1760 extended-remote which already was debugging an inferior, we
1761 may not know about it yet. Add it before adding its child
1762 thread, so notifications are emitted in a sensible order. */
1763 if (!in_inferior_list (ptid_get_pid (currthread)))
1765 struct remote_state *rs = get_remote_state ();
1766 int fake_pid_p = !remote_multi_process_p (rs);
1768 inf = remote_add_inferior (fake_pid_p,
1769 ptid_get_pid (currthread), -1, 1);
1772 /* This is really a new thread. Add it. */
1773 remote_add_thread (currthread, running);
1775 /* If we found a new inferior, let the common code do whatever
1776 it needs to with it (e.g., read shared libraries, insert
1777 breakpoints), unless we're just setting up an all-stop
1781 struct remote_state *rs = get_remote_state ();
1783 if (non_stop || !rs->starting_up)
1784 notice_new_inferior (currthread, running, 0);
1789 /* Return the private thread data, creating it if necessary. */
1791 static struct private_thread_info *
1792 demand_private_info (ptid_t ptid)
1794 struct thread_info *info = find_thread_ptid (ptid);
1800 info->priv = XNEW (struct private_thread_info);
1801 info->private_dtor = free_private_thread_info;
1802 info->priv->core = -1;
1803 info->priv->extra = 0;
1809 /* Call this function as a result of
1810 1) A halt indication (T packet) containing a thread id
1811 2) A direct query of currthread
1812 3) Successful execution of set thread */
1815 record_currthread (struct remote_state *rs, ptid_t currthread)
1817 rs->general_thread = currthread;
1820 /* If 'QPassSignals' is supported, tell the remote stub what signals
1821 it can simply pass through to the inferior without reporting. */
1824 remote_pass_signals (struct target_ops *self,
1825 int numsigs, unsigned char *pass_signals)
1827 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1829 char *pass_packet, *p;
1831 struct remote_state *rs = get_remote_state ();
1833 gdb_assert (numsigs < 256);
1834 for (i = 0; i < numsigs; i++)
1836 if (pass_signals[i])
1839 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1840 strcpy (pass_packet, "QPassSignals:");
1841 p = pass_packet + strlen (pass_packet);
1842 for (i = 0; i < numsigs; i++)
1844 if (pass_signals[i])
1847 *p++ = tohex (i >> 4);
1848 *p++ = tohex (i & 15);
1857 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1859 putpkt (pass_packet);
1860 getpkt (&rs->buf, &rs->buf_size, 0);
1861 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1862 if (rs->last_pass_packet)
1863 xfree (rs->last_pass_packet);
1864 rs->last_pass_packet = pass_packet;
1867 xfree (pass_packet);
1871 /* If 'QProgramSignals' is supported, tell the remote stub what
1872 signals it should pass through to the inferior when detaching. */
1875 remote_program_signals (struct target_ops *self,
1876 int numsigs, unsigned char *signals)
1878 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1882 struct remote_state *rs = get_remote_state ();
1884 gdb_assert (numsigs < 256);
1885 for (i = 0; i < numsigs; i++)
1890 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1891 strcpy (packet, "QProgramSignals:");
1892 p = packet + strlen (packet);
1893 for (i = 0; i < numsigs; i++)
1895 if (signal_pass_state (i))
1898 *p++ = tohex (i >> 4);
1899 *p++ = tohex (i & 15);
1908 if (!rs->last_program_signals_packet
1909 || strcmp (rs->last_program_signals_packet, packet) != 0)
1912 getpkt (&rs->buf, &rs->buf_size, 0);
1913 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1914 xfree (rs->last_program_signals_packet);
1915 rs->last_program_signals_packet = packet;
1922 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1923 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1924 thread. If GEN is set, set the general thread, if not, then set
1925 the step/continue thread. */
1927 set_thread (struct ptid ptid, int gen)
1929 struct remote_state *rs = get_remote_state ();
1930 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1931 char *buf = rs->buf;
1932 char *endbuf = rs->buf + get_remote_packet_size ();
1934 if (ptid_equal (state, ptid))
1938 *buf++ = gen ? 'g' : 'c';
1939 if (ptid_equal (ptid, magic_null_ptid))
1940 xsnprintf (buf, endbuf - buf, "0");
1941 else if (ptid_equal (ptid, any_thread_ptid))
1942 xsnprintf (buf, endbuf - buf, "0");
1943 else if (ptid_equal (ptid, minus_one_ptid))
1944 xsnprintf (buf, endbuf - buf, "-1");
1946 write_ptid (buf, endbuf, ptid);
1948 getpkt (&rs->buf, &rs->buf_size, 0);
1950 rs->general_thread = ptid;
1952 rs->continue_thread = ptid;
1956 set_general_thread (struct ptid ptid)
1958 set_thread (ptid, 1);
1962 set_continue_thread (struct ptid ptid)
1964 set_thread (ptid, 0);
1967 /* Change the remote current process. Which thread within the process
1968 ends up selected isn't important, as long as it is the same process
1969 as what INFERIOR_PTID points to.
1971 This comes from that fact that there is no explicit notion of
1972 "selected process" in the protocol. The selected process for
1973 general operations is the process the selected general thread
1977 set_general_process (void)
1979 struct remote_state *rs = get_remote_state ();
1981 /* If the remote can't handle multiple processes, don't bother. */
1982 if (!rs->extended || !remote_multi_process_p (rs))
1985 /* We only need to change the remote current thread if it's pointing
1986 at some other process. */
1987 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1988 set_general_thread (inferior_ptid);
1992 /* Return nonzero if this is the main thread that we made up ourselves
1993 to model non-threaded targets as single-threaded. */
1996 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1998 struct remote_state *rs = get_remote_state ();
2001 if (ptid_equal (ptid, magic_null_ptid))
2002 /* The main thread is always alive. */
2005 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2006 /* The main thread is always alive. This can happen after a
2007 vAttach, if the remote side doesn't support
2014 /* Return nonzero if the thread PTID is still alive on the remote
2018 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2020 struct remote_state *rs = get_remote_state ();
2023 /* Check if this is a thread that we made up ourselves to model
2024 non-threaded targets as single-threaded. */
2025 if (remote_thread_always_alive (ops, ptid))
2029 endp = rs->buf + get_remote_packet_size ();
2032 write_ptid (p, endp, ptid);
2035 getpkt (&rs->buf, &rs->buf_size, 0);
2036 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2039 /* About these extended threadlist and threadinfo packets. They are
2040 variable length packets but, the fields within them are often fixed
2041 length. They are redundent enough to send over UDP as is the
2042 remote protocol in general. There is a matching unit test module
2045 /* WARNING: This threadref data structure comes from the remote O.S.,
2046 libstub protocol encoding, and remote.c. It is not particularly
2049 /* Right now, the internal structure is int. We want it to be bigger.
2050 Plan to fix this. */
2052 typedef int gdb_threadref; /* Internal GDB thread reference. */
2054 /* gdb_ext_thread_info is an internal GDB data structure which is
2055 equivalent to the reply of the remote threadinfo packet. */
2057 struct gdb_ext_thread_info
2059 threadref threadid; /* External form of thread reference. */
2060 int active; /* Has state interesting to GDB?
2062 char display[256]; /* Brief state display, name,
2063 blocked/suspended. */
2064 char shortname[32]; /* To be used to name threads. */
2065 char more_display[256]; /* Long info, statistics, queue depth,
2069 /* The volume of remote transfers can be limited by submitting
2070 a mask containing bits specifying the desired information.
2071 Use a union of these values as the 'selection' parameter to
2072 get_thread_info. FIXME: Make these TAG names more thread specific. */
2074 #define TAG_THREADID 1
2075 #define TAG_EXISTS 2
2076 #define TAG_DISPLAY 4
2077 #define TAG_THREADNAME 8
2078 #define TAG_MOREDISPLAY 16
2080 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2082 static char *unpack_nibble (char *buf, int *val);
2084 static char *unpack_byte (char *buf, int *value);
2086 static char *pack_int (char *buf, int value);
2088 static char *unpack_int (char *buf, int *value);
2090 static char *unpack_string (char *src, char *dest, int length);
2092 static char *pack_threadid (char *pkt, threadref *id);
2094 static char *unpack_threadid (char *inbuf, threadref *id);
2096 void int_to_threadref (threadref *id, int value);
2098 static int threadref_to_int (threadref *ref);
2100 static void copy_threadref (threadref *dest, threadref *src);
2102 static int threadmatch (threadref *dest, threadref *src);
2104 static char *pack_threadinfo_request (char *pkt, int mode,
2107 static int remote_unpack_thread_info_response (char *pkt,
2108 threadref *expectedref,
2109 struct gdb_ext_thread_info
2113 static int remote_get_threadinfo (threadref *threadid,
2114 int fieldset, /*TAG mask */
2115 struct gdb_ext_thread_info *info);
2117 static char *pack_threadlist_request (char *pkt, int startflag,
2119 threadref *nextthread);
2121 static int parse_threadlist_response (char *pkt,
2123 threadref *original_echo,
2124 threadref *resultlist,
2127 static int remote_get_threadlist (int startflag,
2128 threadref *nextthread,
2132 threadref *threadlist);
2134 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2136 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2137 void *context, int looplimit);
2139 static int remote_newthread_step (threadref *ref, void *context);
2142 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2143 buffer we're allowed to write to. Returns
2144 BUF+CHARACTERS_WRITTEN. */
2147 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2150 struct remote_state *rs = get_remote_state ();
2152 if (remote_multi_process_p (rs))
2154 pid = ptid_get_pid (ptid);
2156 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2158 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2160 tid = ptid_get_lwp (ptid);
2162 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2164 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2169 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2170 passed the last parsed char. Returns null_ptid on error. */
2173 read_ptid (char *buf, char **obuf)
2177 ULONGEST pid = 0, tid = 0;
2181 /* Multi-process ptid. */
2182 pp = unpack_varlen_hex (p + 1, &pid);
2184 error (_("invalid remote ptid: %s"), p);
2187 pp = unpack_varlen_hex (p + 1, &tid);
2190 return ptid_build (pid, tid, 0);
2193 /* No multi-process. Just a tid. */
2194 pp = unpack_varlen_hex (p, &tid);
2196 /* Return null_ptid when no thread id is found. */
2204 /* Since the stub is not sending a process id, then default to
2205 what's in inferior_ptid, unless it's null at this point. If so,
2206 then since there's no way to know the pid of the reported
2207 threads, use the magic number. */
2208 if (ptid_equal (inferior_ptid, null_ptid))
2209 pid = ptid_get_pid (magic_null_ptid);
2211 pid = ptid_get_pid (inferior_ptid);
2215 return ptid_build (pid, tid, 0);
2221 if (ch >= 'a' && ch <= 'f')
2222 return ch - 'a' + 10;
2223 if (ch >= '0' && ch <= '9')
2225 if (ch >= 'A' && ch <= 'F')
2226 return ch - 'A' + 10;
2231 stub_unpack_int (char *buff, int fieldlength)
2238 nibble = stubhex (*buff++);
2242 retval = retval << 4;
2248 unpack_nibble (char *buf, int *val)
2250 *val = fromhex (*buf++);
2255 unpack_byte (char *buf, int *value)
2257 *value = stub_unpack_int (buf, 2);
2262 pack_int (char *buf, int value)
2264 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2265 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2266 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2267 buf = pack_hex_byte (buf, (value & 0xff));
2272 unpack_int (char *buf, int *value)
2274 *value = stub_unpack_int (buf, 8);
2278 #if 0 /* Currently unused, uncomment when needed. */
2279 static char *pack_string (char *pkt, char *string);
2282 pack_string (char *pkt, char *string)
2287 len = strlen (string);
2289 len = 200; /* Bigger than most GDB packets, junk??? */
2290 pkt = pack_hex_byte (pkt, len);
2294 if ((ch == '\0') || (ch == '#'))
2295 ch = '*'; /* Protect encapsulation. */
2300 #endif /* 0 (unused) */
2303 unpack_string (char *src, char *dest, int length)
2312 pack_threadid (char *pkt, threadref *id)
2315 unsigned char *altid;
2317 altid = (unsigned char *) id;
2318 limit = pkt + BUF_THREAD_ID_SIZE;
2320 pkt = pack_hex_byte (pkt, *altid++);
2326 unpack_threadid (char *inbuf, threadref *id)
2329 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2332 altref = (char *) id;
2334 while (inbuf < limit)
2336 x = stubhex (*inbuf++);
2337 y = stubhex (*inbuf++);
2338 *altref++ = (x << 4) | y;
2343 /* Externally, threadrefs are 64 bits but internally, they are still
2344 ints. This is due to a mismatch of specifications. We would like
2345 to use 64bit thread references internally. This is an adapter
2349 int_to_threadref (threadref *id, int value)
2351 unsigned char *scan;
2353 scan = (unsigned char *) id;
2359 *scan++ = (value >> 24) & 0xff;
2360 *scan++ = (value >> 16) & 0xff;
2361 *scan++ = (value >> 8) & 0xff;
2362 *scan++ = (value & 0xff);
2366 threadref_to_int (threadref *ref)
2369 unsigned char *scan;
2375 value = (value << 8) | ((*scan++) & 0xff);
2380 copy_threadref (threadref *dest, threadref *src)
2383 unsigned char *csrc, *cdest;
2385 csrc = (unsigned char *) src;
2386 cdest = (unsigned char *) dest;
2393 threadmatch (threadref *dest, threadref *src)
2395 /* Things are broken right now, so just assume we got a match. */
2397 unsigned char *srcp, *destp;
2399 srcp = (char *) src;
2400 destp = (char *) dest;
2404 result &= (*srcp++ == *destp++) ? 1 : 0;
2411 threadid:1, # always request threadid
2418 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2421 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2423 *pkt++ = 'q'; /* Info Query */
2424 *pkt++ = 'P'; /* process or thread info */
2425 pkt = pack_int (pkt, mode); /* mode */
2426 pkt = pack_threadid (pkt, id); /* threadid */
2427 *pkt = '\0'; /* terminate */
2431 /* These values tag the fields in a thread info response packet. */
2432 /* Tagging the fields allows us to request specific fields and to
2433 add more fields as time goes by. */
2435 #define TAG_THREADID 1 /* Echo the thread identifier. */
2436 #define TAG_EXISTS 2 /* Is this process defined enough to
2437 fetch registers and its stack? */
2438 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2439 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2440 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2444 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2445 struct gdb_ext_thread_info *info)
2447 struct remote_state *rs = get_remote_state ();
2451 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2454 /* info->threadid = 0; FIXME: implement zero_threadref. */
2456 info->display[0] = '\0';
2457 info->shortname[0] = '\0';
2458 info->more_display[0] = '\0';
2460 /* Assume the characters indicating the packet type have been
2462 pkt = unpack_int (pkt, &mask); /* arg mask */
2463 pkt = unpack_threadid (pkt, &ref);
2466 warning (_("Incomplete response to threadinfo request."));
2467 if (!threadmatch (&ref, expectedref))
2468 { /* This is an answer to a different request. */
2469 warning (_("ERROR RMT Thread info mismatch."));
2472 copy_threadref (&info->threadid, &ref);
2474 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2476 /* Packets are terminated with nulls. */
2477 while ((pkt < limit) && mask && *pkt)
2479 pkt = unpack_int (pkt, &tag); /* tag */
2480 pkt = unpack_byte (pkt, &length); /* length */
2481 if (!(tag & mask)) /* Tags out of synch with mask. */
2483 warning (_("ERROR RMT: threadinfo tag mismatch."));
2487 if (tag == TAG_THREADID)
2491 warning (_("ERROR RMT: length of threadid is not 16."));
2495 pkt = unpack_threadid (pkt, &ref);
2496 mask = mask & ~TAG_THREADID;
2499 if (tag == TAG_EXISTS)
2501 info->active = stub_unpack_int (pkt, length);
2503 mask = mask & ~(TAG_EXISTS);
2506 warning (_("ERROR RMT: 'exists' length too long."));
2512 if (tag == TAG_THREADNAME)
2514 pkt = unpack_string (pkt, &info->shortname[0], length);
2515 mask = mask & ~TAG_THREADNAME;
2518 if (tag == TAG_DISPLAY)
2520 pkt = unpack_string (pkt, &info->display[0], length);
2521 mask = mask & ~TAG_DISPLAY;
2524 if (tag == TAG_MOREDISPLAY)
2526 pkt = unpack_string (pkt, &info->more_display[0], length);
2527 mask = mask & ~TAG_MOREDISPLAY;
2530 warning (_("ERROR RMT: unknown thread info tag."));
2531 break; /* Not a tag we know about. */
2537 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2538 struct gdb_ext_thread_info *info)
2540 struct remote_state *rs = get_remote_state ();
2543 pack_threadinfo_request (rs->buf, fieldset, threadid);
2545 getpkt (&rs->buf, &rs->buf_size, 0);
2547 if (rs->buf[0] == '\0')
2550 result = remote_unpack_thread_info_response (rs->buf + 2,
2555 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2558 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2559 threadref *nextthread)
2561 *pkt++ = 'q'; /* info query packet */
2562 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2563 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2564 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2565 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2570 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2573 parse_threadlist_response (char *pkt, int result_limit,
2574 threadref *original_echo, threadref *resultlist,
2577 struct remote_state *rs = get_remote_state ();
2579 int count, resultcount, done;
2582 /* Assume the 'q' and 'M chars have been stripped. */
2583 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2584 /* done parse past here */
2585 pkt = unpack_byte (pkt, &count); /* count field */
2586 pkt = unpack_nibble (pkt, &done);
2587 /* The first threadid is the argument threadid. */
2588 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2589 while ((count-- > 0) && (pkt < limit))
2591 pkt = unpack_threadid (pkt, resultlist++);
2592 if (resultcount++ >= result_limit)
2600 /* Fetch the next batch of threads from the remote. Returns -1 if the
2601 qL packet is not supported, 0 on error and 1 on success. */
2604 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2605 int *done, int *result_count, threadref *threadlist)
2607 struct remote_state *rs = get_remote_state ();
2610 /* Trancate result limit to be smaller than the packet size. */
2611 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2612 >= get_remote_packet_size ())
2613 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2615 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2617 getpkt (&rs->buf, &rs->buf_size, 0);
2618 if (*rs->buf == '\0')
2620 /* Packet not supported. */
2625 parse_threadlist_response (rs->buf + 2, result_limit,
2626 &rs->echo_nextthread, threadlist, done);
2628 if (!threadmatch (&rs->echo_nextthread, nextthread))
2630 /* FIXME: This is a good reason to drop the packet. */
2631 /* Possably, there is a duplicate response. */
2633 retransmit immediatly - race conditions
2634 retransmit after timeout - yes
2636 wait for packet, then exit
2638 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2639 return 0; /* I choose simply exiting. */
2641 if (*result_count <= 0)
2645 warning (_("RMT ERROR : failed to get remote thread list."));
2648 return result; /* break; */
2650 if (*result_count > result_limit)
2653 warning (_("RMT ERROR: threadlist response longer than requested."));
2659 /* Fetch the list of remote threads, with the qL packet, and call
2660 STEPFUNCTION for each thread found. Stops iterating and returns 1
2661 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2662 STEPFUNCTION returns false. If the packet is not supported,
2666 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2669 struct remote_state *rs = get_remote_state ();
2670 int done, i, result_count;
2678 if (loopcount++ > looplimit)
2681 warning (_("Remote fetch threadlist -infinite loop-."));
2684 result = remote_get_threadlist (startflag, &rs->nextthread,
2685 MAXTHREADLISTRESULTS,
2686 &done, &result_count,
2687 rs->resultthreadlist);
2690 /* Clear for later iterations. */
2692 /* Setup to resume next batch of thread references, set nextthread. */
2693 if (result_count >= 1)
2694 copy_threadref (&rs->nextthread,
2695 &rs->resultthreadlist[result_count - 1]);
2697 while (result_count--)
2699 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2709 /* A thread found on the remote target. */
2711 typedef struct thread_item
2713 /* The thread's PTID. */
2716 /* The thread's extra info. May be NULL. */
2719 /* The core the thread was running on. -1 if not known. */
2722 DEF_VEC_O(thread_item_t);
2724 /* Context passed around to the various methods listing remote
2725 threads. As new threads are found, they're added to the ITEMS
2728 struct threads_listing_context
2730 /* The threads found on the remote target. */
2731 VEC (thread_item_t) *items;
2734 /* Discard the contents of the constructed thread listing context. */
2737 clear_threads_listing_context (void *p)
2739 struct threads_listing_context *context = p;
2741 struct thread_item *item;
2743 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2744 xfree (item->extra);
2746 VEC_free (thread_item_t, context->items);
2749 /* Remove the thread specified as the related_pid field of WS
2750 from the CONTEXT list. */
2753 threads_listing_context_remove (struct target_waitstatus *ws,
2754 struct threads_listing_context *context)
2756 struct thread_item *item;
2758 ptid_t child_ptid = ws->value.related_pid;
2760 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2762 if (ptid_equal (item->ptid, child_ptid))
2764 VEC_ordered_remove (thread_item_t, context->items, i);
2771 remote_newthread_step (threadref *ref, void *data)
2773 struct threads_listing_context *context = data;
2774 struct thread_item item;
2775 int pid = ptid_get_pid (inferior_ptid);
2777 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2781 VEC_safe_push (thread_item_t, context->items, &item);
2783 return 1; /* continue iterator */
2786 #define CRAZY_MAX_THREADS 1000
2789 remote_current_thread (ptid_t oldpid)
2791 struct remote_state *rs = get_remote_state ();
2794 getpkt (&rs->buf, &rs->buf_size, 0);
2795 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2800 result = read_ptid (&rs->buf[2], &obuf);
2801 if (*obuf != '\0' && remote_debug)
2802 fprintf_unfiltered (gdb_stdlog,
2803 "warning: garbage in qC reply\n");
2811 /* List remote threads using the deprecated qL packet. */
2814 remote_get_threads_with_ql (struct target_ops *ops,
2815 struct threads_listing_context *context)
2817 if (remote_threadlist_iterator (remote_newthread_step, context,
2818 CRAZY_MAX_THREADS) >= 0)
2824 #if defined(HAVE_LIBEXPAT)
2827 start_thread (struct gdb_xml_parser *parser,
2828 const struct gdb_xml_element *element,
2829 void *user_data, VEC(gdb_xml_value_s) *attributes)
2831 struct threads_listing_context *data = user_data;
2833 struct thread_item item;
2835 struct gdb_xml_value *attr;
2837 id = xml_find_attribute (attributes, "id")->value;
2838 item.ptid = read_ptid (id, NULL);
2840 attr = xml_find_attribute (attributes, "core");
2842 item.core = *(ULONGEST *) attr->value;
2848 VEC_safe_push (thread_item_t, data->items, &item);
2852 end_thread (struct gdb_xml_parser *parser,
2853 const struct gdb_xml_element *element,
2854 void *user_data, const char *body_text)
2856 struct threads_listing_context *data = user_data;
2858 if (body_text && *body_text)
2859 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2862 const struct gdb_xml_attribute thread_attributes[] = {
2863 { "id", GDB_XML_AF_NONE, NULL, NULL },
2864 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2865 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2868 const struct gdb_xml_element thread_children[] = {
2869 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2872 const struct gdb_xml_element threads_children[] = {
2873 { "thread", thread_attributes, thread_children,
2874 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2875 start_thread, end_thread },
2876 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2879 const struct gdb_xml_element threads_elements[] = {
2880 { "threads", NULL, threads_children,
2881 GDB_XML_EF_NONE, NULL, NULL },
2882 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2887 /* List remote threads using qXfer:threads:read. */
2890 remote_get_threads_with_qxfer (struct target_ops *ops,
2891 struct threads_listing_context *context)
2893 #if defined(HAVE_LIBEXPAT)
2894 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2896 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2897 struct cleanup *back_to = make_cleanup (xfree, xml);
2899 if (xml != NULL && *xml != '\0')
2901 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2902 threads_elements, xml, context);
2905 do_cleanups (back_to);
2913 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2916 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2917 struct threads_listing_context *context)
2919 struct remote_state *rs = get_remote_state ();
2921 if (rs->use_threadinfo_query)
2925 putpkt ("qfThreadInfo");
2926 getpkt (&rs->buf, &rs->buf_size, 0);
2928 if (bufp[0] != '\0') /* q packet recognized */
2930 while (*bufp++ == 'm') /* reply contains one or more TID */
2934 struct thread_item item;
2936 item.ptid = read_ptid (bufp, &bufp);
2940 VEC_safe_push (thread_item_t, context->items, &item);
2942 while (*bufp++ == ','); /* comma-separated list */
2943 putpkt ("qsThreadInfo");
2944 getpkt (&rs->buf, &rs->buf_size, 0);
2951 /* Packet not recognized. */
2952 rs->use_threadinfo_query = 0;
2959 /* Implement the to_update_thread_list function for the remote
2963 remote_update_thread_list (struct target_ops *ops)
2965 struct remote_state *rs = get_remote_state ();
2966 struct threads_listing_context context;
2967 struct cleanup *old_chain;
2970 context.items = NULL;
2971 old_chain = make_cleanup (clear_threads_listing_context, &context);
2973 /* We have a few different mechanisms to fetch the thread list. Try
2974 them all, starting with the most preferred one first, falling
2975 back to older methods. */
2976 if (remote_get_threads_with_qxfer (ops, &context)
2977 || remote_get_threads_with_qthreadinfo (ops, &context)
2978 || remote_get_threads_with_ql (ops, &context))
2981 struct thread_item *item;
2982 struct thread_info *tp, *tmp;
2986 if (VEC_empty (thread_item_t, context.items)
2987 && remote_thread_always_alive (ops, inferior_ptid))
2989 /* Some targets don't really support threads, but still
2990 reply an (empty) thread list in response to the thread
2991 listing packets, instead of replying "packet not
2992 supported". Exit early so we don't delete the main
2994 do_cleanups (old_chain);
2998 /* CONTEXT now holds the current thread list on the remote
2999 target end. Delete GDB-side threads no longer found on the
3001 ALL_THREADS_SAFE (tp, tmp)
3004 VEC_iterate (thread_item_t, context.items, i, item);
3007 if (ptid_equal (item->ptid, tp->ptid))
3011 if (i == VEC_length (thread_item_t, context.items))
3014 delete_thread (tp->ptid);
3018 /* Remove any unreported fork child threads from CONTEXT so
3019 that we don't interfere with follow fork, which is where
3020 creation of such threads is handled. */
3021 remove_new_fork_children (&context);
3023 /* And now add threads we don't know about yet to our list. */
3025 VEC_iterate (thread_item_t, context.items, i, item);
3028 if (!ptid_equal (item->ptid, null_ptid))
3030 struct private_thread_info *info;
3031 /* In non-stop mode, we assume new found threads are
3032 running until proven otherwise with a stop reply. In
3033 all-stop, we can only get here if all threads are
3035 int running = non_stop ? 1 : 0;
3037 remote_notice_new_inferior (item->ptid, running);
3039 info = demand_private_info (item->ptid);
3040 info->core = item->core;
3041 info->extra = item->extra;
3049 /* If no thread listing method is supported, then query whether
3050 each known thread is alive, one by one, with the T packet.
3051 If the target doesn't support threads at all, then this is a
3052 no-op. See remote_thread_alive. */
3056 do_cleanups (old_chain);
3060 * Collect a descriptive string about the given thread.
3061 * The target may say anything it wants to about the thread
3062 * (typically info about its blocked / runnable state, name, etc.).
3063 * This string will appear in the info threads display.
3065 * Optional: targets are not required to implement this function.
3069 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3071 struct remote_state *rs = get_remote_state ();
3075 struct gdb_ext_thread_info threadinfo;
3076 static char display_buf[100]; /* arbitrary... */
3077 int n = 0; /* position in display_buf */
3079 if (rs->remote_desc == 0) /* paranoia */
3080 internal_error (__FILE__, __LINE__,
3081 _("remote_threads_extra_info"));
3083 if (ptid_equal (tp->ptid, magic_null_ptid)
3084 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3085 /* This is the main thread which was added by GDB. The remote
3086 server doesn't know about it. */
3089 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3091 struct thread_info *info = find_thread_ptid (tp->ptid);
3093 if (info && info->priv)
3094 return info->priv->extra;
3099 if (rs->use_threadextra_query)
3102 char *endb = rs->buf + get_remote_packet_size ();
3104 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3106 write_ptid (b, endb, tp->ptid);
3109 getpkt (&rs->buf, &rs->buf_size, 0);
3110 if (rs->buf[0] != 0)
3112 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3113 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3114 display_buf [result] = '\0';
3119 /* If the above query fails, fall back to the old method. */
3120 rs->use_threadextra_query = 0;
3121 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3122 | TAG_MOREDISPLAY | TAG_DISPLAY;
3123 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3124 if (remote_get_threadinfo (&id, set, &threadinfo))
3125 if (threadinfo.active)
3127 if (*threadinfo.shortname)
3128 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3129 " Name: %s,", threadinfo.shortname);
3130 if (*threadinfo.display)
3131 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3132 " State: %s,", threadinfo.display);
3133 if (*threadinfo.more_display)
3134 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3135 " Priority: %s", threadinfo.more_display);
3139 /* For purely cosmetic reasons, clear up trailing commas. */
3140 if (',' == display_buf[n-1])
3141 display_buf[n-1] = ' ';
3150 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3151 struct static_tracepoint_marker *marker)
3153 struct remote_state *rs = get_remote_state ();
3156 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3158 p += hexnumstr (p, addr);
3160 getpkt (&rs->buf, &rs->buf_size, 0);
3164 error (_("Remote failure reply: %s"), p);
3168 parse_static_tracepoint_marker_definition (p, &p, marker);
3175 static VEC(static_tracepoint_marker_p) *
3176 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3179 struct remote_state *rs = get_remote_state ();
3180 VEC(static_tracepoint_marker_p) *markers = NULL;
3181 struct static_tracepoint_marker *marker = NULL;
3182 struct cleanup *old_chain;
3185 /* Ask for a first packet of static tracepoint marker
3188 getpkt (&rs->buf, &rs->buf_size, 0);
3191 error (_("Remote failure reply: %s"), p);
3193 old_chain = make_cleanup (free_current_marker, &marker);
3198 marker = XCNEW (struct static_tracepoint_marker);
3202 parse_static_tracepoint_marker_definition (p, &p, marker);
3204 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3206 VEC_safe_push (static_tracepoint_marker_p,
3212 release_static_tracepoint_marker (marker);
3213 memset (marker, 0, sizeof (*marker));
3216 while (*p++ == ','); /* comma-separated list */
3217 /* Ask for another packet of static tracepoint definition. */
3219 getpkt (&rs->buf, &rs->buf_size, 0);
3223 do_cleanups (old_chain);
3228 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3231 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3233 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3237 /* Restart the remote side; this is an extended protocol operation. */
3240 extended_remote_restart (void)
3242 struct remote_state *rs = get_remote_state ();
3244 /* Send the restart command; for reasons I don't understand the
3245 remote side really expects a number after the "R". */
3246 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3249 remote_fileio_reset ();
3252 /* Clean up connection to a remote debugger. */
3255 remote_close (struct target_ops *self)
3257 struct remote_state *rs = get_remote_state ();
3259 if (rs->remote_desc == NULL)
3260 return; /* already closed */
3262 /* Make sure we leave stdin registered in the event loop, and we
3263 don't leave the async SIGINT signal handler installed. */
3264 remote_terminal_ours (self);
3266 serial_close (rs->remote_desc);
3267 rs->remote_desc = NULL;
3269 /* We don't have a connection to the remote stub anymore. Get rid
3270 of all the inferiors and their threads we were controlling.
3271 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3272 will be unable to find the thread corresponding to (pid, 0, 0). */
3273 inferior_ptid = null_ptid;
3274 discard_all_inferiors ();
3276 /* We are closing the remote target, so we should discard
3277 everything of this target. */
3278 discard_pending_stop_replies_in_queue (rs);
3280 if (remote_async_inferior_event_token)
3281 delete_async_event_handler (&remote_async_inferior_event_token);
3283 remote_notif_state_xfree (rs->notif_state);
3285 trace_reset_local_state ();
3288 /* Query the remote side for the text, data and bss offsets. */
3293 struct remote_state *rs = get_remote_state ();
3296 int lose, num_segments = 0, do_sections, do_segments;
3297 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3298 struct section_offsets *offs;
3299 struct symfile_segment_data *data;
3301 if (symfile_objfile == NULL)
3304 putpkt ("qOffsets");
3305 getpkt (&rs->buf, &rs->buf_size, 0);
3308 if (buf[0] == '\000')
3309 return; /* Return silently. Stub doesn't support
3313 warning (_("Remote failure reply: %s"), buf);
3317 /* Pick up each field in turn. This used to be done with scanf, but
3318 scanf will make trouble if CORE_ADDR size doesn't match
3319 conversion directives correctly. The following code will work
3320 with any size of CORE_ADDR. */
3321 text_addr = data_addr = bss_addr = 0;
3325 if (startswith (ptr, "Text="))
3328 /* Don't use strtol, could lose on big values. */
3329 while (*ptr && *ptr != ';')
3330 text_addr = (text_addr << 4) + fromhex (*ptr++);
3332 if (startswith (ptr, ";Data="))
3335 while (*ptr && *ptr != ';')
3336 data_addr = (data_addr << 4) + fromhex (*ptr++);
3341 if (!lose && startswith (ptr, ";Bss="))
3344 while (*ptr && *ptr != ';')
3345 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3347 if (bss_addr != data_addr)
3348 warning (_("Target reported unsupported offsets: %s"), buf);
3353 else if (startswith (ptr, "TextSeg="))
3356 /* Don't use strtol, could lose on big values. */
3357 while (*ptr && *ptr != ';')
3358 text_addr = (text_addr << 4) + fromhex (*ptr++);
3361 if (startswith (ptr, ";DataSeg="))
3364 while (*ptr && *ptr != ';')
3365 data_addr = (data_addr << 4) + fromhex (*ptr++);
3373 error (_("Malformed response to offset query, %s"), buf);
3374 else if (*ptr != '\0')
3375 warning (_("Target reported unsupported offsets: %s"), buf);
3377 offs = ((struct section_offsets *)
3378 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3379 memcpy (offs, symfile_objfile->section_offsets,
3380 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3382 data = get_symfile_segment_data (symfile_objfile->obfd);
3383 do_segments = (data != NULL);
3384 do_sections = num_segments == 0;
3386 if (num_segments > 0)
3388 segments[0] = text_addr;
3389 segments[1] = data_addr;
3391 /* If we have two segments, we can still try to relocate everything
3392 by assuming that the .text and .data offsets apply to the whole
3393 text and data segments. Convert the offsets given in the packet
3394 to base addresses for symfile_map_offsets_to_segments. */
3395 else if (data && data->num_segments == 2)
3397 segments[0] = data->segment_bases[0] + text_addr;
3398 segments[1] = data->segment_bases[1] + data_addr;
3401 /* If the object file has only one segment, assume that it is text
3402 rather than data; main programs with no writable data are rare,
3403 but programs with no code are useless. Of course the code might
3404 have ended up in the data segment... to detect that we would need
3405 the permissions here. */
3406 else if (data && data->num_segments == 1)
3408 segments[0] = data->segment_bases[0] + text_addr;
3411 /* There's no way to relocate by segment. */
3417 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3418 offs, num_segments, segments);
3420 if (ret == 0 && !do_sections)
3421 error (_("Can not handle qOffsets TextSeg "
3422 "response with this symbol file"));
3429 free_symfile_segment_data (data);
3433 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3435 /* This is a temporary kludge to force data and bss to use the
3436 same offsets because that's what nlmconv does now. The real
3437 solution requires changes to the stub and remote.c that I
3438 don't have time to do right now. */
3440 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3441 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3444 objfile_relocate (symfile_objfile, offs);
3447 /* Send interrupt_sequence to remote target. */
3449 send_interrupt_sequence (void)
3451 struct remote_state *rs = get_remote_state ();
3453 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3454 remote_serial_write ("\x03", 1);
3455 else if (interrupt_sequence_mode == interrupt_sequence_break)
3456 serial_send_break (rs->remote_desc);
3457 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3459 serial_send_break (rs->remote_desc);
3460 remote_serial_write ("g", 1);
3463 internal_error (__FILE__, __LINE__,
3464 _("Invalid value for interrupt_sequence_mode: %s."),
3465 interrupt_sequence_mode);
3469 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3470 and extract the PTID. Returns NULL_PTID if not found. */
3473 stop_reply_extract_thread (char *stop_reply)
3475 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3479 /* Txx r:val ; r:val (...) */
3482 /* Look for "register" named "thread". */
3487 p1 = strchr (p, ':');
3491 if (strncmp (p, "thread", p1 - p) == 0)
3492 return read_ptid (++p1, &p);
3494 p1 = strchr (p, ';');
3506 /* Determine the remote side's current thread. If we have a stop
3507 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3508 "thread" register we can extract the current thread from. If not,
3509 ask the remote which is the current thread with qC. The former
3510 method avoids a roundtrip. */
3513 get_current_thread (char *wait_status)
3515 ptid_t ptid = null_ptid;
3517 /* Note we don't use remote_parse_stop_reply as that makes use of
3518 the target architecture, which we haven't yet fully determined at
3520 if (wait_status != NULL)
3521 ptid = stop_reply_extract_thread (wait_status);
3522 if (ptid_equal (ptid, null_ptid))
3523 ptid = remote_current_thread (inferior_ptid);
3528 /* Query the remote target for which is the current thread/process,
3529 add it to our tables, and update INFERIOR_PTID. The caller is
3530 responsible for setting the state such that the remote end is ready
3531 to return the current thread.
3533 This function is called after handling the '?' or 'vRun' packets,
3534 whose response is a stop reply from which we can also try
3535 extracting the thread. If the target doesn't support the explicit
3536 qC query, we infer the current thread from that stop reply, passed
3537 in in WAIT_STATUS, which may be NULL. */
3540 add_current_inferior_and_thread (char *wait_status)
3542 struct remote_state *rs = get_remote_state ();
3546 inferior_ptid = null_ptid;
3548 /* Now, if we have thread information, update inferior_ptid. */
3549 ptid = get_current_thread (wait_status);
3551 if (!ptid_equal (ptid, null_ptid))
3553 if (!remote_multi_process_p (rs))
3556 inferior_ptid = ptid;
3560 /* Without this, some commands which require an active target
3561 (such as kill) won't work. This variable serves (at least)
3562 double duty as both the pid of the target process (if it has
3563 such), and as a flag indicating that a target is active. */
3564 inferior_ptid = magic_null_ptid;
3568 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3570 /* Add the main thread. */
3571 add_thread_silent (inferior_ptid);
3574 /* Process all initial stop replies the remote side sent in response
3575 to the ? packet. These indicate threads that were already stopped
3576 on initial connection. We mark these threads as stopped and print
3577 their current frame before giving the user the prompt. */
3580 process_initial_stop_replies (void)
3582 int pending_stop_replies = stop_reply_queue_length ();
3584 /* Consume the initial pending events. */
3585 while (pending_stop_replies-- > 0)
3587 ptid_t waiton_ptid = minus_one_ptid;
3589 struct target_waitstatus ws;
3590 int ignore_event = 0;
3592 memset (&ws, 0, sizeof (ws));
3593 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3595 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3599 case TARGET_WAITKIND_IGNORE:
3600 case TARGET_WAITKIND_NO_RESUMED:
3601 case TARGET_WAITKIND_SIGNALLED:
3602 case TARGET_WAITKIND_EXITED:
3603 /* We shouldn't see these, but if we do, just ignore. */
3605 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3609 case TARGET_WAITKIND_EXECD:
3610 xfree (ws.value.execd_pathname);
3619 switch_to_thread (event_ptid);
3620 set_executing (event_ptid, 0);
3621 set_running (event_ptid, 0);
3623 stop_pc = get_frame_pc (get_current_frame ());
3624 set_current_sal_from_frame (get_current_frame ());
3626 if (ws.kind == TARGET_WAITKIND_STOPPED)
3628 enum gdb_signal sig = ws.value.sig;
3630 /* Stubs traditionally report SIGTRAP as initial signal,
3631 instead of signal 0. Suppress it. */
3632 if (sig == GDB_SIGNAL_TRAP)
3634 inferior_thread ()->suspend.stop_signal = sig;
3636 if (signal_print_state (sig))
3637 observer_notify_signal_received (sig);
3640 print_stop_event (&ws);
3641 observer_notify_normal_stop (NULL, 1);
3646 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3648 struct remote_state *rs = get_remote_state ();
3649 struct packet_config *noack_config;
3650 char *wait_status = NULL;
3652 immediate_quit++; /* Allow user to interrupt it. */
3655 if (interrupt_on_connect)
3656 send_interrupt_sequence ();
3658 /* Ack any packet which the remote side has already sent. */
3659 serial_write (rs->remote_desc, "+", 1);
3661 /* Signal other parts that we're going through the initial setup,
3662 and so things may not be stable yet. */
3663 rs->starting_up = 1;
3665 /* The first packet we send to the target is the optional "supported
3666 packets" request. If the target can answer this, it will tell us
3667 which later probes to skip. */
3668 remote_query_supported ();
3670 /* If the stub wants to get a QAllow, compose one and send it. */
3671 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3672 remote_set_permissions (target);
3674 /* Next, we possibly activate noack mode.
3676 If the QStartNoAckMode packet configuration is set to AUTO,
3677 enable noack mode if the stub reported a wish for it with
3680 If set to TRUE, then enable noack mode even if the stub didn't
3681 report it in qSupported. If the stub doesn't reply OK, the
3682 session ends with an error.
3684 If FALSE, then don't activate noack mode, regardless of what the
3685 stub claimed should be the default with qSupported. */
3687 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3688 if (packet_config_support (noack_config) != PACKET_DISABLE)
3690 putpkt ("QStartNoAckMode");
3691 getpkt (&rs->buf, &rs->buf_size, 0);
3692 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3698 /* Tell the remote that we are using the extended protocol. */
3700 getpkt (&rs->buf, &rs->buf_size, 0);
3703 /* Let the target know which signals it is allowed to pass down to
3705 update_signals_program_target ();
3707 /* Next, if the target can specify a description, read it. We do
3708 this before anything involving memory or registers. */
3709 target_find_description ();
3711 /* Next, now that we know something about the target, update the
3712 address spaces in the program spaces. */
3713 update_address_spaces ();
3715 /* On OSs where the list of libraries is global to all
3716 processes, we fetch them early. */
3717 if (gdbarch_has_global_solist (target_gdbarch ()))
3718 solib_add (NULL, from_tty, target, auto_solib_add);
3722 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3723 error (_("Non-stop mode requested, but remote "
3724 "does not support non-stop"));
3726 putpkt ("QNonStop:1");
3727 getpkt (&rs->buf, &rs->buf_size, 0);
3729 if (strcmp (rs->buf, "OK") != 0)
3730 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3732 /* Find about threads and processes the stub is already
3733 controlling. We default to adding them in the running state.
3734 The '?' query below will then tell us about which threads are
3736 remote_update_thread_list (target);
3738 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3740 /* Don't assume that the stub can operate in all-stop mode.
3741 Request it explicitly. */
3742 putpkt ("QNonStop:0");
3743 getpkt (&rs->buf, &rs->buf_size, 0);
3745 if (strcmp (rs->buf, "OK") != 0)
3746 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3749 /* Upload TSVs regardless of whether the target is running or not. The
3750 remote stub, such as GDBserver, may have some predefined or builtin
3751 TSVs, even if the target is not running. */
3752 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3754 struct uploaded_tsv *uploaded_tsvs = NULL;
3756 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3757 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3760 /* Check whether the target is running now. */
3762 getpkt (&rs->buf, &rs->buf_size, 0);
3768 struct inferior *inf;
3770 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3773 error (_("The target is not running (try extended-remote?)"));
3775 /* We're connected, but not running. Drop out before we
3776 call start_remote. */
3777 rs->starting_up = 0;
3782 /* Save the reply for later. */
3783 wait_status = alloca (strlen (rs->buf) + 1);
3784 strcpy (wait_status, rs->buf);
3787 /* Fetch thread list. */
3788 target_update_thread_list ();
3790 /* Let the stub know that we want it to return the thread. */
3791 set_continue_thread (minus_one_ptid);
3793 if (thread_count () == 0)
3795 /* Target has no concept of threads at all. GDB treats
3796 non-threaded target as single-threaded; add a main
3798 add_current_inferior_and_thread (wait_status);
3802 /* We have thread information; select the thread the target
3803 says should be current. If we're reconnecting to a
3804 multi-threaded program, this will ideally be the thread
3805 that last reported an event before GDB disconnected. */
3806 inferior_ptid = get_current_thread (wait_status);
3807 if (ptid_equal (inferior_ptid, null_ptid))
3809 /* Odd... The target was able to list threads, but not
3810 tell us which thread was current (no "thread"
3811 register in T stop reply?). Just pick the first
3812 thread in the thread list then. */
3815 fprintf_unfiltered (gdb_stdlog,
3816 "warning: couldn't determine remote "
3817 "current thread; picking first in list.\n");
3819 inferior_ptid = thread_list->ptid;
3823 /* init_wait_for_inferior should be called before get_offsets in order
3824 to manage `inserted' flag in bp loc in a correct state.
3825 breakpoint_init_inferior, called from init_wait_for_inferior, set
3826 `inserted' flag to 0, while before breakpoint_re_set, called from
3827 start_remote, set `inserted' flag to 1. In the initialization of
3828 inferior, breakpoint_init_inferior should be called first, and then
3829 breakpoint_re_set can be called. If this order is broken, state of
3830 `inserted' flag is wrong, and cause some problems on breakpoint
3832 init_wait_for_inferior ();
3834 get_offsets (); /* Get text, data & bss offsets. */
3836 /* If we could not find a description using qXfer, and we know
3837 how to do it some other way, try again. This is not
3838 supported for non-stop; it could be, but it is tricky if
3839 there are no stopped threads when we connect. */
3840 if (remote_read_description_p (target)
3841 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3843 target_clear_description ();
3844 target_find_description ();
3847 /* Use the previously fetched status. */
3848 gdb_assert (wait_status != NULL);
3849 strcpy (rs->buf, wait_status);
3850 rs->cached_wait_status = 1;
3853 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3857 ptid_t current_ptid;
3859 /* Clear WFI global state. Do this before finding about new
3860 threads and inferiors, and setting the current inferior.
3861 Otherwise we would clear the proceed status of the current
3862 inferior when we want its stop_soon state to be preserved
3863 (see notice_new_inferior). */
3864 init_wait_for_inferior ();
3866 /* In non-stop, we will either get an "OK", meaning that there
3867 are no stopped threads at this time; or, a regular stop
3868 reply. In the latter case, there may be more than one thread
3869 stopped --- we pull them all out using the vStopped
3871 if (strcmp (rs->buf, "OK") != 0)
3873 struct notif_client *notif = ¬if_client_stop;
3875 /* remote_notif_get_pending_replies acks this one, and gets
3877 rs->notif_state->pending_event[notif_client_stop.id]
3878 = remote_notif_parse (notif, rs->buf);
3879 remote_notif_get_pending_events (notif);
3882 if (thread_count () == 0)
3885 error (_("The target is not running (try extended-remote?)"));
3887 /* We're connected, but not running. Drop out before we
3888 call start_remote. */
3889 rs->starting_up = 0;
3893 /* Let the stub know that we want it to return the thread. */
3895 /* Force the stub to choose a thread. */
3896 set_general_thread (null_ptid);
3899 current_ptid = remote_current_thread (minus_one_ptid);
3900 if (ptid_equal (inferior_ptid, minus_one_ptid))
3901 error (_("remote didn't report the current thread in non-stop mode"));
3903 inferior_ptid = current_ptid;
3904 get_offsets (); /* Get text, data & bss offsets. */
3906 /* In non-stop mode, any cached wait status will be stored in
3907 the stop reply queue. */
3908 gdb_assert (wait_status == NULL);
3910 /* Report all signals during attach/startup. */
3911 remote_pass_signals (target, 0, NULL);
3913 /* If there are already stopped threads, mark them stopped and
3914 report their stops before giving the prompt to the user. */
3915 process_initial_stop_replies ();
3917 switch_to_thread (current_ptid);
3919 if (target_can_async_p ())
3923 /* If we connected to a live target, do some additional setup. */
3924 if (target_has_execution)
3926 if (symfile_objfile) /* No use without a symbol-file. */
3927 remote_check_symbols ();
3930 /* Possibly the target has been engaged in a trace run started
3931 previously; find out where things are at. */
3932 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3934 struct uploaded_tp *uploaded_tps = NULL;
3936 if (current_trace_status ()->running)
3937 printf_filtered (_("Trace is already running on the target.\n"));
3939 remote_upload_tracepoints (target, &uploaded_tps);
3941 merge_uploaded_tracepoints (&uploaded_tps);
3944 /* The thread and inferior lists are now synchronized with the
3945 target, our symbols have been relocated, and we're merged the
3946 target's tracepoints with ours. We're done with basic start
3948 rs->starting_up = 0;
3950 /* Maybe breakpoints are global and need to be inserted now. */
3951 if (breakpoints_should_be_inserted_now ())
3952 insert_breakpoints ();
3955 /* Open a connection to a remote debugger.
3956 NAME is the filename used for communication. */
3959 remote_open (const char *name, int from_tty)
3961 remote_open_1 (name, from_tty, &remote_ops, 0);
3964 /* Open a connection to a remote debugger using the extended
3965 remote gdb protocol. NAME is the filename used for communication. */
3968 extended_remote_open (const char *name, int from_tty)
3970 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3973 /* Reset all packets back to "unknown support". Called when opening a
3974 new connection to a remote target. */
3977 reset_all_packet_configs_support (void)
3981 for (i = 0; i < PACKET_MAX; i++)
3982 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3985 /* Initialize all packet configs. */
3988 init_all_packet_configs (void)
3992 for (i = 0; i < PACKET_MAX; i++)
3994 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3995 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3999 /* Symbol look-up. */
4002 remote_check_symbols (void)
4004 struct remote_state *rs = get_remote_state ();
4005 char *msg, *reply, *tmp;
4006 struct bound_minimal_symbol sym;
4008 struct cleanup *old_chain;
4010 /* The remote side has no concept of inferiors that aren't running
4011 yet, it only knows about running processes. If we're connected
4012 but our current inferior is not running, we should not invite the
4013 remote target to request symbol lookups related to its
4014 (unrelated) current process. */
4015 if (!target_has_execution)
4018 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4021 /* Make sure the remote is pointing at the right process. Note
4022 there's no way to select "no process". */
4023 set_general_process ();
4025 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4026 because we need both at the same time. */
4027 msg = xmalloc (get_remote_packet_size ());
4028 old_chain = make_cleanup (xfree, msg);
4030 /* Invite target to request symbol lookups. */
4032 putpkt ("qSymbol::");
4033 getpkt (&rs->buf, &rs->buf_size, 0);
4034 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4037 while (startswith (reply, "qSymbol:"))
4039 struct bound_minimal_symbol sym;
4042 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4044 sym = lookup_minimal_symbol (msg, NULL, NULL);
4045 if (sym.minsym == NULL)
4046 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4049 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4050 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4052 /* If this is a function address, return the start of code
4053 instead of any data function descriptor. */
4054 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4058 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4059 phex_nz (sym_addr, addr_size), &reply[8]);
4063 getpkt (&rs->buf, &rs->buf_size, 0);
4067 do_cleanups (old_chain);
4070 static struct serial *
4071 remote_serial_open (const char *name)
4073 static int udp_warning = 0;
4075 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4076 of in ser-tcp.c, because it is the remote protocol assuming that the
4077 serial connection is reliable and not the serial connection promising
4079 if (!udp_warning && startswith (name, "udp:"))
4081 warning (_("The remote protocol may be unreliable over UDP.\n"
4082 "Some events may be lost, rendering further debugging "
4087 return serial_open (name);
4090 /* Inform the target of our permission settings. The permission flags
4091 work without this, but if the target knows the settings, it can do
4092 a couple things. First, it can add its own check, to catch cases
4093 that somehow manage to get by the permissions checks in target
4094 methods. Second, if the target is wired to disallow particular
4095 settings (for instance, a system in the field that is not set up to
4096 be able to stop at a breakpoint), it can object to any unavailable
4100 remote_set_permissions (struct target_ops *self)
4102 struct remote_state *rs = get_remote_state ();
4104 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4105 "WriteReg:%x;WriteMem:%x;"
4106 "InsertBreak:%x;InsertTrace:%x;"
4107 "InsertFastTrace:%x;Stop:%x",
4108 may_write_registers, may_write_memory,
4109 may_insert_breakpoints, may_insert_tracepoints,
4110 may_insert_fast_tracepoints, may_stop);
4112 getpkt (&rs->buf, &rs->buf_size, 0);
4114 /* If the target didn't like the packet, warn the user. Do not try
4115 to undo the user's settings, that would just be maddening. */
4116 if (strcmp (rs->buf, "OK") != 0)
4117 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4120 /* This type describes each known response to the qSupported
4122 struct protocol_feature
4124 /* The name of this protocol feature. */
4127 /* The default for this protocol feature. */
4128 enum packet_support default_support;
4130 /* The function to call when this feature is reported, or after
4131 qSupported processing if the feature is not supported.
4132 The first argument points to this structure. The second
4133 argument indicates whether the packet requested support be
4134 enabled, disabled, or probed (or the default, if this function
4135 is being called at the end of processing and this feature was
4136 not reported). The third argument may be NULL; if not NULL, it
4137 is a NUL-terminated string taken from the packet following
4138 this feature's name and an equals sign. */
4139 void (*func) (const struct protocol_feature *, enum packet_support,
4142 /* The corresponding packet for this feature. Only used if
4143 FUNC is remote_supported_packet. */
4148 remote_supported_packet (const struct protocol_feature *feature,
4149 enum packet_support support,
4150 const char *argument)
4154 warning (_("Remote qSupported response supplied an unexpected value for"
4155 " \"%s\"."), feature->name);
4159 remote_protocol_packets[feature->packet].support = support;
4163 remote_packet_size (const struct protocol_feature *feature,
4164 enum packet_support support, const char *value)
4166 struct remote_state *rs = get_remote_state ();
4171 if (support != PACKET_ENABLE)
4174 if (value == NULL || *value == '\0')
4176 warning (_("Remote target reported \"%s\" without a size."),
4182 packet_size = strtol (value, &value_end, 16);
4183 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4185 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4186 feature->name, value);
4190 /* Record the new maximum packet size. */
4191 rs->explicit_packet_size = packet_size;
4194 static const struct protocol_feature remote_protocol_features[] = {
4195 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4196 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4197 PACKET_qXfer_auxv },
4198 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4199 PACKET_qXfer_exec_file },
4200 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4201 PACKET_qXfer_features },
4202 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4203 PACKET_qXfer_libraries },
4204 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4205 PACKET_qXfer_libraries_svr4 },
4206 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4207 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4208 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4209 PACKET_qXfer_memory_map },
4210 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4211 PACKET_qXfer_spu_read },
4212 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4213 PACKET_qXfer_spu_write },
4214 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4215 PACKET_qXfer_osdata },
4216 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4217 PACKET_qXfer_threads },
4218 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4219 PACKET_qXfer_traceframe_info },
4220 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4221 PACKET_QPassSignals },
4222 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4223 PACKET_QProgramSignals },
4224 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4225 PACKET_QStartNoAckMode },
4226 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4227 PACKET_multiprocess_feature },
4228 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4229 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4230 PACKET_qXfer_siginfo_read },
4231 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4232 PACKET_qXfer_siginfo_write },
4233 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4234 PACKET_ConditionalTracepoints },
4235 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4236 PACKET_ConditionalBreakpoints },
4237 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4238 PACKET_BreakpointCommands },
4239 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4240 PACKET_FastTracepoints },
4241 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4242 PACKET_StaticTracepoints },
4243 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4244 PACKET_InstallInTrace},
4245 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4246 PACKET_DisconnectedTracing_feature },
4247 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4249 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4251 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4252 PACKET_TracepointSource },
4253 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4255 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4256 PACKET_EnableDisableTracepoints_feature },
4257 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4258 PACKET_qXfer_fdpic },
4259 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4261 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4262 PACKET_QDisableRandomization },
4263 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4264 { "QTBuffer:size", PACKET_DISABLE,
4265 remote_supported_packet, PACKET_QTBuffer_size},
4266 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4267 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4268 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4269 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4270 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4271 PACKET_qXfer_btrace },
4272 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4273 PACKET_qXfer_btrace_conf },
4274 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4275 PACKET_Qbtrace_conf_bts_size },
4276 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4277 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4278 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4279 PACKET_fork_event_feature },
4280 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4281 PACKET_vfork_event_feature },
4282 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4283 PACKET_Qbtrace_conf_pt_size }
4286 static char *remote_support_xml;
4288 /* Register string appended to "xmlRegisters=" in qSupported query. */
4291 register_remote_support_xml (const char *xml)
4293 #if defined(HAVE_LIBEXPAT)
4294 if (remote_support_xml == NULL)
4295 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4298 char *copy = xstrdup (remote_support_xml + 13);
4299 char *p = strtok (copy, ",");
4303 if (strcmp (p, xml) == 0)
4310 while ((p = strtok (NULL, ",")) != NULL);
4313 remote_support_xml = reconcat (remote_support_xml,
4314 remote_support_xml, ",", xml,
4321 remote_query_supported_append (char *msg, const char *append)
4324 return reconcat (msg, msg, ";", append, (char *) NULL);
4326 return xstrdup (append);
4330 remote_query_supported (void)
4332 struct remote_state *rs = get_remote_state ();
4335 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4337 /* The packet support flags are handled differently for this packet
4338 than for most others. We treat an error, a disabled packet, and
4339 an empty response identically: any features which must be reported
4340 to be used will be automatically disabled. An empty buffer
4341 accomplishes this, since that is also the representation for a list
4342 containing no features. */
4345 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4348 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4350 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4351 q = remote_query_supported_append (q, "multiprocess+");
4353 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4354 q = remote_query_supported_append (q, "swbreak+");
4355 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4356 q = remote_query_supported_append (q, "hwbreak+");
4358 if (remote_support_xml)
4359 q = remote_query_supported_append (q, remote_support_xml);
4361 q = remote_query_supported_append (q, "qRelocInsn+");
4365 if (packet_set_cmd_state (PACKET_fork_event_feature)
4366 != AUTO_BOOLEAN_FALSE)
4367 q = remote_query_supported_append (q, "fork-events+");
4368 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4369 != AUTO_BOOLEAN_FALSE)
4370 q = remote_query_supported_append (q, "vfork-events+");
4373 q = reconcat (q, "qSupported:", q, (char *) NULL);
4376 do_cleanups (old_chain);
4378 getpkt (&rs->buf, &rs->buf_size, 0);
4380 /* If an error occured, warn, but do not return - just reset the
4381 buffer to empty and go on to disable features. */
4382 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4385 warning (_("Remote failure reply: %s"), rs->buf);
4390 memset (seen, 0, sizeof (seen));
4395 enum packet_support is_supported;
4396 char *p, *end, *name_end, *value;
4398 /* First separate out this item from the rest of the packet. If
4399 there's another item after this, we overwrite the separator
4400 (terminated strings are much easier to work with). */
4402 end = strchr (p, ';');
4405 end = p + strlen (p);
4415 warning (_("empty item in \"qSupported\" response"));
4420 name_end = strchr (p, '=');
4423 /* This is a name=value entry. */
4424 is_supported = PACKET_ENABLE;
4425 value = name_end + 1;
4434 is_supported = PACKET_ENABLE;
4438 is_supported = PACKET_DISABLE;
4442 is_supported = PACKET_SUPPORT_UNKNOWN;
4446 warning (_("unrecognized item \"%s\" "
4447 "in \"qSupported\" response"), p);
4453 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4454 if (strcmp (remote_protocol_features[i].name, p) == 0)
4456 const struct protocol_feature *feature;
4459 feature = &remote_protocol_features[i];
4460 feature->func (feature, is_supported, value);
4465 /* If we increased the packet size, make sure to increase the global
4466 buffer size also. We delay this until after parsing the entire
4467 qSupported packet, because this is the same buffer we were
4469 if (rs->buf_size < rs->explicit_packet_size)
4471 rs->buf_size = rs->explicit_packet_size;
4472 rs->buf = xrealloc (rs->buf, rs->buf_size);
4475 /* Handle the defaults for unmentioned features. */
4476 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4479 const struct protocol_feature *feature;
4481 feature = &remote_protocol_features[i];
4482 feature->func (feature, feature->default_support, NULL);
4486 /* Remove any of the remote.c targets from target stack. Upper targets depend
4487 on it so remove them first. */
4490 remote_unpush_target (void)
4492 pop_all_targets_above (process_stratum - 1);
4496 remote_open_1 (const char *name, int from_tty,
4497 struct target_ops *target, int extended_p)
4499 struct remote_state *rs = get_remote_state ();
4502 error (_("To open a remote debug connection, you need to specify what\n"
4503 "serial device is attached to the remote system\n"
4504 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4506 /* See FIXME above. */
4507 if (!target_async_permitted)
4508 wait_forever_enabled_p = 1;
4510 /* If we're connected to a running target, target_preopen will kill it.
4511 Ask this question first, before target_preopen has a chance to kill
4513 if (rs->remote_desc != NULL && !have_inferiors ())
4516 && !query (_("Already connected to a remote target. Disconnect? ")))
4517 error (_("Still connected."));
4520 /* Here the possibly existing remote target gets unpushed. */
4521 target_preopen (from_tty);
4523 /* Make sure we send the passed signals list the next time we resume. */
4524 xfree (rs->last_pass_packet);
4525 rs->last_pass_packet = NULL;
4527 /* Make sure we send the program signals list the next time we
4529 xfree (rs->last_program_signals_packet);
4530 rs->last_program_signals_packet = NULL;
4532 remote_fileio_reset ();
4533 reopen_exec_file ();
4536 rs->remote_desc = remote_serial_open (name);
4537 if (!rs->remote_desc)
4538 perror_with_name (name);
4540 if (baud_rate != -1)
4542 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4544 /* The requested speed could not be set. Error out to
4545 top level after closing remote_desc. Take care to
4546 set remote_desc to NULL to avoid closing remote_desc
4548 serial_close (rs->remote_desc);
4549 rs->remote_desc = NULL;
4550 perror_with_name (name);
4554 serial_setparity (rs->remote_desc, serial_parity);
4555 serial_raw (rs->remote_desc);
4557 /* If there is something sitting in the buffer we might take it as a
4558 response to a command, which would be bad. */
4559 serial_flush_input (rs->remote_desc);
4563 puts_filtered ("Remote debugging using ");
4564 puts_filtered (name);
4565 puts_filtered ("\n");
4567 push_target (target); /* Switch to using remote target now. */
4569 /* Register extra event sources in the event loop. */
4570 remote_async_inferior_event_token
4571 = create_async_event_handler (remote_async_inferior_event_handler,
4573 rs->notif_state = remote_notif_state_allocate ();
4575 /* Reset the target state; these things will be queried either by
4576 remote_query_supported or as they are needed. */
4577 reset_all_packet_configs_support ();
4578 rs->cached_wait_status = 0;
4579 rs->explicit_packet_size = 0;
4581 rs->extended = extended_p;
4582 rs->waiting_for_stop_reply = 0;
4583 rs->ctrlc_pending_p = 0;
4585 rs->general_thread = not_sent_ptid;
4586 rs->continue_thread = not_sent_ptid;
4587 rs->remote_traceframe_number = -1;
4589 /* Probe for ability to use "ThreadInfo" query, as required. */
4590 rs->use_threadinfo_query = 1;
4591 rs->use_threadextra_query = 1;
4593 readahead_cache_invalidate ();
4595 if (target_async_permitted)
4597 /* With this target we start out by owning the terminal. */
4598 remote_async_terminal_ours_p = 1;
4600 /* FIXME: cagney/1999-09-23: During the initial connection it is
4601 assumed that the target is already ready and able to respond to
4602 requests. Unfortunately remote_start_remote() eventually calls
4603 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4604 around this. Eventually a mechanism that allows
4605 wait_for_inferior() to expect/get timeouts will be
4607 wait_forever_enabled_p = 0;
4610 /* First delete any symbols previously loaded from shared libraries. */
4611 no_shared_libraries (NULL, 0);
4614 init_thread_list ();
4616 /* Start the remote connection. If error() or QUIT, discard this
4617 target (we'd otherwise be in an inconsistent state) and then
4618 propogate the error on up the exception chain. This ensures that
4619 the caller doesn't stumble along blindly assuming that the
4620 function succeeded. The CLI doesn't have this problem but other
4621 UI's, such as MI do.
4623 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4624 this function should return an error indication letting the
4625 caller restore the previous state. Unfortunately the command
4626 ``target remote'' is directly wired to this function making that
4627 impossible. On a positive note, the CLI side of this problem has
4628 been fixed - the function set_cmd_context() makes it possible for
4629 all the ``target ....'' commands to share a common callback
4630 function. See cli-dump.c. */
4635 remote_start_remote (from_tty, target, extended_p);
4637 CATCH (ex, RETURN_MASK_ALL)
4639 /* Pop the partially set up target - unless something else did
4640 already before throwing the exception. */
4641 if (rs->remote_desc != NULL)
4642 remote_unpush_target ();
4643 if (target_async_permitted)
4644 wait_forever_enabled_p = 1;
4645 throw_exception (ex);
4650 remote_btrace_reset ();
4652 if (target_async_permitted)
4653 wait_forever_enabled_p = 1;
4656 /* Detach the specified process. */
4659 remote_detach_pid (int pid)
4661 struct remote_state *rs = get_remote_state ();
4663 if (remote_multi_process_p (rs))
4664 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4666 strcpy (rs->buf, "D");
4669 getpkt (&rs->buf, &rs->buf_size, 0);
4671 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4673 else if (rs->buf[0] == '\0')
4674 error (_("Remote doesn't know how to detach"));
4676 error (_("Can't detach process."));
4679 /* This detaches a program to which we previously attached, using
4680 inferior_ptid to identify the process. After this is done, GDB
4681 can be used to debug some other program. We better not have left
4682 any breakpoints in the target program or it'll die when it hits
4686 remote_detach_1 (const char *args, int from_tty)
4688 int pid = ptid_get_pid (inferior_ptid);
4689 struct remote_state *rs = get_remote_state ();
4690 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4694 error (_("Argument given to \"detach\" when remotely debugging."));
4696 if (!target_has_execution)
4697 error (_("No process to detach from."));
4701 char *exec_file = get_exec_file (0);
4702 if (exec_file == NULL)
4704 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4705 target_pid_to_str (pid_to_ptid (pid)));
4706 gdb_flush (gdb_stdout);
4709 /* Tell the remote target to detach. */
4710 remote_detach_pid (pid);
4712 if (from_tty && !rs->extended)
4713 puts_filtered (_("Ending remote debugging.\n"));
4715 /* Check to see if we are detaching a fork parent. Note that if we
4716 are detaching a fork child, tp == NULL. */
4717 is_fork_parent = (tp != NULL
4718 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4720 /* If doing detach-on-fork, we don't mourn, because that will delete
4721 breakpoints that should be available for the followed inferior. */
4722 if (!is_fork_parent)
4723 target_mourn_inferior ();
4726 inferior_ptid = null_ptid;
4727 detach_inferior (pid);
4732 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4734 remote_detach_1 (args, from_tty);
4738 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4740 remote_detach_1 (args, from_tty);
4743 /* Target follow-fork function for remote targets. On entry, and
4744 at return, the current inferior is the fork parent.
4746 Note that although this is currently only used for extended-remote,
4747 it is named remote_follow_fork in anticipation of using it for the
4748 remote target as well. */
4751 remote_follow_fork (struct target_ops *ops, int follow_child,
4754 struct remote_state *rs = get_remote_state ();
4755 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
4757 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4758 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
4760 /* When following the parent and detaching the child, we detach
4761 the child here. For the case of following the child and
4762 detaching the parent, the detach is done in the target-
4763 independent follow fork code in infrun.c. We can't use
4764 target_detach when detaching an unfollowed child because
4765 the client side doesn't know anything about the child. */
4766 if (detach_fork && !follow_child)
4768 /* Detach the fork child. */
4772 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4773 child_pid = ptid_get_pid (child_ptid);
4775 remote_detach_pid (child_pid);
4776 detach_inferior (child_pid);
4782 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4785 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4788 error (_("Argument given to \"disconnect\" when remotely debugging."));
4790 /* Make sure we unpush even the extended remote targets; mourn
4791 won't do it. So call remote_mourn directly instead of
4792 target_mourn_inferior. */
4793 remote_mourn (target);
4796 puts_filtered ("Ending remote debugging.\n");
4799 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4800 be chatty about it. */
4803 extended_remote_attach (struct target_ops *target, const char *args,
4806 struct remote_state *rs = get_remote_state ();
4808 char *wait_status = NULL;
4810 pid = parse_pid_to_attach (args);
4812 /* Remote PID can be freely equal to getpid, do not check it here the same
4813 way as in other targets. */
4815 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4816 error (_("This target does not support attaching to a process"));
4820 char *exec_file = get_exec_file (0);
4823 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4824 target_pid_to_str (pid_to_ptid (pid)));
4826 printf_unfiltered (_("Attaching to %s\n"),
4827 target_pid_to_str (pid_to_ptid (pid)));
4829 gdb_flush (gdb_stdout);
4832 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4834 getpkt (&rs->buf, &rs->buf_size, 0);
4836 switch (packet_ok (rs->buf,
4837 &remote_protocol_packets[PACKET_vAttach]))
4842 /* Save the reply for later. */
4843 wait_status = alloca (strlen (rs->buf) + 1);
4844 strcpy (wait_status, rs->buf);
4846 else if (strcmp (rs->buf, "OK") != 0)
4847 error (_("Attaching to %s failed with: %s"),
4848 target_pid_to_str (pid_to_ptid (pid)),
4851 case PACKET_UNKNOWN:
4852 error (_("This target does not support attaching to a process"));
4854 error (_("Attaching to %s failed"),
4855 target_pid_to_str (pid_to_ptid (pid)));
4858 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
4860 inferior_ptid = pid_to_ptid (pid);
4864 struct thread_info *thread;
4866 /* Get list of threads. */
4867 remote_update_thread_list (target);
4869 thread = first_thread_of_process (pid);
4871 inferior_ptid = thread->ptid;
4873 inferior_ptid = pid_to_ptid (pid);
4875 /* Invalidate our notion of the remote current thread. */
4876 record_currthread (rs, minus_one_ptid);
4880 /* Now, if we have thread information, update inferior_ptid. */
4881 inferior_ptid = remote_current_thread (inferior_ptid);
4883 /* Add the main thread to the thread list. */
4884 add_thread_silent (inferior_ptid);
4887 /* Next, if the target can specify a description, read it. We do
4888 this before anything involving memory or registers. */
4889 target_find_description ();
4893 /* Use the previously fetched status. */
4894 gdb_assert (wait_status != NULL);
4896 if (target_can_async_p ())
4898 struct notif_event *reply
4899 = remote_notif_parse (¬if_client_stop, wait_status);
4901 push_stop_reply ((struct stop_reply *) reply);
4907 gdb_assert (wait_status != NULL);
4908 strcpy (rs->buf, wait_status);
4909 rs->cached_wait_status = 1;
4913 gdb_assert (wait_status == NULL);
4916 /* Implementation of the to_post_attach method. */
4919 extended_remote_post_attach (struct target_ops *ops, int pid)
4921 /* In certain cases GDB might not have had the chance to start
4922 symbol lookup up until now. This could happen if the debugged
4923 binary is not using shared libraries, the vsyscall page is not
4924 present (on Linux) and the binary itself hadn't changed since the
4925 debugging process was started. */
4926 if (symfile_objfile != NULL)
4927 remote_check_symbols();
4931 /* Check for the availability of vCont. This function should also check
4935 remote_vcont_probe (struct remote_state *rs)
4939 strcpy (rs->buf, "vCont?");
4941 getpkt (&rs->buf, &rs->buf_size, 0);
4944 /* Make sure that the features we assume are supported. */
4945 if (startswith (buf, "vCont"))
4948 int support_s, support_S, support_c, support_C;
4954 rs->supports_vCont.t = 0;
4955 rs->supports_vCont.r = 0;
4956 while (p && *p == ';')
4959 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4961 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4963 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4965 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4967 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4968 rs->supports_vCont.t = 1;
4969 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4970 rs->supports_vCont.r = 1;
4972 p = strchr (p, ';');
4975 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4976 BUF will make packet_ok disable the packet. */
4977 if (!support_s || !support_S || !support_c || !support_C)
4981 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4984 /* Helper function for building "vCont" resumptions. Write a
4985 resumption to P. ENDP points to one-passed-the-end of the buffer
4986 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4987 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4988 resumed thread should be single-stepped and/or signalled. If PTID
4989 equals minus_one_ptid, then all threads are resumed; if PTID
4990 represents a process, then all threads of the process are resumed;
4991 the thread to be stepped and/or signalled is given in the global
4995 append_resumption (char *p, char *endp,
4996 ptid_t ptid, int step, enum gdb_signal siggnal)
4998 struct remote_state *rs = get_remote_state ();
5000 if (step && siggnal != GDB_SIGNAL_0)
5001 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5003 /* GDB is willing to range step. */
5004 && use_range_stepping
5005 /* Target supports range stepping. */
5006 && rs->supports_vCont.r
5007 /* We don't currently support range stepping multiple
5008 threads with a wildcard (though the protocol allows it,
5009 so stubs shouldn't make an active effort to forbid
5011 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5013 struct thread_info *tp;
5015 if (ptid_equal (ptid, minus_one_ptid))
5017 /* If we don't know about the target thread's tid, then
5018 we're resuming magic_null_ptid (see caller). */
5019 tp = find_thread_ptid (magic_null_ptid);
5022 tp = find_thread_ptid (ptid);
5023 gdb_assert (tp != NULL);
5025 if (tp->control.may_range_step)
5027 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5029 p += xsnprintf (p, endp - p, ";r%s,%s",
5030 phex_nz (tp->control.step_range_start,
5032 phex_nz (tp->control.step_range_end,
5036 p += xsnprintf (p, endp - p, ";s");
5039 p += xsnprintf (p, endp - p, ";s");
5040 else if (siggnal != GDB_SIGNAL_0)
5041 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5043 p += xsnprintf (p, endp - p, ";c");
5045 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5049 /* All (-1) threads of process. */
5050 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5052 p += xsnprintf (p, endp - p, ":");
5053 p = write_ptid (p, endp, nptid);
5055 else if (!ptid_equal (ptid, minus_one_ptid))
5057 p += xsnprintf (p, endp - p, ":");
5058 p = write_ptid (p, endp, ptid);
5064 /* Append a vCont continue-with-signal action for threads that have a
5065 non-zero stop signal. */
5068 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5070 struct thread_info *thread;
5072 ALL_NON_EXITED_THREADS (thread)
5073 if (ptid_match (thread->ptid, ptid)
5074 && !ptid_equal (inferior_ptid, thread->ptid)
5075 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5077 p = append_resumption (p, endp, thread->ptid,
5078 0, thread->suspend.stop_signal);
5079 thread->suspend.stop_signal = GDB_SIGNAL_0;
5085 /* Resume the remote inferior by using a "vCont" packet. The thread
5086 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5087 resumed thread should be single-stepped and/or signalled. If PTID
5088 equals minus_one_ptid, then all threads are resumed; the thread to
5089 be stepped and/or signalled is given in the global INFERIOR_PTID.
5090 This function returns non-zero iff it resumes the inferior.
5092 This function issues a strict subset of all possible vCont commands at the
5096 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5098 struct remote_state *rs = get_remote_state ();
5102 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5103 remote_vcont_probe (rs);
5105 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5109 endp = rs->buf + get_remote_packet_size ();
5111 /* If we could generate a wider range of packets, we'd have to worry
5112 about overflowing BUF. Should there be a generic
5113 "multi-part-packet" packet? */
5115 p += xsnprintf (p, endp - p, "vCont");
5117 if (ptid_equal (ptid, magic_null_ptid))
5119 /* MAGIC_NULL_PTID means that we don't have any active threads,
5120 so we don't have any TID numbers the inferior will
5121 understand. Make sure to only send forms that do not specify
5123 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5125 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5127 /* Resume all threads (of all processes, or of a single
5128 process), with preference for INFERIOR_PTID. This assumes
5129 inferior_ptid belongs to the set of all threads we are about
5131 if (step || siggnal != GDB_SIGNAL_0)
5133 /* Step inferior_ptid, with or without signal. */
5134 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5137 /* Also pass down any pending signaled resumption for other
5138 threads not the current. */
5139 p = append_pending_thread_resumptions (p, endp, ptid);
5141 /* And continue others without a signal. */
5142 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5146 /* Scheduler locking; resume only PTID. */
5147 append_resumption (p, endp, ptid, step, siggnal);
5150 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5155 /* In non-stop, the stub replies to vCont with "OK". The stop
5156 reply will be reported asynchronously by means of a `%Stop'
5158 getpkt (&rs->buf, &rs->buf_size, 0);
5159 if (strcmp (rs->buf, "OK") != 0)
5160 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5166 /* Tell the remote machine to resume. */
5169 remote_resume (struct target_ops *ops,
5170 ptid_t ptid, int step, enum gdb_signal siggnal)
5172 struct remote_state *rs = get_remote_state ();
5175 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5176 (explained in remote-notif.c:handle_notification) so
5177 remote_notif_process is not called. We need find a place where
5178 it is safe to start a 'vNotif' sequence. It is good to do it
5179 before resuming inferior, because inferior was stopped and no RSP
5180 traffic at that moment. */
5182 remote_notif_process (rs->notif_state, ¬if_client_stop);
5184 rs->last_sent_signal = siggnal;
5185 rs->last_sent_step = step;
5187 /* The vCont packet doesn't need to specify threads via Hc. */
5188 /* No reverse support (yet) for vCont. */
5189 if (execution_direction != EXEC_REVERSE)
5190 if (remote_vcont_resume (ptid, step, siggnal))
5193 /* All other supported resume packets do use Hc, so set the continue
5195 if (ptid_equal (ptid, minus_one_ptid))
5196 set_continue_thread (any_thread_ptid);
5198 set_continue_thread (ptid);
5201 if (execution_direction == EXEC_REVERSE)
5203 /* We don't pass signals to the target in reverse exec mode. */
5204 if (info_verbose && siggnal != GDB_SIGNAL_0)
5205 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5208 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5209 error (_("Remote reverse-step not supported."));
5210 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5211 error (_("Remote reverse-continue not supported."));
5213 strcpy (buf, step ? "bs" : "bc");
5215 else if (siggnal != GDB_SIGNAL_0)
5217 buf[0] = step ? 'S' : 'C';
5218 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5219 buf[2] = tohex (((int) siggnal) & 0xf);
5223 strcpy (buf, step ? "s" : "c");
5228 /* We are about to start executing the inferior, let's register it
5229 with the event loop. NOTE: this is the one place where all the
5230 execution commands end up. We could alternatively do this in each
5231 of the execution commands in infcmd.c. */
5232 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5233 into infcmd.c in order to allow inferior function calls to work
5234 NOT asynchronously. */
5235 if (target_can_async_p ())
5238 /* We've just told the target to resume. The remote server will
5239 wait for the inferior to stop, and then send a stop reply. In
5240 the mean time, we can't start another command/query ourselves
5241 because the stub wouldn't be ready to process it. This applies
5242 only to the base all-stop protocol, however. In non-stop (which
5243 only supports vCont), the stub replies with an "OK", and is
5244 immediate able to process further serial input. */
5246 rs->waiting_for_stop_reply = 1;
5250 /* Set up the signal handler for SIGINT, while the target is
5251 executing, ovewriting the 'regular' SIGINT signal handler. */
5253 async_initialize_sigint_signal_handler (void)
5255 signal (SIGINT, async_handle_remote_sigint);
5258 /* Signal handler for SIGINT, while the target is executing. */
5260 async_handle_remote_sigint (int sig)
5262 signal (sig, async_handle_remote_sigint_twice);
5263 /* Note we need to go through gdb_call_async_signal_handler in order
5264 to wake up the event loop on Windows. */
5265 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5268 /* Signal handler for SIGINT, installed after SIGINT has already been
5269 sent once. It will take effect the second time that the user sends
5272 async_handle_remote_sigint_twice (int sig)
5274 signal (sig, async_handle_remote_sigint);
5275 /* See note in async_handle_remote_sigint. */
5276 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5279 /* Implementation of to_check_pending_interrupt. */
5282 remote_check_pending_interrupt (struct target_ops *self)
5284 struct async_signal_handler *token = async_sigint_remote_twice_token;
5286 if (async_signal_handler_is_marked (token))
5288 clear_async_signal_handler (token);
5289 call_async_signal_handler (token);
5293 /* Perform the real interruption of the target execution, in response
5296 async_remote_interrupt (gdb_client_data arg)
5299 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5301 target_stop (inferior_ptid);
5304 /* Perform interrupt, if the first attempt did not succeed. Just give
5305 up on the target alltogether. */
5307 async_remote_interrupt_twice (gdb_client_data arg)
5310 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5315 /* Reinstall the usual SIGINT handlers, after the target has
5318 async_cleanup_sigint_signal_handler (void *dummy)
5320 signal (SIGINT, handle_sigint);
5323 /* Send ^C to target to halt it. Target will respond, and send us a
5325 static void (*ofunc) (int);
5327 /* The command line interface's interrupt routine. This function is installed
5328 as a signal handler for SIGINT. The first time a user requests an
5329 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5330 response from the target (it didn't stop when the user requested it),
5331 we ask the user if he'd like to detach from the target. */
5334 sync_remote_interrupt (int signo)
5336 /* If this doesn't work, try more severe steps. */
5337 signal (signo, sync_remote_interrupt_twice);
5339 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5342 /* The user typed ^C twice. */
5345 sync_remote_interrupt_twice (int signo)
5347 signal (signo, ofunc);
5348 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5349 signal (signo, sync_remote_interrupt);
5352 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5353 thread, all threads of a remote process, or all threads of all
5357 remote_stop_ns (ptid_t ptid)
5359 struct remote_state *rs = get_remote_state ();
5361 char *endp = rs->buf + get_remote_packet_size ();
5363 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5364 remote_vcont_probe (rs);
5366 if (!rs->supports_vCont.t)
5367 error (_("Remote server does not support stopping threads"));
5369 if (ptid_equal (ptid, minus_one_ptid)
5370 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5371 p += xsnprintf (p, endp - p, "vCont;t");
5376 p += xsnprintf (p, endp - p, "vCont;t:");
5378 if (ptid_is_pid (ptid))
5379 /* All (-1) threads of process. */
5380 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5383 /* Small optimization: if we already have a stop reply for
5384 this thread, no use in telling the stub we want this
5386 if (peek_stop_reply (ptid))
5392 write_ptid (p, endp, nptid);
5395 /* In non-stop, we get an immediate OK reply. The stop reply will
5396 come in asynchronously by notification. */
5398 getpkt (&rs->buf, &rs->buf_size, 0);
5399 if (strcmp (rs->buf, "OK") != 0)
5400 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5403 /* All-stop version of target_interrupt. Sends a break or a ^C to
5404 interrupt the remote target. It is undefined which thread of which
5405 process reports the interrupt. */
5408 remote_interrupt_as (ptid_t ptid)
5410 struct remote_state *rs = get_remote_state ();
5412 rs->ctrlc_pending_p = 1;
5414 /* If the inferior is stopped already, but the core didn't know
5415 about it yet, just ignore the request. The cached wait status
5416 will be collected in remote_wait. */
5417 if (rs->cached_wait_status)
5420 /* Send interrupt_sequence to remote target. */
5421 send_interrupt_sequence ();
5424 /* Implement the to_stop function for the remote targets. */
5427 remote_stop (struct target_ops *self, ptid_t ptid)
5430 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5433 remote_stop_ns (ptid);
5436 /* We don't currently have a way to transparently pause the
5437 remote target in all-stop mode. Interrupt it instead. */
5438 remote_interrupt_as (ptid);
5442 /* Implement the to_interrupt function for the remote targets. */
5445 remote_interrupt (struct target_ops *self, ptid_t ptid)
5448 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5452 /* We don't currently have a way to ^C the remote target in
5453 non-stop mode. Stop it (with no signal) instead. */
5454 remote_stop_ns (ptid);
5457 remote_interrupt_as (ptid);
5460 /* Ask the user what to do when an interrupt is received. */
5463 interrupt_query (void)
5465 struct remote_state *rs = get_remote_state ();
5466 struct cleanup *old_chain;
5468 old_chain = make_cleanup_restore_target_terminal ();
5469 target_terminal_ours ();
5471 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5473 if (query (_("The target is not responding to interrupt requests.\n"
5474 "Stop debugging it? ")))
5476 remote_unpush_target ();
5477 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5482 if (query (_("Interrupted while waiting for the program.\n"
5483 "Give up waiting? ")))
5487 do_cleanups (old_chain);
5490 /* Enable/disable target terminal ownership. Most targets can use
5491 terminal groups to control terminal ownership. Remote targets are
5492 different in that explicit transfer of ownership to/from GDB/target
5496 remote_terminal_inferior (struct target_ops *self)
5498 if (!target_async_permitted)
5499 /* Nothing to do. */
5502 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5503 idempotent. The event-loop GDB talking to an asynchronous target
5504 with a synchronous command calls this function from both
5505 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5506 transfer the terminal to the target when it shouldn't this guard
5508 if (!remote_async_terminal_ours_p)
5510 delete_file_handler (input_fd);
5511 remote_async_terminal_ours_p = 0;
5512 async_initialize_sigint_signal_handler ();
5513 /* NOTE: At this point we could also register our selves as the
5514 recipient of all input. Any characters typed could then be
5515 passed on down to the target. */
5519 remote_terminal_ours (struct target_ops *self)
5521 if (!target_async_permitted)
5522 /* Nothing to do. */
5525 /* See FIXME in remote_terminal_inferior. */
5526 if (remote_async_terminal_ours_p)
5528 async_cleanup_sigint_signal_handler (NULL);
5529 add_file_handler (input_fd, stdin_event_handler, 0);
5530 remote_async_terminal_ours_p = 1;
5534 remote_console_output (char *msg)
5538 for (p = msg; p[0] && p[1]; p += 2)
5541 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5545 fputs_unfiltered (tb, gdb_stdtarg);
5547 gdb_flush (gdb_stdtarg);
5550 typedef struct cached_reg
5553 gdb_byte data[MAX_REGISTER_SIZE];
5556 DEF_VEC_O(cached_reg_t);
5558 typedef struct stop_reply
5560 struct notif_event base;
5562 /* The identifier of the thread about this event */
5565 /* The remote state this event is associated with. When the remote
5566 connection, represented by a remote_state object, is closed,
5567 all the associated stop_reply events should be released. */
5568 struct remote_state *rs;
5570 struct target_waitstatus ws;
5572 /* Expedited registers. This makes remote debugging a bit more
5573 efficient for those targets that provide critical registers as
5574 part of their normal status mechanism (as another roundtrip to
5575 fetch them is avoided). */
5576 VEC(cached_reg_t) *regcache;
5578 enum target_stop_reason stop_reason;
5580 CORE_ADDR watch_data_address;
5585 DECLARE_QUEUE_P (stop_reply_p);
5586 DEFINE_QUEUE_P (stop_reply_p);
5587 /* The list of already fetched and acknowledged stop events. This
5588 queue is used for notification Stop, and other notifications
5589 don't need queue for their events, because the notification events
5590 of Stop can't be consumed immediately, so that events should be
5591 queued first, and be consumed by remote_wait_{ns,as} one per
5592 time. Other notifications can consume their events immediately,
5593 so queue is not needed for them. */
5594 static QUEUE (stop_reply_p) *stop_reply_queue;
5597 stop_reply_xfree (struct stop_reply *r)
5599 notif_event_xfree ((struct notif_event *) r);
5602 /* Return the length of the stop reply queue. */
5605 stop_reply_queue_length (void)
5607 return QUEUE_length (stop_reply_p, stop_reply_queue);
5611 remote_notif_stop_parse (struct notif_client *self, char *buf,
5612 struct notif_event *event)
5614 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5618 remote_notif_stop_ack (struct notif_client *self, char *buf,
5619 struct notif_event *event)
5621 struct stop_reply *stop_reply = (struct stop_reply *) event;
5624 putpkt ((char *) self->ack_command);
5626 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5627 /* We got an unknown stop reply. */
5628 error (_("Unknown stop reply"));
5630 push_stop_reply (stop_reply);
5634 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5636 /* We can't get pending events in remote_notif_process for
5637 notification stop, and we have to do this in remote_wait_ns
5638 instead. If we fetch all queued events from stub, remote stub
5639 may exit and we have no chance to process them back in
5641 mark_async_event_handler (remote_async_inferior_event_token);
5646 stop_reply_dtr (struct notif_event *event)
5648 struct stop_reply *r = (struct stop_reply *) event;
5650 VEC_free (cached_reg_t, r->regcache);
5653 static struct notif_event *
5654 remote_notif_stop_alloc_reply (void)
5656 /* We cast to a pointer to the "base class". */
5657 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5659 r->dtr = stop_reply_dtr;
5664 /* A client of notification Stop. */
5666 struct notif_client notif_client_stop =
5670 remote_notif_stop_parse,
5671 remote_notif_stop_ack,
5672 remote_notif_stop_can_get_pending_events,
5673 remote_notif_stop_alloc_reply,
5677 /* A parameter to pass data in and out. */
5679 struct queue_iter_param
5682 struct stop_reply *output;
5685 /* Determine if THREAD is a pending fork parent thread. ARG contains
5686 the pid of the process that owns the threads we want to check, or
5687 -1 if we want to check all threads. */
5690 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5693 if (ws->kind == TARGET_WAITKIND_FORKED
5694 || ws->kind == TARGET_WAITKIND_VFORKED)
5696 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5703 /* Check whether EVENT is a fork event, and if it is, remove the
5704 fork child from the context list passed in DATA. */
5707 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5708 QUEUE_ITER (stop_reply_p) *iter,
5712 struct queue_iter_param *param = data;
5713 struct threads_listing_context *context = param->input;
5715 if (event->ws.kind == TARGET_WAITKIND_FORKED
5716 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5718 threads_listing_context_remove (&event->ws, context);
5724 /* If CONTEXT contains any fork child threads that have not been
5725 reported yet, remove them from the CONTEXT list. If such a
5726 thread exists it is because we are stopped at a fork catchpoint
5727 and have not yet called follow_fork, which will set up the
5728 host-side data structures for the new process. */
5731 remove_new_fork_children (struct threads_listing_context *context)
5733 struct thread_info * thread;
5735 struct notif_client *notif = ¬if_client_stop;
5736 struct queue_iter_param param;
5738 /* For any threads stopped at a fork event, remove the corresponding
5739 fork child threads from the CONTEXT list. */
5740 ALL_NON_EXITED_THREADS (thread)
5742 struct target_waitstatus *ws = &thread->pending_follow;
5744 if (is_pending_fork_parent (ws, pid, thread->ptid))
5746 threads_listing_context_remove (ws, context);
5750 /* Check for any pending fork events (not reported or processed yet)
5751 in process PID and remove those fork child threads from the
5752 CONTEXT list as well. */
5753 remote_notif_get_pending_events (notif);
5754 param.input = context;
5755 param.output = NULL;
5756 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5757 remove_child_of_pending_fork, ¶m);
5760 /* Remove stop replies in the queue if its pid is equal to the given
5764 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5765 QUEUE_ITER (stop_reply_p) *iter,
5769 struct queue_iter_param *param = data;
5770 struct inferior *inf = param->input;
5772 if (ptid_get_pid (event->ptid) == inf->pid)
5774 stop_reply_xfree (event);
5775 QUEUE_remove_elem (stop_reply_p, q, iter);
5781 /* Discard all pending stop replies of inferior INF. */
5784 discard_pending_stop_replies (struct inferior *inf)
5787 struct queue_iter_param param;
5788 struct stop_reply *reply;
5789 struct remote_state *rs = get_remote_state ();
5790 struct remote_notif_state *rns = rs->notif_state;
5792 /* This function can be notified when an inferior exists. When the
5793 target is not remote, the notification state is NULL. */
5794 if (rs->remote_desc == NULL)
5797 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5799 /* Discard the in-flight notification. */
5800 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5802 stop_reply_xfree (reply);
5803 rns->pending_event[notif_client_stop.id] = NULL;
5807 param.output = NULL;
5808 /* Discard the stop replies we have already pulled with
5810 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5811 remove_stop_reply_for_inferior, ¶m);
5814 /* If its remote state is equal to the given remote state,
5815 remove EVENT from the stop reply queue. */
5818 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5819 QUEUE_ITER (stop_reply_p) *iter,
5823 struct queue_iter_param *param = data;
5824 struct remote_state *rs = param->input;
5826 if (event->rs == rs)
5828 stop_reply_xfree (event);
5829 QUEUE_remove_elem (stop_reply_p, q, iter);
5835 /* Discard the stop replies for RS in stop_reply_queue. */
5838 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5840 struct queue_iter_param param;
5843 param.output = NULL;
5844 /* Discard the stop replies we have already pulled with
5846 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5847 remove_stop_reply_of_remote_state, ¶m);
5850 /* A parameter to pass data in and out. */
5853 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5854 QUEUE_ITER (stop_reply_p) *iter,
5858 struct queue_iter_param *param = data;
5859 ptid_t *ptid = param->input;
5861 if (ptid_match (event->ptid, *ptid))
5863 param->output = event;
5864 QUEUE_remove_elem (stop_reply_p, q, iter);
5871 /* Remove the first reply in 'stop_reply_queue' which matches
5874 static struct stop_reply *
5875 remote_notif_remove_queued_reply (ptid_t ptid)
5877 struct queue_iter_param param;
5879 param.input = &ptid;
5880 param.output = NULL;
5882 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5883 remote_notif_remove_once_on_match, ¶m);
5885 fprintf_unfiltered (gdb_stdlog,
5886 "notif: discard queued event: 'Stop' in %s\n",
5887 target_pid_to_str (ptid));
5889 return param.output;
5892 /* Look for a queued stop reply belonging to PTID. If one is found,
5893 remove it from the queue, and return it. Returns NULL if none is
5894 found. If there are still queued events left to process, tell the
5895 event loop to get back to target_wait soon. */
5897 static struct stop_reply *
5898 queued_stop_reply (ptid_t ptid)
5900 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5902 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5903 /* There's still at least an event left. */
5904 mark_async_event_handler (remote_async_inferior_event_token);
5909 /* Push a fully parsed stop reply in the stop reply queue. Since we
5910 know that we now have at least one queued event left to pass to the
5911 core side, tell the event loop to get back to target_wait soon. */
5914 push_stop_reply (struct stop_reply *new_event)
5916 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5919 fprintf_unfiltered (gdb_stdlog,
5920 "notif: push 'Stop' %s to queue %d\n",
5921 target_pid_to_str (new_event->ptid),
5922 QUEUE_length (stop_reply_p,
5925 mark_async_event_handler (remote_async_inferior_event_token);
5929 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5930 QUEUE_ITER (stop_reply_p) *iter,
5931 struct stop_reply *event,
5934 ptid_t *ptid = data;
5936 return !(ptid_equal (*ptid, event->ptid)
5937 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5940 /* Returns true if we have a stop reply for PTID. */
5943 peek_stop_reply (ptid_t ptid)
5945 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5946 stop_reply_match_ptid_and_ws, &ptid);
5949 /* Skip PACKET until the next semi-colon (or end of string). */
5952 skip_to_semicolon (char *p)
5954 while (*p != '\0' && *p != ';')
5959 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
5960 starting with P and ending with PEND matches PREFIX. */
5963 strprefix (const char *p, const char *pend, const char *prefix)
5965 for ( ; p < pend; p++, prefix++)
5968 return *prefix == '\0';
5971 /* Parse the stop reply in BUF. Either the function succeeds, and the
5972 result is stored in EVENT, or throws an error. */
5975 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5977 struct remote_arch_state *rsa = get_remote_arch_state ();
5981 event->ptid = null_ptid;
5982 event->rs = get_remote_state ();
5983 event->ws.kind = TARGET_WAITKIND_IGNORE;
5984 event->ws.value.integer = 0;
5985 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5986 event->regcache = NULL;
5991 case 'T': /* Status with PC, SP, FP, ... */
5992 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5993 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5995 n... = register number
5996 r... = register contents
5999 p = &buf[3]; /* after Txx */
6005 p1 = strchr (p, ':');
6007 error (_("Malformed packet(a) (missing colon): %s\n\
6011 error (_("Malformed packet(a) (missing register number): %s\n\
6015 /* Some "registers" are actually extended stop information.
6016 Note if you're adding a new entry here: GDB 7.9 and
6017 earlier assume that all register "numbers" that start
6018 with an hex digit are real register numbers. Make sure
6019 the server only sends such a packet if it knows the
6020 client understands it. */
6022 if (strprefix (p, p1, "thread"))
6023 event->ptid = read_ptid (++p1, &p);
6024 else if (strprefix (p, p1, "watch")
6025 || strprefix (p, p1, "rwatch")
6026 || strprefix (p, p1, "awatch"))
6028 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6029 p = unpack_varlen_hex (++p1, &addr);
6030 event->watch_data_address = (CORE_ADDR) addr;
6032 else if (strprefix (p, p1, "swbreak"))
6034 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6036 /* Make sure the stub doesn't forget to indicate support
6038 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6039 error (_("Unexpected swbreak stop reason"));
6041 /* The value part is documented as "must be empty",
6042 though we ignore it, in case we ever decide to make
6043 use of it in a backward compatible way. */
6044 p = skip_to_semicolon (p1 + 1);
6046 else if (strprefix (p, p1, "hwbreak"))
6048 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6050 /* Make sure the stub doesn't forget to indicate support
6052 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6053 error (_("Unexpected hwbreak stop reason"));
6056 p = skip_to_semicolon (p1 + 1);
6058 else if (strprefix (p, p1, "library"))
6060 event->ws.kind = TARGET_WAITKIND_LOADED;
6061 p = skip_to_semicolon (p1 + 1);
6063 else if (strprefix (p, p1, "replaylog"))
6065 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6066 /* p1 will indicate "begin" or "end", but it makes
6067 no difference for now, so ignore it. */
6068 p = skip_to_semicolon (p1 + 1);
6070 else if (strprefix (p, p1, "core"))
6074 p = unpack_varlen_hex (++p1, &c);
6077 else if (strprefix (p, p1, "fork"))
6079 event->ws.value.related_pid = read_ptid (++p1, &p);
6080 event->ws.kind = TARGET_WAITKIND_FORKED;
6082 else if (strprefix (p, p1, "vfork"))
6084 event->ws.value.related_pid = read_ptid (++p1, &p);
6085 event->ws.kind = TARGET_WAITKIND_VFORKED;
6087 else if (strprefix (p, p1, "vforkdone"))
6089 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6090 p = skip_to_semicolon (p1 + 1);
6097 /* Maybe a real ``P'' register number. */
6098 p_temp = unpack_varlen_hex (p, &pnum);
6099 /* If the first invalid character is the colon, we got a
6100 register number. Otherwise, it's an unknown stop
6104 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6105 cached_reg_t cached_reg;
6108 error (_("Remote sent bad register number %s: %s\n\
6110 hex_string (pnum), p, buf);
6112 cached_reg.num = reg->regnum;
6115 fieldsize = hex2bin (p, cached_reg.data,
6116 register_size (target_gdbarch (),
6119 if (fieldsize < register_size (target_gdbarch (),
6121 warning (_("Remote reply is too short: %s"), buf);
6123 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6127 /* Not a number. Silently skip unknown optional
6129 p = skip_to_semicolon (p1 + 1);
6134 error (_("Remote register badly formatted: %s\nhere: %s"),
6139 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6143 case 'S': /* Old style status, just signal only. */
6147 event->ws.kind = TARGET_WAITKIND_STOPPED;
6148 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6149 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6150 event->ws.value.sig = (enum gdb_signal) sig;
6152 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6155 case 'W': /* Target exited. */
6162 /* GDB used to accept only 2 hex chars here. Stubs should
6163 only send more if they detect GDB supports multi-process
6165 p = unpack_varlen_hex (&buf[1], &value);
6169 /* The remote process exited. */
6170 event->ws.kind = TARGET_WAITKIND_EXITED;
6171 event->ws.value.integer = value;
6175 /* The remote process exited with a signal. */
6176 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6177 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6178 event->ws.value.sig = (enum gdb_signal) value;
6180 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6183 /* If no process is specified, assume inferior_ptid. */
6184 pid = ptid_get_pid (inferior_ptid);
6193 else if (startswith (p, "process:"))
6197 p += sizeof ("process:") - 1;
6198 unpack_varlen_hex (p, &upid);
6202 error (_("unknown stop reply packet: %s"), buf);
6205 error (_("unknown stop reply packet: %s"), buf);
6206 event->ptid = pid_to_ptid (pid);
6211 if (non_stop && ptid_equal (event->ptid, null_ptid))
6212 error (_("No process or thread specified in stop reply: %s"), buf);
6215 /* When the stub wants to tell GDB about a new notification reply, it
6216 sends a notification (%Stop, for example). Those can come it at
6217 any time, hence, we have to make sure that any pending
6218 putpkt/getpkt sequence we're making is finished, before querying
6219 the stub for more events with the corresponding ack command
6220 (vStopped, for example). E.g., if we started a vStopped sequence
6221 immediately upon receiving the notification, something like this
6229 1.6) <-- (registers reply to step #1.3)
6231 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6234 To solve this, whenever we parse a %Stop notification successfully,
6235 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6236 doing whatever we were doing:
6242 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6243 2.5) <-- (registers reply to step #2.3)
6245 Eventualy after step #2.5, we return to the event loop, which
6246 notices there's an event on the
6247 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6248 associated callback --- the function below. At this point, we're
6249 always safe to start a vStopped sequence. :
6252 2.7) <-- T05 thread:2
6258 remote_notif_get_pending_events (struct notif_client *nc)
6260 struct remote_state *rs = get_remote_state ();
6262 if (rs->notif_state->pending_event[nc->id] != NULL)
6265 fprintf_unfiltered (gdb_stdlog,
6266 "notif: process: '%s' ack pending event\n",
6270 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6271 rs->notif_state->pending_event[nc->id] = NULL;
6275 getpkt (&rs->buf, &rs->buf_size, 0);
6276 if (strcmp (rs->buf, "OK") == 0)
6279 remote_notif_ack (nc, rs->buf);
6285 fprintf_unfiltered (gdb_stdlog,
6286 "notif: process: '%s' no pending reply\n",
6291 /* Called when it is decided that STOP_REPLY holds the info of the
6292 event that is to be returned to the core. This function always
6293 destroys STOP_REPLY. */
6296 process_stop_reply (struct stop_reply *stop_reply,
6297 struct target_waitstatus *status)
6301 *status = stop_reply->ws;
6302 ptid = stop_reply->ptid;
6304 /* If no thread/process was reported by the stub, assume the current
6306 if (ptid_equal (ptid, null_ptid))
6307 ptid = inferior_ptid;
6309 if (status->kind != TARGET_WAITKIND_EXITED
6310 && status->kind != TARGET_WAITKIND_SIGNALLED)
6312 struct remote_state *rs = get_remote_state ();
6314 /* Expedited registers. */
6315 if (stop_reply->regcache)
6317 struct regcache *regcache
6318 = get_thread_arch_regcache (ptid, target_gdbarch ());
6323 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6325 regcache_raw_supply (regcache, reg->num, reg->data);
6326 VEC_free (cached_reg_t, stop_reply->regcache);
6329 rs->stop_reason = stop_reply->stop_reason;
6330 rs->remote_watch_data_address = stop_reply->watch_data_address;
6332 remote_notice_new_inferior (ptid, 0);
6333 demand_private_info (ptid)->core = stop_reply->core;
6336 stop_reply_xfree (stop_reply);
6340 /* The non-stop mode version of target_wait. */
6343 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6345 struct remote_state *rs = get_remote_state ();
6346 struct stop_reply *stop_reply;
6350 /* If in non-stop mode, get out of getpkt even if a
6351 notification is received. */
6353 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6354 0 /* forever */, &is_notif);
6357 if (ret != -1 && !is_notif)
6360 case 'E': /* Error of some sort. */
6361 /* We're out of sync with the target now. Did it continue
6362 or not? We can't tell which thread it was in non-stop,
6363 so just ignore this. */
6364 warning (_("Remote failure reply: %s"), rs->buf);
6366 case 'O': /* Console output. */
6367 remote_console_output (rs->buf + 1);
6370 warning (_("Invalid remote reply: %s"), rs->buf);
6374 /* Acknowledge a pending stop reply that may have arrived in the
6376 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6377 remote_notif_get_pending_events (¬if_client_stop);
6379 /* If indeed we noticed a stop reply, we're done. */
6380 stop_reply = queued_stop_reply (ptid);
6381 if (stop_reply != NULL)
6382 return process_stop_reply (stop_reply, status);
6384 /* Still no event. If we're just polling for an event, then
6385 return to the event loop. */
6386 if (options & TARGET_WNOHANG)
6388 status->kind = TARGET_WAITKIND_IGNORE;
6389 return minus_one_ptid;
6392 /* Otherwise do a blocking wait. */
6393 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6394 1 /* forever */, &is_notif);
6398 /* Wait until the remote machine stops, then return, storing status in
6399 STATUS just as `wait' would. */
6402 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6404 struct remote_state *rs = get_remote_state ();
6405 ptid_t event_ptid = null_ptid;
6407 struct stop_reply *stop_reply;
6411 status->kind = TARGET_WAITKIND_IGNORE;
6412 status->value.integer = 0;
6414 stop_reply = queued_stop_reply (ptid);
6415 if (stop_reply != NULL)
6416 return process_stop_reply (stop_reply, status);
6418 if (rs->cached_wait_status)
6419 /* Use the cached wait status, but only once. */
6420 rs->cached_wait_status = 0;
6425 int forever = ((options & TARGET_WNOHANG) == 0
6426 && wait_forever_enabled_p);
6428 if (!rs->waiting_for_stop_reply)
6430 status->kind = TARGET_WAITKIND_NO_RESUMED;
6431 return minus_one_ptid;
6434 if (!target_is_async_p ())
6436 ofunc = signal (SIGINT, sync_remote_interrupt);
6437 /* If the user hit C-c before this packet, or between packets,
6438 pretend that it was hit right here. */
6439 if (check_quit_flag ())
6442 sync_remote_interrupt (SIGINT);
6446 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6447 _never_ wait for ever -> test on target_is_async_p().
6448 However, before we do that we need to ensure that the caller
6449 knows how to take the target into/out of async mode. */
6450 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6451 forever, &is_notif);
6453 if (!target_is_async_p ())
6454 signal (SIGINT, ofunc);
6456 /* GDB gets a notification. Return to core as this event is
6458 if (ret != -1 && is_notif)
6459 return minus_one_ptid;
6461 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6462 return minus_one_ptid;
6467 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6469 /* We got something. */
6470 rs->waiting_for_stop_reply = 0;
6472 /* Assume that the target has acknowledged Ctrl-C unless we receive
6473 an 'F' or 'O' packet. */
6474 if (buf[0] != 'F' && buf[0] != 'O')
6475 rs->ctrlc_pending_p = 0;
6479 case 'E': /* Error of some sort. */
6480 /* We're out of sync with the target now. Did it continue or
6481 not? Not is more likely, so report a stop. */
6482 warning (_("Remote failure reply: %s"), buf);
6483 status->kind = TARGET_WAITKIND_STOPPED;
6484 status->value.sig = GDB_SIGNAL_0;
6486 case 'F': /* File-I/O request. */
6487 remote_fileio_request (buf, rs->ctrlc_pending_p);
6488 rs->ctrlc_pending_p = 0;
6490 case 'T': case 'S': case 'X': case 'W':
6492 struct stop_reply *stop_reply
6493 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6496 event_ptid = process_stop_reply (stop_reply, status);
6499 case 'O': /* Console output. */
6500 remote_console_output (buf + 1);
6502 /* The target didn't really stop; keep waiting. */
6503 rs->waiting_for_stop_reply = 1;
6507 if (rs->last_sent_signal != GDB_SIGNAL_0)
6509 /* Zero length reply means that we tried 'S' or 'C' and the
6510 remote system doesn't support it. */
6511 target_terminal_ours_for_output ();
6513 ("Can't send signals to this remote system. %s not sent.\n",
6514 gdb_signal_to_name (rs->last_sent_signal));
6515 rs->last_sent_signal = GDB_SIGNAL_0;
6516 target_terminal_inferior ();
6518 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6519 putpkt ((char *) buf);
6521 /* We just told the target to resume, so a stop reply is in
6523 rs->waiting_for_stop_reply = 1;
6526 /* else fallthrough */
6528 warning (_("Invalid remote reply: %s"), buf);
6530 rs->waiting_for_stop_reply = 1;
6534 if (status->kind == TARGET_WAITKIND_IGNORE)
6536 /* Nothing interesting happened. If we're doing a non-blocking
6537 poll, we're done. Otherwise, go back to waiting. */
6538 if (options & TARGET_WNOHANG)
6539 return minus_one_ptid;
6543 else if (status->kind != TARGET_WAITKIND_EXITED
6544 && status->kind != TARGET_WAITKIND_SIGNALLED)
6546 if (!ptid_equal (event_ptid, null_ptid))
6547 record_currthread (rs, event_ptid);
6549 event_ptid = inferior_ptid;
6552 /* A process exit. Invalidate our notion of current thread. */
6553 record_currthread (rs, minus_one_ptid);
6558 /* Wait until the remote machine stops, then return, storing status in
6559 STATUS just as `wait' would. */
6562 remote_wait (struct target_ops *ops,
6563 ptid_t ptid, struct target_waitstatus *status, int options)
6568 event_ptid = remote_wait_ns (ptid, status, options);
6570 event_ptid = remote_wait_as (ptid, status, options);
6572 if (target_is_async_p ())
6574 /* If there are are events left in the queue tell the event loop
6576 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6577 mark_async_event_handler (remote_async_inferior_event_token);
6583 /* Fetch a single register using a 'p' packet. */
6586 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6588 struct remote_state *rs = get_remote_state ();
6590 char regp[MAX_REGISTER_SIZE];
6593 if (packet_support (PACKET_p) == PACKET_DISABLE)
6596 if (reg->pnum == -1)
6601 p += hexnumstr (p, reg->pnum);
6604 getpkt (&rs->buf, &rs->buf_size, 0);
6608 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6612 case PACKET_UNKNOWN:
6615 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6616 gdbarch_register_name (get_regcache_arch (regcache),
6621 /* If this register is unfetchable, tell the regcache. */
6624 regcache_raw_supply (regcache, reg->regnum, NULL);
6628 /* Otherwise, parse and supply the value. */
6634 error (_("fetch_register_using_p: early buf termination"));
6636 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6639 regcache_raw_supply (regcache, reg->regnum, regp);
6643 /* Fetch the registers included in the target's 'g' packet. */
6646 send_g_packet (void)
6648 struct remote_state *rs = get_remote_state ();
6651 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6652 remote_send (&rs->buf, &rs->buf_size);
6654 /* We can get out of synch in various cases. If the first character
6655 in the buffer is not a hex character, assume that has happened
6656 and try to fetch another packet to read. */
6657 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6658 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6659 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6660 && rs->buf[0] != 'x') /* New: unavailable register value. */
6663 fprintf_unfiltered (gdb_stdlog,
6664 "Bad register packet; fetching a new packet\n");
6665 getpkt (&rs->buf, &rs->buf_size, 0);
6668 buf_len = strlen (rs->buf);
6670 /* Sanity check the received packet. */
6671 if (buf_len % 2 != 0)
6672 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6678 process_g_packet (struct regcache *regcache)
6680 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6681 struct remote_state *rs = get_remote_state ();
6682 struct remote_arch_state *rsa = get_remote_arch_state ();
6687 buf_len = strlen (rs->buf);
6689 /* Further sanity checks, with knowledge of the architecture. */
6690 if (buf_len > 2 * rsa->sizeof_g_packet)
6691 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6693 /* Save the size of the packet sent to us by the target. It is used
6694 as a heuristic when determining the max size of packets that the
6695 target can safely receive. */
6696 if (rsa->actual_register_packet_size == 0)
6697 rsa->actual_register_packet_size = buf_len;
6699 /* If this is smaller than we guessed the 'g' packet would be,
6700 update our records. A 'g' reply that doesn't include a register's
6701 value implies either that the register is not available, or that
6702 the 'p' packet must be used. */
6703 if (buf_len < 2 * rsa->sizeof_g_packet)
6705 rsa->sizeof_g_packet = buf_len / 2;
6707 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6709 if (rsa->regs[i].pnum == -1)
6712 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6713 rsa->regs[i].in_g_packet = 0;
6715 rsa->regs[i].in_g_packet = 1;
6719 regs = alloca (rsa->sizeof_g_packet);
6721 /* Unimplemented registers read as all bits zero. */
6722 memset (regs, 0, rsa->sizeof_g_packet);
6724 /* Reply describes registers byte by byte, each byte encoded as two
6725 hex characters. Suck them all up, then supply them to the
6726 register cacheing/storage mechanism. */
6729 for (i = 0; i < rsa->sizeof_g_packet; i++)
6731 if (p[0] == 0 || p[1] == 0)
6732 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6733 internal_error (__FILE__, __LINE__,
6734 _("unexpected end of 'g' packet reply"));
6736 if (p[0] == 'x' && p[1] == 'x')
6737 regs[i] = 0; /* 'x' */
6739 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6743 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6745 struct packet_reg *r = &rsa->regs[i];
6749 if (r->offset * 2 >= strlen (rs->buf))
6750 /* This shouldn't happen - we adjusted in_g_packet above. */
6751 internal_error (__FILE__, __LINE__,
6752 _("unexpected end of 'g' packet reply"));
6753 else if (rs->buf[r->offset * 2] == 'x')
6755 gdb_assert (r->offset * 2 < strlen (rs->buf));
6756 /* The register isn't available, mark it as such (at
6757 the same time setting the value to zero). */
6758 regcache_raw_supply (regcache, r->regnum, NULL);
6761 regcache_raw_supply (regcache, r->regnum,
6768 fetch_registers_using_g (struct regcache *regcache)
6771 process_g_packet (regcache);
6774 /* Make the remote selected traceframe match GDB's selected
6778 set_remote_traceframe (void)
6781 struct remote_state *rs = get_remote_state ();
6783 if (rs->remote_traceframe_number == get_traceframe_number ())
6786 /* Avoid recursion, remote_trace_find calls us again. */
6787 rs->remote_traceframe_number = get_traceframe_number ();
6789 newnum = target_trace_find (tfind_number,
6790 get_traceframe_number (), 0, 0, NULL);
6792 /* Should not happen. If it does, all bets are off. */
6793 if (newnum != get_traceframe_number ())
6794 warning (_("could not set remote traceframe"));
6798 remote_fetch_registers (struct target_ops *ops,
6799 struct regcache *regcache, int regnum)
6801 struct remote_arch_state *rsa = get_remote_arch_state ();
6804 set_remote_traceframe ();
6805 set_general_thread (inferior_ptid);
6809 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6811 gdb_assert (reg != NULL);
6813 /* If this register might be in the 'g' packet, try that first -
6814 we are likely to read more than one register. If this is the
6815 first 'g' packet, we might be overly optimistic about its
6816 contents, so fall back to 'p'. */
6817 if (reg->in_g_packet)
6819 fetch_registers_using_g (regcache);
6820 if (reg->in_g_packet)
6824 if (fetch_register_using_p (regcache, reg))
6827 /* This register is not available. */
6828 regcache_raw_supply (regcache, reg->regnum, NULL);
6833 fetch_registers_using_g (regcache);
6835 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6836 if (!rsa->regs[i].in_g_packet)
6837 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6839 /* This register is not available. */
6840 regcache_raw_supply (regcache, i, NULL);
6844 /* Prepare to store registers. Since we may send them all (using a
6845 'G' request), we have to read out the ones we don't want to change
6849 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6851 struct remote_arch_state *rsa = get_remote_arch_state ();
6853 gdb_byte buf[MAX_REGISTER_SIZE];
6855 /* Make sure the entire registers array is valid. */
6856 switch (packet_support (PACKET_P))
6858 case PACKET_DISABLE:
6859 case PACKET_SUPPORT_UNKNOWN:
6860 /* Make sure all the necessary registers are cached. */
6861 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6862 if (rsa->regs[i].in_g_packet)
6863 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6870 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6871 packet was not recognized. */
6874 store_register_using_P (const struct regcache *regcache,
6875 struct packet_reg *reg)
6877 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6878 struct remote_state *rs = get_remote_state ();
6879 /* Try storing a single register. */
6880 char *buf = rs->buf;
6881 gdb_byte regp[MAX_REGISTER_SIZE];
6884 if (packet_support (PACKET_P) == PACKET_DISABLE)
6887 if (reg->pnum == -1)
6890 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6891 p = buf + strlen (buf);
6892 regcache_raw_collect (regcache, reg->regnum, regp);
6893 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6895 getpkt (&rs->buf, &rs->buf_size, 0);
6897 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6902 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6903 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6904 case PACKET_UNKNOWN:
6907 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6911 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6912 contents of the register cache buffer. FIXME: ignores errors. */
6915 store_registers_using_G (const struct regcache *regcache)
6917 struct remote_state *rs = get_remote_state ();
6918 struct remote_arch_state *rsa = get_remote_arch_state ();
6922 /* Extract all the registers in the regcache copying them into a
6927 regs = alloca (rsa->sizeof_g_packet);
6928 memset (regs, 0, rsa->sizeof_g_packet);
6929 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6931 struct packet_reg *r = &rsa->regs[i];
6934 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6938 /* Command describes registers byte by byte,
6939 each byte encoded as two hex characters. */
6942 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6944 bin2hex (regs, p, rsa->sizeof_g_packet);
6946 getpkt (&rs->buf, &rs->buf_size, 0);
6947 if (packet_check_result (rs->buf) == PACKET_ERROR)
6948 error (_("Could not write registers; remote failure reply '%s'"),
6952 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6953 of the register cache buffer. FIXME: ignores errors. */
6956 remote_store_registers (struct target_ops *ops,
6957 struct regcache *regcache, int regnum)
6959 struct remote_arch_state *rsa = get_remote_arch_state ();
6962 set_remote_traceframe ();
6963 set_general_thread (inferior_ptid);
6967 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6969 gdb_assert (reg != NULL);
6971 /* Always prefer to store registers using the 'P' packet if
6972 possible; we often change only a small number of registers.
6973 Sometimes we change a larger number; we'd need help from a
6974 higher layer to know to use 'G'. */
6975 if (store_register_using_P (regcache, reg))
6978 /* For now, don't complain if we have no way to write the
6979 register. GDB loses track of unavailable registers too
6980 easily. Some day, this may be an error. We don't have
6981 any way to read the register, either... */
6982 if (!reg->in_g_packet)
6985 store_registers_using_G (regcache);
6989 store_registers_using_G (regcache);
6991 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6992 if (!rsa->regs[i].in_g_packet)
6993 if (!store_register_using_P (regcache, &rsa->regs[i]))
6994 /* See above for why we do not issue an error here. */
6999 /* Return the number of hex digits in num. */
7002 hexnumlen (ULONGEST num)
7006 for (i = 0; num != 0; i++)
7012 /* Set BUF to the minimum number of hex digits representing NUM. */
7015 hexnumstr (char *buf, ULONGEST num)
7017 int len = hexnumlen (num);
7019 return hexnumnstr (buf, num, len);
7023 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7026 hexnumnstr (char *buf, ULONGEST num, int width)
7032 for (i = width - 1; i >= 0; i--)
7034 buf[i] = "0123456789abcdef"[(num & 0xf)];
7041 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7044 remote_address_masked (CORE_ADDR addr)
7046 unsigned int address_size = remote_address_size;
7048 /* If "remoteaddresssize" was not set, default to target address size. */
7050 address_size = gdbarch_addr_bit (target_gdbarch ());
7052 if (address_size > 0
7053 && address_size < (sizeof (ULONGEST) * 8))
7055 /* Only create a mask when that mask can safely be constructed
7056 in a ULONGEST variable. */
7059 mask = (mask << address_size) - 1;
7065 /* Determine whether the remote target supports binary downloading.
7066 This is accomplished by sending a no-op memory write of zero length
7067 to the target at the specified address. It does not suffice to send
7068 the whole packet, since many stubs strip the eighth bit and
7069 subsequently compute a wrong checksum, which causes real havoc with
7072 NOTE: This can still lose if the serial line is not eight-bit
7073 clean. In cases like this, the user should clear "remote
7077 check_binary_download (CORE_ADDR addr)
7079 struct remote_state *rs = get_remote_state ();
7081 switch (packet_support (PACKET_X))
7083 case PACKET_DISABLE:
7087 case PACKET_SUPPORT_UNKNOWN:
7093 p += hexnumstr (p, (ULONGEST) addr);
7095 p += hexnumstr (p, (ULONGEST) 0);
7099 putpkt_binary (rs->buf, (int) (p - rs->buf));
7100 getpkt (&rs->buf, &rs->buf_size, 0);
7102 if (rs->buf[0] == '\0')
7105 fprintf_unfiltered (gdb_stdlog,
7106 "binary downloading NOT "
7107 "supported by target\n");
7108 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7113 fprintf_unfiltered (gdb_stdlog,
7114 "binary downloading supported by target\n");
7115 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7122 /* Helper function to resize the payload in order to try to get a good
7123 alignment. We try to write an amount of data such that the next write will
7124 start on an address aligned on REMOTE_ALIGN_WRITES. */
7127 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7129 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7132 /* Write memory data directly to the remote machine.
7133 This does not inform the data cache; the data cache uses this.
7134 HEADER is the starting part of the packet.
7135 MEMADDR is the address in the remote memory space.
7136 MYADDR is the address of the buffer in our space.
7137 LEN_UNITS is the number of addressable units to write.
7138 UNIT_SIZE is the length in bytes of an addressable unit.
7139 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7140 should send data as binary ('X'), or hex-encoded ('M').
7142 The function creates packet of the form
7143 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7145 where encoding of <DATA> is terminated by PACKET_FORMAT.
7147 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7150 Return the transferred status, error or OK (an
7151 'enum target_xfer_status' value). Save the number of addressable units
7152 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7154 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7155 exchange between gdb and the stub could look like (?? in place of the
7161 -> $M1000,3:eeeeffffeeee#??
7165 <- eeeeffffeeeedddd */
7167 static enum target_xfer_status
7168 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7169 const gdb_byte *myaddr, ULONGEST len_units,
7170 int unit_size, ULONGEST *xfered_len_units,
7171 char packet_format, int use_length)
7173 struct remote_state *rs = get_remote_state ();
7179 int payload_capacity_bytes;
7180 int payload_length_bytes;
7182 if (packet_format != 'X' && packet_format != 'M')
7183 internal_error (__FILE__, __LINE__,
7184 _("remote_write_bytes_aux: bad packet format"));
7187 return TARGET_XFER_EOF;
7189 payload_capacity_bytes = get_memory_write_packet_size ();
7191 /* The packet buffer will be large enough for the payload;
7192 get_memory_packet_size ensures this. */
7195 /* Compute the size of the actual payload by subtracting out the
7196 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7198 payload_capacity_bytes -= strlen ("$,:#NN");
7200 /* The comma won't be used. */
7201 payload_capacity_bytes += 1;
7202 payload_capacity_bytes -= strlen (header);
7203 payload_capacity_bytes -= hexnumlen (memaddr);
7205 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7207 strcat (rs->buf, header);
7208 p = rs->buf + strlen (header);
7210 /* Compute a best guess of the number of bytes actually transfered. */
7211 if (packet_format == 'X')
7213 /* Best guess at number of bytes that will fit. */
7214 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7216 payload_capacity_bytes -= hexnumlen (todo_units);
7217 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7221 /* Number of bytes that will fit. */
7222 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7224 payload_capacity_bytes -= hexnumlen (todo_units);
7225 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7228 if (todo_units <= 0)
7229 internal_error (__FILE__, __LINE__,
7230 _("minimum packet size too small to write data"));
7232 /* If we already need another packet, then try to align the end
7233 of this packet to a useful boundary. */
7234 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7235 todo_units = align_for_efficient_write (todo_units, memaddr);
7237 /* Append "<memaddr>". */
7238 memaddr = remote_address_masked (memaddr);
7239 p += hexnumstr (p, (ULONGEST) memaddr);
7246 /* Append the length and retain its location and size. It may need to be
7247 adjusted once the packet body has been created. */
7249 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7257 /* Append the packet body. */
7258 if (packet_format == 'X')
7260 /* Binary mode. Send target system values byte by byte, in
7261 increasing byte addresses. Only escape certain critical
7263 payload_length_bytes =
7264 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7265 &units_written, payload_capacity_bytes);
7267 /* If not all TODO units fit, then we'll need another packet. Make
7268 a second try to keep the end of the packet aligned. Don't do
7269 this if the packet is tiny. */
7270 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7274 new_todo_units = align_for_efficient_write (units_written, memaddr);
7276 if (new_todo_units != units_written)
7277 payload_length_bytes =
7278 remote_escape_output (myaddr, new_todo_units, unit_size,
7279 (gdb_byte *) p, &units_written,
7280 payload_capacity_bytes);
7283 p += payload_length_bytes;
7284 if (use_length && units_written < todo_units)
7286 /* Escape chars have filled up the buffer prematurely,
7287 and we have actually sent fewer units than planned.
7288 Fix-up the length field of the packet. Use the same
7289 number of characters as before. */
7290 plen += hexnumnstr (plen, (ULONGEST) units_written,
7292 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7297 /* Normal mode: Send target system values byte by byte, in
7298 increasing byte addresses. Each byte is encoded as a two hex
7300 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7301 units_written = todo_units;
7304 putpkt_binary (rs->buf, (int) (p - rs->buf));
7305 getpkt (&rs->buf, &rs->buf_size, 0);
7307 if (rs->buf[0] == 'E')
7308 return TARGET_XFER_E_IO;
7310 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7311 send fewer units than we'd planned. */
7312 *xfered_len_units = (ULONGEST) units_written;
7313 return TARGET_XFER_OK;
7316 /* Write memory data directly to the remote machine.
7317 This does not inform the data cache; the data cache uses this.
7318 MEMADDR is the address in the remote memory space.
7319 MYADDR is the address of the buffer in our space.
7320 LEN is the number of bytes.
7322 Return the transferred status, error or OK (an
7323 'enum target_xfer_status' value). Save the number of bytes
7324 transferred in *XFERED_LEN. Only transfer a single packet. */
7326 static enum target_xfer_status
7327 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7328 int unit_size, ULONGEST *xfered_len)
7330 char *packet_format = 0;
7332 /* Check whether the target supports binary download. */
7333 check_binary_download (memaddr);
7335 switch (packet_support (PACKET_X))
7338 packet_format = "X";
7340 case PACKET_DISABLE:
7341 packet_format = "M";
7343 case PACKET_SUPPORT_UNKNOWN:
7344 internal_error (__FILE__, __LINE__,
7345 _("remote_write_bytes: bad internal state"));
7347 internal_error (__FILE__, __LINE__, _("bad switch"));
7350 return remote_write_bytes_aux (packet_format,
7351 memaddr, myaddr, len, unit_size, xfered_len,
7352 packet_format[0], 1);
7355 /* Read memory data directly from the remote machine.
7356 This does not use the data cache; the data cache uses this.
7357 MEMADDR is the address in the remote memory space.
7358 MYADDR is the address of the buffer in our space.
7359 LEN_UNITS is the number of addressable memory units to read..
7360 UNIT_SIZE is the length in bytes of an addressable unit.
7362 Return the transferred status, error or OK (an
7363 'enum target_xfer_status' value). Save the number of bytes
7364 transferred in *XFERED_LEN_UNITS.
7366 See the comment of remote_write_bytes_aux for an example of
7367 memory read/write exchange between gdb and the stub. */
7369 static enum target_xfer_status
7370 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7371 int unit_size, ULONGEST *xfered_len_units)
7373 struct remote_state *rs = get_remote_state ();
7374 int buf_size_bytes; /* Max size of packet output buffer. */
7379 buf_size_bytes = get_memory_read_packet_size ();
7380 /* The packet buffer will be large enough for the payload;
7381 get_memory_packet_size ensures this. */
7383 /* Number of units that will fit. */
7384 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7386 /* Construct "m"<memaddr>","<len>". */
7387 memaddr = remote_address_masked (memaddr);
7390 p += hexnumstr (p, (ULONGEST) memaddr);
7392 p += hexnumstr (p, (ULONGEST) todo_units);
7395 getpkt (&rs->buf, &rs->buf_size, 0);
7396 if (rs->buf[0] == 'E'
7397 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7398 && rs->buf[3] == '\0')
7399 return TARGET_XFER_E_IO;
7400 /* Reply describes memory byte by byte, each byte encoded as two hex
7403 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7404 /* Return what we have. Let higher layers handle partial reads. */
7405 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7406 return TARGET_XFER_OK;
7409 /* Using the set of read-only target sections of remote, read live
7412 For interface/parameters/return description see target.h,
7415 static enum target_xfer_status
7416 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7417 ULONGEST memaddr, ULONGEST len,
7418 int unit_size, ULONGEST *xfered_len)
7420 struct target_section *secp;
7421 struct target_section_table *table;
7423 secp = target_section_by_addr (ops, memaddr);
7425 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7426 secp->the_bfd_section)
7429 struct target_section *p;
7430 ULONGEST memend = memaddr + len;
7432 table = target_get_section_table (ops);
7434 for (p = table->sections; p < table->sections_end; p++)
7436 if (memaddr >= p->addr)
7438 if (memend <= p->endaddr)
7440 /* Entire transfer is within this section. */
7441 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7444 else if (memaddr >= p->endaddr)
7446 /* This section ends before the transfer starts. */
7451 /* This section overlaps the transfer. Just do half. */
7452 len = p->endaddr - memaddr;
7453 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7460 return TARGET_XFER_EOF;
7463 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7464 first if the requested memory is unavailable in traceframe.
7465 Otherwise, fall back to remote_read_bytes_1. */
7467 static enum target_xfer_status
7468 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7469 gdb_byte *myaddr, ULONGEST len, int unit_size,
7470 ULONGEST *xfered_len)
7473 return TARGET_XFER_EOF;
7475 if (get_traceframe_number () != -1)
7477 VEC(mem_range_s) *available;
7479 /* If we fail to get the set of available memory, then the
7480 target does not support querying traceframe info, and so we
7481 attempt reading from the traceframe anyway (assuming the
7482 target implements the old QTro packet then). */
7483 if (traceframe_available_memory (&available, memaddr, len))
7485 struct cleanup *old_chain;
7487 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7489 if (VEC_empty (mem_range_s, available)
7490 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7492 enum target_xfer_status res;
7494 /* Don't read into the traceframe's available
7496 if (!VEC_empty (mem_range_s, available))
7498 LONGEST oldlen = len;
7500 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7501 gdb_assert (len <= oldlen);
7504 do_cleanups (old_chain);
7506 /* This goes through the topmost target again. */
7507 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7508 len, unit_size, xfered_len);
7509 if (res == TARGET_XFER_OK)
7510 return TARGET_XFER_OK;
7513 /* No use trying further, we know some memory starting
7514 at MEMADDR isn't available. */
7516 return TARGET_XFER_UNAVAILABLE;
7520 /* Don't try to read more than how much is available, in
7521 case the target implements the deprecated QTro packet to
7522 cater for older GDBs (the target's knowledge of read-only
7523 sections may be outdated by now). */
7524 len = VEC_index (mem_range_s, available, 0)->length;
7526 do_cleanups (old_chain);
7530 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7535 /* Sends a packet with content determined by the printf format string
7536 FORMAT and the remaining arguments, then gets the reply. Returns
7537 whether the packet was a success, a failure, or unknown. */
7539 static enum packet_result remote_send_printf (const char *format, ...)
7540 ATTRIBUTE_PRINTF (1, 2);
7542 static enum packet_result
7543 remote_send_printf (const char *format, ...)
7545 struct remote_state *rs = get_remote_state ();
7546 int max_size = get_remote_packet_size ();
7549 va_start (ap, format);
7552 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7553 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7555 if (putpkt (rs->buf) < 0)
7556 error (_("Communication problem with target."));
7559 getpkt (&rs->buf, &rs->buf_size, 0);
7561 return packet_check_result (rs->buf);
7565 restore_remote_timeout (void *p)
7567 int value = *(int *)p;
7569 remote_timeout = value;
7572 /* Flash writing can take quite some time. We'll set
7573 effectively infinite timeout for flash operations.
7574 In future, we'll need to decide on a better approach. */
7575 static const int remote_flash_timeout = 1000;
7578 remote_flash_erase (struct target_ops *ops,
7579 ULONGEST address, LONGEST length)
7581 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7582 int saved_remote_timeout = remote_timeout;
7583 enum packet_result ret;
7584 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7585 &saved_remote_timeout);
7587 remote_timeout = remote_flash_timeout;
7589 ret = remote_send_printf ("vFlashErase:%s,%s",
7590 phex (address, addr_size),
7594 case PACKET_UNKNOWN:
7595 error (_("Remote target does not support flash erase"));
7597 error (_("Error erasing flash with vFlashErase packet"));
7602 do_cleanups (back_to);
7605 static enum target_xfer_status
7606 remote_flash_write (struct target_ops *ops, ULONGEST address,
7607 ULONGEST length, ULONGEST *xfered_len,
7608 const gdb_byte *data)
7610 int saved_remote_timeout = remote_timeout;
7611 enum target_xfer_status ret;
7612 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7613 &saved_remote_timeout);
7615 remote_timeout = remote_flash_timeout;
7616 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7618 do_cleanups (back_to);
7624 remote_flash_done (struct target_ops *ops)
7626 int saved_remote_timeout = remote_timeout;
7628 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7629 &saved_remote_timeout);
7631 remote_timeout = remote_flash_timeout;
7632 ret = remote_send_printf ("vFlashDone");
7633 do_cleanups (back_to);
7637 case PACKET_UNKNOWN:
7638 error (_("Remote target does not support vFlashDone"));
7640 error (_("Error finishing flash operation"));
7647 remote_files_info (struct target_ops *ignore)
7649 puts_filtered ("Debugging a target over a serial line.\n");
7652 /* Stuff for dealing with the packets which are part of this protocol.
7653 See comment at top of file for details. */
7655 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7656 error to higher layers. Called when a serial error is detected.
7657 The exception message is STRING, followed by a colon and a blank,
7658 the system error message for errno at function entry and final dot
7659 for output compatibility with throw_perror_with_name. */
7662 unpush_and_perror (const char *string)
7664 int saved_errno = errno;
7666 remote_unpush_target ();
7667 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7668 safe_strerror (saved_errno));
7671 /* Read a single character from the remote end. */
7674 readchar (int timeout)
7677 struct remote_state *rs = get_remote_state ();
7679 ch = serial_readchar (rs->remote_desc, timeout);
7684 switch ((enum serial_rc) ch)
7687 remote_unpush_target ();
7688 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7691 unpush_and_perror (_("Remote communication error. "
7692 "Target disconnected."));
7694 case SERIAL_TIMEOUT:
7700 /* Wrapper for serial_write that closes the target and throws if
7704 remote_serial_write (const char *str, int len)
7706 struct remote_state *rs = get_remote_state ();
7708 if (serial_write (rs->remote_desc, str, len))
7710 unpush_and_perror (_("Remote communication error. "
7711 "Target disconnected."));
7715 /* Send the command in *BUF to the remote machine, and read the reply
7716 into *BUF. Report an error if we get an error reply. Resize
7717 *BUF using xrealloc if necessary to hold the result, and update
7721 remote_send (char **buf,
7725 getpkt (buf, sizeof_buf, 0);
7727 if ((*buf)[0] == 'E')
7728 error (_("Remote failure reply: %s"), *buf);
7731 /* Return a pointer to an xmalloc'ed string representing an escaped
7732 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7733 etc. The caller is responsible for releasing the returned
7737 escape_buffer (const char *buf, int n)
7739 struct cleanup *old_chain;
7740 struct ui_file *stb;
7743 stb = mem_fileopen ();
7744 old_chain = make_cleanup_ui_file_delete (stb);
7746 fputstrn_unfiltered (buf, n, '\\', stb);
7747 str = ui_file_xstrdup (stb, NULL);
7748 do_cleanups (old_chain);
7752 /* Display a null-terminated packet on stdout, for debugging, using C
7756 print_packet (const char *buf)
7758 puts_filtered ("\"");
7759 fputstr_filtered (buf, '"', gdb_stdout);
7760 puts_filtered ("\"");
7764 putpkt (const char *buf)
7766 return putpkt_binary (buf, strlen (buf));
7769 /* Send a packet to the remote machine, with error checking. The data
7770 of the packet is in BUF. The string in BUF can be at most
7771 get_remote_packet_size () - 5 to account for the $, # and checksum,
7772 and for a possible /0 if we are debugging (remote_debug) and want
7773 to print the sent packet as a string. */
7776 putpkt_binary (const char *buf, int cnt)
7778 struct remote_state *rs = get_remote_state ();
7780 unsigned char csum = 0;
7781 char *buf2 = xmalloc (cnt + 6);
7782 struct cleanup *old_chain = make_cleanup (xfree, buf2);
7789 /* Catch cases like trying to read memory or listing threads while
7790 we're waiting for a stop reply. The remote server wouldn't be
7791 ready to handle this request, so we'd hang and timeout. We don't
7792 have to worry about this in synchronous mode, because in that
7793 case it's not possible to issue a command while the target is
7794 running. This is not a problem in non-stop mode, because in that
7795 case, the stub is always ready to process serial input. */
7796 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7798 error (_("Cannot execute this command while the target is running.\n"
7799 "Use the \"interrupt\" command to stop the target\n"
7800 "and then try again."));
7803 /* We're sending out a new packet. Make sure we don't look at a
7804 stale cached response. */
7805 rs->cached_wait_status = 0;
7807 /* Copy the packet into buffer BUF2, encapsulating it
7808 and giving it a checksum. */
7813 for (i = 0; i < cnt; i++)
7819 *p++ = tohex ((csum >> 4) & 0xf);
7820 *p++ = tohex (csum & 0xf);
7822 /* Send it over and over until we get a positive ack. */
7826 int started_error_output = 0;
7830 struct cleanup *old_chain;
7834 str = escape_buffer (buf2, p - buf2);
7835 old_chain = make_cleanup (xfree, str);
7836 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7837 gdb_flush (gdb_stdlog);
7838 do_cleanups (old_chain);
7840 remote_serial_write (buf2, p - buf2);
7842 /* If this is a no acks version of the remote protocol, send the
7843 packet and move on. */
7847 /* Read until either a timeout occurs (-2) or '+' is read.
7848 Handle any notification that arrives in the mean time. */
7851 ch = readchar (remote_timeout);
7859 case SERIAL_TIMEOUT:
7862 if (started_error_output)
7864 putchar_unfiltered ('\n');
7865 started_error_output = 0;
7874 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7875 do_cleanups (old_chain);
7879 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7881 case SERIAL_TIMEOUT:
7885 do_cleanups (old_chain);
7888 break; /* Retransmit buffer. */
7892 fprintf_unfiltered (gdb_stdlog,
7893 "Packet instead of Ack, ignoring it\n");
7894 /* It's probably an old response sent because an ACK
7895 was lost. Gobble up the packet and ack it so it
7896 doesn't get retransmitted when we resend this
7899 remote_serial_write ("+", 1);
7900 continue; /* Now, go look for +. */
7907 /* If we got a notification, handle it, and go back to looking
7909 /* We've found the start of a notification. Now
7910 collect the data. */
7911 val = read_frame (&rs->buf, &rs->buf_size);
7916 struct cleanup *old_chain;
7919 str = escape_buffer (rs->buf, val);
7920 old_chain = make_cleanup (xfree, str);
7921 fprintf_unfiltered (gdb_stdlog,
7922 " Notification received: %s\n",
7924 do_cleanups (old_chain);
7926 handle_notification (rs->notif_state, rs->buf);
7927 /* We're in sync now, rewait for the ack. */
7934 if (!started_error_output)
7936 started_error_output = 1;
7937 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7939 fputc_unfiltered (ch & 0177, gdb_stdlog);
7940 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7949 if (!started_error_output)
7951 started_error_output = 1;
7952 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7954 fputc_unfiltered (ch & 0177, gdb_stdlog);
7958 break; /* Here to retransmit. */
7962 /* This is wrong. If doing a long backtrace, the user should be
7963 able to get out next time we call QUIT, without anything as
7964 violent as interrupt_query. If we want to provide a way out of
7965 here without getting to the next QUIT, it should be based on
7966 hitting ^C twice as in remote_wait. */
7975 do_cleanups (old_chain);
7979 /* Come here after finding the start of a frame when we expected an
7980 ack. Do our best to discard the rest of this packet. */
7989 c = readchar (remote_timeout);
7992 case SERIAL_TIMEOUT:
7993 /* Nothing we can do. */
7996 /* Discard the two bytes of checksum and stop. */
7997 c = readchar (remote_timeout);
7999 c = readchar (remote_timeout);
8002 case '*': /* Run length encoding. */
8003 /* Discard the repeat count. */
8004 c = readchar (remote_timeout);
8009 /* A regular character. */
8015 /* Come here after finding the start of the frame. Collect the rest
8016 into *BUF, verifying the checksum, length, and handling run-length
8017 compression. NUL terminate the buffer. If there is not enough room,
8018 expand *BUF using xrealloc.
8020 Returns -1 on error, number of characters in buffer (ignoring the
8021 trailing NULL) on success. (could be extended to return one of the
8022 SERIAL status indications). */
8025 read_frame (char **buf_p,
8032 struct remote_state *rs = get_remote_state ();
8039 c = readchar (remote_timeout);
8042 case SERIAL_TIMEOUT:
8044 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8048 fputs_filtered ("Saw new packet start in middle of old one\n",
8050 return -1; /* Start a new packet, count retries. */
8053 unsigned char pktcsum;
8059 check_0 = readchar (remote_timeout);
8061 check_1 = readchar (remote_timeout);
8063 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8066 fputs_filtered ("Timeout in checksum, retrying\n",
8070 else if (check_0 < 0 || check_1 < 0)
8073 fputs_filtered ("Communication error in checksum\n",
8078 /* Don't recompute the checksum; with no ack packets we
8079 don't have any way to indicate a packet retransmission
8084 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8085 if (csum == pktcsum)
8090 struct cleanup *old_chain;
8093 str = escape_buffer (buf, bc);
8094 old_chain = make_cleanup (xfree, str);
8095 fprintf_unfiltered (gdb_stdlog,
8096 "Bad checksum, sentsum=0x%x, "
8097 "csum=0x%x, buf=%s\n",
8098 pktcsum, csum, str);
8099 do_cleanups (old_chain);
8101 /* Number of characters in buffer ignoring trailing
8105 case '*': /* Run length encoding. */
8110 c = readchar (remote_timeout);
8112 repeat = c - ' ' + 3; /* Compute repeat count. */
8114 /* The character before ``*'' is repeated. */
8116 if (repeat > 0 && repeat <= 255 && bc > 0)
8118 if (bc + repeat - 1 >= *sizeof_buf - 1)
8120 /* Make some more room in the buffer. */
8121 *sizeof_buf += repeat;
8122 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8126 memset (&buf[bc], buf[bc - 1], repeat);
8132 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8136 if (bc >= *sizeof_buf - 1)
8138 /* Make some more room in the buffer. */
8140 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8151 /* Read a packet from the remote machine, with error checking, and
8152 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8153 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8154 rather than timing out; this is used (in synchronous mode) to wait
8155 for a target that is is executing user code to stop. */
8156 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8157 don't have to change all the calls to getpkt to deal with the
8158 return value, because at the moment I don't know what the right
8159 thing to do it for those. */
8167 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8171 /* Read a packet from the remote machine, with error checking, and
8172 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8173 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8174 rather than timing out; this is used (in synchronous mode) to wait
8175 for a target that is is executing user code to stop. If FOREVER ==
8176 0, this function is allowed to time out gracefully and return an
8177 indication of this to the caller. Otherwise return the number of
8178 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8179 enough reason to return to the caller. *IS_NOTIF is an output
8180 boolean that indicates whether *BUF holds a notification or not
8181 (a regular packet). */
8184 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8185 int expecting_notif, int *is_notif)
8187 struct remote_state *rs = get_remote_state ();
8193 /* We're reading a new response. Make sure we don't look at a
8194 previously cached response. */
8195 rs->cached_wait_status = 0;
8197 strcpy (*buf, "timeout");
8200 timeout = watchdog > 0 ? watchdog : -1;
8201 else if (expecting_notif)
8202 timeout = 0; /* There should already be a char in the buffer. If
8205 timeout = remote_timeout;
8209 /* Process any number of notifications, and then return when
8213 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8215 for (tries = 1; tries <= MAX_TRIES; tries++)
8217 /* This can loop forever if the remote side sends us
8218 characters continuously, but if it pauses, we'll get
8219 SERIAL_TIMEOUT from readchar because of timeout. Then
8220 we'll count that as a retry.
8222 Note that even when forever is set, we will only wait
8223 forever prior to the start of a packet. After that, we
8224 expect characters to arrive at a brisk pace. They should
8225 show up within remote_timeout intervals. */
8227 c = readchar (timeout);
8228 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8230 if (c == SERIAL_TIMEOUT)
8232 if (expecting_notif)
8233 return -1; /* Don't complain, it's normal to not get
8234 anything in this case. */
8236 if (forever) /* Watchdog went off? Kill the target. */
8239 remote_unpush_target ();
8240 throw_error (TARGET_CLOSE_ERROR,
8241 _("Watchdog timeout has expired. "
8242 "Target detached."));
8245 fputs_filtered ("Timed out.\n", gdb_stdlog);
8249 /* We've found the start of a packet or notification.
8250 Now collect the data. */
8251 val = read_frame (buf, sizeof_buf);
8256 remote_serial_write ("-", 1);
8259 if (tries > MAX_TRIES)
8261 /* We have tried hard enough, and just can't receive the
8262 packet/notification. Give up. */
8263 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8265 /* Skip the ack char if we're in no-ack mode. */
8266 if (!rs->noack_mode)
8267 remote_serial_write ("+", 1);
8271 /* If we got an ordinary packet, return that to our caller. */
8276 struct cleanup *old_chain;
8279 str = escape_buffer (*buf, val);
8280 old_chain = make_cleanup (xfree, str);
8281 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8282 do_cleanups (old_chain);
8285 /* Skip the ack char if we're in no-ack mode. */
8286 if (!rs->noack_mode)
8287 remote_serial_write ("+", 1);
8288 if (is_notif != NULL)
8293 /* If we got a notification, handle it, and go back to looking
8297 gdb_assert (c == '%');
8301 struct cleanup *old_chain;
8304 str = escape_buffer (*buf, val);
8305 old_chain = make_cleanup (xfree, str);
8306 fprintf_unfiltered (gdb_stdlog,
8307 " Notification received: %s\n",
8309 do_cleanups (old_chain);
8311 if (is_notif != NULL)
8314 handle_notification (rs->notif_state, *buf);
8316 /* Notifications require no acknowledgement. */
8318 if (expecting_notif)
8325 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8327 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8331 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8334 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8338 /* Check whether EVENT is a fork event for the process specified
8339 by the pid passed in DATA, and if it is, kill the fork child. */
8342 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8343 QUEUE_ITER (stop_reply_p) *iter,
8347 struct queue_iter_param *param = data;
8348 int parent_pid = *(int *) param->input;
8350 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8352 struct remote_state *rs = get_remote_state ();
8353 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8356 res = remote_vkill (child_pid, rs);
8358 error (_("Can't kill fork child process %d"), child_pid);
8364 /* Kill any new fork children of process PID that haven't been
8365 processed by follow_fork. */
8368 kill_new_fork_children (int pid, struct remote_state *rs)
8370 struct thread_info *thread;
8371 struct notif_client *notif = ¬if_client_stop;
8372 struct queue_iter_param param;
8374 /* Kill the fork child threads of any threads in process PID
8375 that are stopped at a fork event. */
8376 ALL_NON_EXITED_THREADS (thread)
8378 struct target_waitstatus *ws = &thread->pending_follow;
8380 if (is_pending_fork_parent (ws, pid, thread->ptid))
8382 struct remote_state *rs = get_remote_state ();
8383 int child_pid = ptid_get_pid (ws->value.related_pid);
8386 res = remote_vkill (child_pid, rs);
8388 error (_("Can't kill fork child process %d"), child_pid);
8392 /* Check for any pending fork events (not reported or processed yet)
8393 in process PID and kill those fork child threads as well. */
8394 remote_notif_get_pending_events (notif);
8396 param.output = NULL;
8397 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8398 kill_child_of_pending_fork, ¶m);
8403 remote_kill (struct target_ops *ops)
8406 /* Catch errors so the user can quit from gdb even when we
8407 aren't on speaking terms with the remote system. */
8412 CATCH (ex, RETURN_MASK_ERROR)
8414 if (ex.error == TARGET_CLOSE_ERROR)
8416 /* If we got an (EOF) error that caused the target
8417 to go away, then we're done, that's what we wanted.
8418 "k" is susceptible to cause a premature EOF, given
8419 that the remote server isn't actually required to
8420 reply to "k", and it can happen that it doesn't
8421 even get to reply ACK to the "k". */
8425 /* Otherwise, something went wrong. We didn't actually kill
8426 the target. Just propagate the exception, and let the
8427 user or higher layers decide what to do. */
8428 throw_exception (ex);
8432 /* We've killed the remote end, we get to mourn it. Since this is
8433 target remote, single-process, mourning the inferior also
8434 unpushes remote_ops. */
8435 target_mourn_inferior ();
8439 remote_vkill (int pid, struct remote_state *rs)
8441 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8444 /* Tell the remote target to detach. */
8445 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8447 getpkt (&rs->buf, &rs->buf_size, 0);
8449 switch (packet_ok (rs->buf,
8450 &remote_protocol_packets[PACKET_vKill]))
8456 case PACKET_UNKNOWN:
8459 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8464 extended_remote_kill (struct target_ops *ops)
8467 int pid = ptid_get_pid (inferior_ptid);
8468 struct remote_state *rs = get_remote_state ();
8470 /* If we're stopped while forking and we haven't followed yet, kill the
8471 child task. We need to do this before killing the parent task
8472 because if this is a vfork then the parent will be sleeping. */
8473 kill_new_fork_children (pid, rs);
8475 res = remote_vkill (pid, rs);
8476 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8478 /* Don't try 'k' on a multi-process aware stub -- it has no way
8479 to specify the pid. */
8483 getpkt (&rs->buf, &rs->buf_size, 0);
8484 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8487 /* Don't wait for it to die. I'm not really sure it matters whether
8488 we do or not. For the existing stubs, kill is a noop. */
8494 error (_("Can't kill process"));
8496 target_mourn_inferior ();
8500 remote_mourn (struct target_ops *target)
8502 unpush_target (target);
8504 /* remote_close takes care of doing most of the clean up. */
8505 generic_mourn_inferior ();
8509 extended_remote_mourn (struct target_ops *target)
8511 struct remote_state *rs = get_remote_state ();
8513 /* In case we got here due to an error, but we're going to stay
8515 rs->waiting_for_stop_reply = 0;
8517 /* If the current general thread belonged to the process we just
8518 detached from or has exited, the remote side current general
8519 thread becomes undefined. Considering a case like this:
8521 - We just got here due to a detach.
8522 - The process that we're detaching from happens to immediately
8523 report a global breakpoint being hit in non-stop mode, in the
8524 same thread we had selected before.
8525 - GDB attaches to this process again.
8526 - This event happens to be the next event we handle.
8528 GDB would consider that the current general thread didn't need to
8529 be set on the stub side (with Hg), since for all it knew,
8530 GENERAL_THREAD hadn't changed.
8532 Notice that although in all-stop mode, the remote server always
8533 sets the current thread to the thread reporting the stop event,
8534 that doesn't happen in non-stop mode; in non-stop, the stub *must
8535 not* change the current thread when reporting a breakpoint hit,
8536 due to the decoupling of event reporting and event handling.
8538 To keep things simple, we always invalidate our notion of the
8540 record_currthread (rs, minus_one_ptid);
8542 /* Unlike "target remote", we do not want to unpush the target; then
8543 the next time the user says "run", we won't be connected. */
8545 /* Call common code to mark the inferior as not running. */
8546 generic_mourn_inferior ();
8548 if (!have_inferiors ())
8550 if (!remote_multi_process_p (rs))
8552 /* Check whether the target is running now - some remote stubs
8553 automatically restart after kill. */
8555 getpkt (&rs->buf, &rs->buf_size, 0);
8557 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8559 /* Assume that the target has been restarted. Set
8560 inferior_ptid so that bits of core GDB realizes
8561 there's something here, e.g., so that the user can
8562 say "kill" again. */
8563 inferior_ptid = magic_null_ptid;
8570 extended_remote_supports_disable_randomization (struct target_ops *self)
8572 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8576 extended_remote_disable_randomization (int val)
8578 struct remote_state *rs = get_remote_state ();
8581 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8584 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8586 error (_("Target does not support QDisableRandomization."));
8587 if (strcmp (reply, "OK") != 0)
8588 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8592 extended_remote_run (char *args)
8594 struct remote_state *rs = get_remote_state ();
8597 /* If the user has disabled vRun support, or we have detected that
8598 support is not available, do not try it. */
8599 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8602 strcpy (rs->buf, "vRun;");
8603 len = strlen (rs->buf);
8605 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8606 error (_("Remote file name too long for run packet"));
8607 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8608 strlen (remote_exec_file));
8610 gdb_assert (args != NULL);
8613 struct cleanup *back_to;
8617 argv = gdb_buildargv (args);
8618 back_to = make_cleanup_freeargv (argv);
8619 for (i = 0; argv[i] != NULL; i++)
8621 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8622 error (_("Argument list too long for run packet"));
8623 rs->buf[len++] = ';';
8624 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8627 do_cleanups (back_to);
8630 rs->buf[len++] = '\0';
8633 getpkt (&rs->buf, &rs->buf_size, 0);
8635 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8638 /* We have a wait response. All is well. */
8640 case PACKET_UNKNOWN:
8643 if (remote_exec_file[0] == '\0')
8644 error (_("Running the default executable on the remote target failed; "
8645 "try \"set remote exec-file\"?"));
8647 error (_("Running \"%s\" on the remote target failed"),
8650 gdb_assert_not_reached (_("bad switch"));
8654 /* In the extended protocol we want to be able to do things like
8655 "run" and have them basically work as expected. So we need
8656 a special create_inferior function. We support changing the
8657 executable file and the command line arguments, but not the
8661 extended_remote_create_inferior (struct target_ops *ops,
8662 char *exec_file, char *args,
8663 char **env, int from_tty)
8667 struct remote_state *rs = get_remote_state ();
8669 /* If running asynchronously, register the target file descriptor
8670 with the event loop. */
8671 if (target_can_async_p ())
8674 /* Disable address space randomization if requested (and supported). */
8675 if (extended_remote_supports_disable_randomization (ops))
8676 extended_remote_disable_randomization (disable_randomization);
8678 /* Now restart the remote server. */
8679 run_worked = extended_remote_run (args) != -1;
8682 /* vRun was not supported. Fail if we need it to do what the
8684 if (remote_exec_file[0])
8685 error (_("Remote target does not support \"set remote exec-file\""));
8687 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8689 /* Fall back to "R". */
8690 extended_remote_restart ();
8693 if (!have_inferiors ())
8695 /* Clean up from the last time we ran, before we mark the target
8696 running again. This will mark breakpoints uninserted, and
8697 get_offsets may insert breakpoints. */
8698 init_thread_list ();
8699 init_wait_for_inferior ();
8702 /* vRun's success return is a stop reply. */
8703 stop_reply = run_worked ? rs->buf : NULL;
8704 add_current_inferior_and_thread (stop_reply);
8706 /* Get updated offsets, if the stub uses qOffsets. */
8711 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8712 the list of conditions (in agent expression bytecode format), if any, the
8713 target needs to evaluate. The output is placed into the packet buffer
8714 started from BUF and ended at BUF_END. */
8717 remote_add_target_side_condition (struct gdbarch *gdbarch,
8718 struct bp_target_info *bp_tgt, char *buf,
8721 struct agent_expr *aexpr = NULL;
8724 char *buf_start = buf;
8726 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8729 buf += strlen (buf);
8730 xsnprintf (buf, buf_end - buf, "%s", ";");
8733 /* Send conditions to the target and free the vector. */
8735 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8738 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8739 buf += strlen (buf);
8740 for (i = 0; i < aexpr->len; ++i)
8741 buf = pack_hex_byte (buf, aexpr->buf[i]);
8748 remote_add_target_side_commands (struct gdbarch *gdbarch,
8749 struct bp_target_info *bp_tgt, char *buf)
8751 struct agent_expr *aexpr = NULL;
8754 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8757 buf += strlen (buf);
8759 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8760 buf += strlen (buf);
8762 /* Concatenate all the agent expressions that are commands into the
8765 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8768 sprintf (buf, "X%x,", aexpr->len);
8769 buf += strlen (buf);
8770 for (i = 0; i < aexpr->len; ++i)
8771 buf = pack_hex_byte (buf, aexpr->buf[i]);
8776 /* Insert a breakpoint. On targets that have software breakpoint
8777 support, we ask the remote target to do the work; on targets
8778 which don't, we insert a traditional memory breakpoint. */
8781 remote_insert_breakpoint (struct target_ops *ops,
8782 struct gdbarch *gdbarch,
8783 struct bp_target_info *bp_tgt)
8785 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8786 If it succeeds, then set the support to PACKET_ENABLE. If it
8787 fails, and the user has explicitly requested the Z support then
8788 report an error, otherwise, mark it disabled and go on. */
8790 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8792 CORE_ADDR addr = bp_tgt->reqstd_address;
8793 struct remote_state *rs;
8796 struct condition_list *cond = NULL;
8798 /* Make sure the remote is pointing at the right process, if
8800 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8801 set_general_process ();
8803 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8805 rs = get_remote_state ();
8807 endbuf = rs->buf + get_remote_packet_size ();
8812 addr = (ULONGEST) remote_address_masked (addr);
8813 p += hexnumstr (p, addr);
8814 xsnprintf (p, endbuf - p, ",%d", bpsize);
8816 if (remote_supports_cond_breakpoints (ops))
8817 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8819 if (remote_can_run_breakpoint_commands (ops))
8820 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8823 getpkt (&rs->buf, &rs->buf_size, 0);
8825 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8830 bp_tgt->placed_address = addr;
8831 bp_tgt->placed_size = bpsize;
8833 case PACKET_UNKNOWN:
8838 /* If this breakpoint has target-side commands but this stub doesn't
8839 support Z0 packets, throw error. */
8840 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8841 throw_error (NOT_SUPPORTED_ERROR, _("\
8842 Target doesn't support breakpoints that have target side commands."));
8844 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8848 remote_remove_breakpoint (struct target_ops *ops,
8849 struct gdbarch *gdbarch,
8850 struct bp_target_info *bp_tgt)
8852 CORE_ADDR addr = bp_tgt->placed_address;
8853 struct remote_state *rs = get_remote_state ();
8855 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8858 char *endbuf = rs->buf + get_remote_packet_size ();
8860 /* Make sure the remote is pointing at the right process, if
8862 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8863 set_general_process ();
8869 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8870 p += hexnumstr (p, addr);
8871 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8874 getpkt (&rs->buf, &rs->buf_size, 0);
8876 return (rs->buf[0] == 'E');
8879 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8882 static enum Z_packet_type
8883 watchpoint_to_Z_packet (int type)
8888 return Z_PACKET_WRITE_WP;
8891 return Z_PACKET_READ_WP;
8894 return Z_PACKET_ACCESS_WP;
8897 internal_error (__FILE__, __LINE__,
8898 _("hw_bp_to_z: bad watchpoint type %d"), type);
8903 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8904 enum target_hw_bp_type type, struct expression *cond)
8906 struct remote_state *rs = get_remote_state ();
8907 char *endbuf = rs->buf + get_remote_packet_size ();
8909 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8911 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8914 /* Make sure the remote is pointing at the right process, if
8916 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8917 set_general_process ();
8919 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8920 p = strchr (rs->buf, '\0');
8921 addr = remote_address_masked (addr);
8922 p += hexnumstr (p, (ULONGEST) addr);
8923 xsnprintf (p, endbuf - p, ",%x", len);
8926 getpkt (&rs->buf, &rs->buf_size, 0);
8928 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8932 case PACKET_UNKNOWN:
8937 internal_error (__FILE__, __LINE__,
8938 _("remote_insert_watchpoint: reached end of function"));
8942 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8943 CORE_ADDR start, int length)
8945 CORE_ADDR diff = remote_address_masked (addr - start);
8947 return diff < length;
8952 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8953 enum target_hw_bp_type type, struct expression *cond)
8955 struct remote_state *rs = get_remote_state ();
8956 char *endbuf = rs->buf + get_remote_packet_size ();
8958 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8960 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8963 /* Make sure the remote is pointing at the right process, if
8965 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8966 set_general_process ();
8968 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8969 p = strchr (rs->buf, '\0');
8970 addr = remote_address_masked (addr);
8971 p += hexnumstr (p, (ULONGEST) addr);
8972 xsnprintf (p, endbuf - p, ",%x", len);
8974 getpkt (&rs->buf, &rs->buf_size, 0);
8976 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8979 case PACKET_UNKNOWN:
8984 internal_error (__FILE__, __LINE__,
8985 _("remote_remove_watchpoint: reached end of function"));
8989 int remote_hw_watchpoint_limit = -1;
8990 int remote_hw_watchpoint_length_limit = -1;
8991 int remote_hw_breakpoint_limit = -1;
8994 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8995 CORE_ADDR addr, int len)
8997 if (remote_hw_watchpoint_length_limit == 0)
8999 else if (remote_hw_watchpoint_length_limit < 0)
9001 else if (len <= remote_hw_watchpoint_length_limit)
9008 remote_check_watch_resources (struct target_ops *self,
9009 enum bptype type, int cnt, int ot)
9011 if (type == bp_hardware_breakpoint)
9013 if (remote_hw_breakpoint_limit == 0)
9015 else if (remote_hw_breakpoint_limit < 0)
9017 else if (cnt <= remote_hw_breakpoint_limit)
9022 if (remote_hw_watchpoint_limit == 0)
9024 else if (remote_hw_watchpoint_limit < 0)
9028 else if (cnt <= remote_hw_watchpoint_limit)
9034 /* The to_stopped_by_sw_breakpoint method of target remote. */
9037 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9039 struct remote_state *rs = get_remote_state ();
9041 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9044 /* The to_supports_stopped_by_sw_breakpoint method of target
9048 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9050 struct remote_state *rs = get_remote_state ();
9052 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9055 /* The to_stopped_by_hw_breakpoint method of target remote. */
9058 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9060 struct remote_state *rs = get_remote_state ();
9062 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9065 /* The to_supports_stopped_by_hw_breakpoint method of target
9069 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9071 struct remote_state *rs = get_remote_state ();
9073 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9077 remote_stopped_by_watchpoint (struct target_ops *ops)
9079 struct remote_state *rs = get_remote_state ();
9081 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
9085 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9087 struct remote_state *rs = get_remote_state ();
9090 if (remote_stopped_by_watchpoint (target))
9092 *addr_p = rs->remote_watch_data_address;
9101 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9102 struct bp_target_info *bp_tgt)
9104 CORE_ADDR addr = bp_tgt->reqstd_address;
9105 struct remote_state *rs;
9110 /* The length field should be set to the size of a breakpoint
9111 instruction, even though we aren't inserting one ourselves. */
9113 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9115 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9118 /* Make sure the remote is pointing at the right process, if
9120 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9121 set_general_process ();
9123 rs = get_remote_state ();
9125 endbuf = rs->buf + get_remote_packet_size ();
9131 addr = remote_address_masked (addr);
9132 p += hexnumstr (p, (ULONGEST) addr);
9133 xsnprintf (p, endbuf - p, ",%x", bpsize);
9135 if (remote_supports_cond_breakpoints (self))
9136 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9138 if (remote_can_run_breakpoint_commands (self))
9139 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9142 getpkt (&rs->buf, &rs->buf_size, 0);
9144 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9147 if (rs->buf[1] == '.')
9149 message = strchr (rs->buf + 2, '.');
9151 error (_("Remote failure reply: %s"), message + 1);
9154 case PACKET_UNKNOWN:
9157 bp_tgt->placed_address = addr;
9158 bp_tgt->placed_size = bpsize;
9161 internal_error (__FILE__, __LINE__,
9162 _("remote_insert_hw_breakpoint: reached end of function"));
9167 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9168 struct bp_target_info *bp_tgt)
9171 struct remote_state *rs = get_remote_state ();
9173 char *endbuf = rs->buf + get_remote_packet_size ();
9175 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9178 /* Make sure the remote is pointing at the right process, if
9180 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9181 set_general_process ();
9187 addr = remote_address_masked (bp_tgt->placed_address);
9188 p += hexnumstr (p, (ULONGEST) addr);
9189 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9192 getpkt (&rs->buf, &rs->buf_size, 0);
9194 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9197 case PACKET_UNKNOWN:
9202 internal_error (__FILE__, __LINE__,
9203 _("remote_remove_hw_breakpoint: reached end of function"));
9206 /* Verify memory using the "qCRC:" request. */
9209 remote_verify_memory (struct target_ops *ops,
9210 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9212 struct remote_state *rs = get_remote_state ();
9213 unsigned long host_crc, target_crc;
9216 /* It doesn't make sense to use qCRC if the remote target is
9217 connected but not running. */
9218 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9220 enum packet_result result;
9222 /* Make sure the remote is pointing at the right process. */
9223 set_general_process ();
9225 /* FIXME: assumes lma can fit into long. */
9226 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9227 (long) lma, (long) size);
9230 /* Be clever; compute the host_crc before waiting for target
9232 host_crc = xcrc32 (data, size, 0xffffffff);
9234 getpkt (&rs->buf, &rs->buf_size, 0);
9236 result = packet_ok (rs->buf,
9237 &remote_protocol_packets[PACKET_qCRC]);
9238 if (result == PACKET_ERROR)
9240 else if (result == PACKET_OK)
9242 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9243 target_crc = target_crc * 16 + fromhex (*tmp);
9245 return (host_crc == target_crc);
9249 return simple_verify_memory (ops, data, lma, size);
9252 /* compare-sections command
9254 With no arguments, compares each loadable section in the exec bfd
9255 with the same memory range on the target, and reports mismatches.
9256 Useful for verifying the image on the target against the exec file. */
9259 compare_sections_command (char *args, int from_tty)
9262 struct cleanup *old_chain;
9264 const char *sectname;
9273 error (_("command cannot be used without an exec file"));
9275 /* Make sure the remote is pointing at the right process. */
9276 set_general_process ();
9278 if (args != NULL && strcmp (args, "-r") == 0)
9284 for (s = exec_bfd->sections; s; s = s->next)
9286 if (!(s->flags & SEC_LOAD))
9287 continue; /* Skip non-loadable section. */
9289 if (read_only && (s->flags & SEC_READONLY) == 0)
9290 continue; /* Skip writeable sections */
9292 size = bfd_get_section_size (s);
9294 continue; /* Skip zero-length section. */
9296 sectname = bfd_get_section_name (exec_bfd, s);
9297 if (args && strcmp (args, sectname) != 0)
9298 continue; /* Not the section selected by user. */
9300 matched = 1; /* Do this section. */
9303 sectdata = xmalloc (size);
9304 old_chain = make_cleanup (xfree, sectdata);
9305 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9307 res = target_verify_memory (sectdata, lma, size);
9310 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9311 paddress (target_gdbarch (), lma),
9312 paddress (target_gdbarch (), lma + size));
9314 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9315 paddress (target_gdbarch (), lma),
9316 paddress (target_gdbarch (), lma + size));
9318 printf_filtered ("matched.\n");
9321 printf_filtered ("MIS-MATCHED!\n");
9325 do_cleanups (old_chain);
9328 warning (_("One or more sections of the target image does not match\n\
9329 the loaded file\n"));
9330 if (args && !matched)
9331 printf_filtered (_("No loaded section named '%s'.\n"), args);
9334 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9335 into remote target. The number of bytes written to the remote
9336 target is returned, or -1 for error. */
9338 static enum target_xfer_status
9339 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9340 const char *annex, const gdb_byte *writebuf,
9341 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9342 struct packet_config *packet)
9346 struct remote_state *rs = get_remote_state ();
9347 int max_size = get_memory_write_packet_size ();
9349 if (packet->support == PACKET_DISABLE)
9350 return TARGET_XFER_E_IO;
9352 /* Insert header. */
9353 i = snprintf (rs->buf, max_size,
9354 "qXfer:%s:write:%s:%s:",
9355 object_name, annex ? annex : "",
9356 phex_nz (offset, sizeof offset));
9357 max_size -= (i + 1);
9359 /* Escape as much data as fits into rs->buf. */
9360 buf_len = remote_escape_output
9361 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9363 if (putpkt_binary (rs->buf, i + buf_len) < 0
9364 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9365 || packet_ok (rs->buf, packet) != PACKET_OK)
9366 return TARGET_XFER_E_IO;
9368 unpack_varlen_hex (rs->buf, &n);
9371 return TARGET_XFER_OK;
9374 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9375 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9376 number of bytes read is returned, or 0 for EOF, or -1 for error.
9377 The number of bytes read may be less than LEN without indicating an
9378 EOF. PACKET is checked and updated to indicate whether the remote
9379 target supports this object. */
9381 static enum target_xfer_status
9382 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9384 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9385 ULONGEST *xfered_len,
9386 struct packet_config *packet)
9388 struct remote_state *rs = get_remote_state ();
9389 LONGEST i, n, packet_len;
9391 if (packet->support == PACKET_DISABLE)
9392 return TARGET_XFER_E_IO;
9394 /* Check whether we've cached an end-of-object packet that matches
9396 if (rs->finished_object)
9398 if (strcmp (object_name, rs->finished_object) == 0
9399 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9400 && offset == rs->finished_offset)
9401 return TARGET_XFER_EOF;
9404 /* Otherwise, we're now reading something different. Discard
9406 xfree (rs->finished_object);
9407 xfree (rs->finished_annex);
9408 rs->finished_object = NULL;
9409 rs->finished_annex = NULL;
9412 /* Request only enough to fit in a single packet. The actual data
9413 may not, since we don't know how much of it will need to be escaped;
9414 the target is free to respond with slightly less data. We subtract
9415 five to account for the response type and the protocol frame. */
9416 n = min (get_remote_packet_size () - 5, len);
9417 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9418 object_name, annex ? annex : "",
9419 phex_nz (offset, sizeof offset),
9420 phex_nz (n, sizeof n));
9421 i = putpkt (rs->buf);
9423 return TARGET_XFER_E_IO;
9426 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9427 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9428 return TARGET_XFER_E_IO;
9430 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9431 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9433 /* 'm' means there is (or at least might be) more data after this
9434 batch. That does not make sense unless there's at least one byte
9435 of data in this reply. */
9436 if (rs->buf[0] == 'm' && packet_len == 1)
9437 error (_("Remote qXfer reply contained no data."));
9439 /* Got some data. */
9440 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9441 packet_len - 1, readbuf, n);
9443 /* 'l' is an EOF marker, possibly including a final block of data,
9444 or possibly empty. If we have the final block of a non-empty
9445 object, record this fact to bypass a subsequent partial read. */
9446 if (rs->buf[0] == 'l' && offset + i > 0)
9448 rs->finished_object = xstrdup (object_name);
9449 rs->finished_annex = xstrdup (annex ? annex : "");
9450 rs->finished_offset = offset + i;
9454 return TARGET_XFER_EOF;
9458 return TARGET_XFER_OK;
9462 static enum target_xfer_status
9463 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9464 const char *annex, gdb_byte *readbuf,
9465 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9466 ULONGEST *xfered_len)
9468 struct remote_state *rs;
9472 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9474 set_remote_traceframe ();
9475 set_general_thread (inferior_ptid);
9477 rs = get_remote_state ();
9479 /* Handle memory using the standard memory routines. */
9480 if (object == TARGET_OBJECT_MEMORY)
9482 /* If the remote target is connected but not running, we should
9483 pass this request down to a lower stratum (e.g. the executable
9485 if (!target_has_execution)
9486 return TARGET_XFER_EOF;
9488 if (writebuf != NULL)
9489 return remote_write_bytes (offset, writebuf, len, unit_size,
9492 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9496 /* Handle SPU memory using qxfer packets. */
9497 if (object == TARGET_OBJECT_SPU)
9500 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9501 xfered_len, &remote_protocol_packets
9502 [PACKET_qXfer_spu_read]);
9504 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9505 xfered_len, &remote_protocol_packets
9506 [PACKET_qXfer_spu_write]);
9509 /* Handle extra signal info using qxfer packets. */
9510 if (object == TARGET_OBJECT_SIGNAL_INFO)
9513 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9514 xfered_len, &remote_protocol_packets
9515 [PACKET_qXfer_siginfo_read]);
9517 return remote_write_qxfer (ops, "siginfo", annex,
9518 writebuf, offset, len, xfered_len,
9519 &remote_protocol_packets
9520 [PACKET_qXfer_siginfo_write]);
9523 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9526 return remote_read_qxfer (ops, "statictrace", annex,
9527 readbuf, offset, len, xfered_len,
9528 &remote_protocol_packets
9529 [PACKET_qXfer_statictrace_read]);
9531 return TARGET_XFER_E_IO;
9534 /* Only handle flash writes. */
9535 if (writebuf != NULL)
9541 case TARGET_OBJECT_FLASH:
9542 return remote_flash_write (ops, offset, len, xfered_len,
9546 return TARGET_XFER_E_IO;
9550 /* Map pre-existing objects onto letters. DO NOT do this for new
9551 objects!!! Instead specify new query packets. */
9554 case TARGET_OBJECT_AVR:
9558 case TARGET_OBJECT_AUXV:
9559 gdb_assert (annex == NULL);
9560 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9562 &remote_protocol_packets[PACKET_qXfer_auxv]);
9564 case TARGET_OBJECT_AVAILABLE_FEATURES:
9565 return remote_read_qxfer
9566 (ops, "features", annex, readbuf, offset, len, xfered_len,
9567 &remote_protocol_packets[PACKET_qXfer_features]);
9569 case TARGET_OBJECT_LIBRARIES:
9570 return remote_read_qxfer
9571 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9572 &remote_protocol_packets[PACKET_qXfer_libraries]);
9574 case TARGET_OBJECT_LIBRARIES_SVR4:
9575 return remote_read_qxfer
9576 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9577 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9579 case TARGET_OBJECT_MEMORY_MAP:
9580 gdb_assert (annex == NULL);
9581 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9583 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9585 case TARGET_OBJECT_OSDATA:
9586 /* Should only get here if we're connected. */
9587 gdb_assert (rs->remote_desc);
9588 return remote_read_qxfer
9589 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9590 &remote_protocol_packets[PACKET_qXfer_osdata]);
9592 case TARGET_OBJECT_THREADS:
9593 gdb_assert (annex == NULL);
9594 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9596 &remote_protocol_packets[PACKET_qXfer_threads]);
9598 case TARGET_OBJECT_TRACEFRAME_INFO:
9599 gdb_assert (annex == NULL);
9600 return remote_read_qxfer
9601 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9602 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9604 case TARGET_OBJECT_FDPIC:
9605 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9607 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9609 case TARGET_OBJECT_OPENVMS_UIB:
9610 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9612 &remote_protocol_packets[PACKET_qXfer_uib]);
9614 case TARGET_OBJECT_BTRACE:
9615 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9617 &remote_protocol_packets[PACKET_qXfer_btrace]);
9619 case TARGET_OBJECT_BTRACE_CONF:
9620 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9622 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9624 case TARGET_OBJECT_EXEC_FILE:
9625 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9627 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9630 return TARGET_XFER_E_IO;
9633 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9634 large enough let the caller deal with it. */
9635 if (len < get_remote_packet_size ())
9636 return TARGET_XFER_E_IO;
9637 len = get_remote_packet_size ();
9639 /* Except for querying the minimum buffer size, target must be open. */
9640 if (!rs->remote_desc)
9641 error (_("remote query is only available after target open"));
9643 gdb_assert (annex != NULL);
9644 gdb_assert (readbuf != NULL);
9650 /* We used one buffer char for the remote protocol q command and
9651 another for the query type. As the remote protocol encapsulation
9652 uses 4 chars plus one extra in case we are debugging
9653 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9656 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9658 /* Bad caller may have sent forbidden characters. */
9659 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9664 gdb_assert (annex[i] == '\0');
9666 i = putpkt (rs->buf);
9668 return TARGET_XFER_E_IO;
9670 getpkt (&rs->buf, &rs->buf_size, 0);
9671 strcpy ((char *) readbuf, rs->buf);
9673 *xfered_len = strlen ((char *) readbuf);
9674 return TARGET_XFER_OK;
9678 remote_search_memory (struct target_ops* ops,
9679 CORE_ADDR start_addr, ULONGEST search_space_len,
9680 const gdb_byte *pattern, ULONGEST pattern_len,
9681 CORE_ADDR *found_addrp)
9683 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9684 struct remote_state *rs = get_remote_state ();
9685 int max_size = get_memory_write_packet_size ();
9686 struct packet_config *packet =
9687 &remote_protocol_packets[PACKET_qSearch_memory];
9688 /* Number of packet bytes used to encode the pattern;
9689 this could be more than PATTERN_LEN due to escape characters. */
9690 int escaped_pattern_len;
9691 /* Amount of pattern that was encodable in the packet. */
9692 int used_pattern_len;
9695 ULONGEST found_addr;
9697 /* Don't go to the target if we don't have to.
9698 This is done before checking packet->support to avoid the possibility that
9699 a success for this edge case means the facility works in general. */
9700 if (pattern_len > search_space_len)
9702 if (pattern_len == 0)
9704 *found_addrp = start_addr;
9708 /* If we already know the packet isn't supported, fall back to the simple
9709 way of searching memory. */
9711 if (packet_config_support (packet) == PACKET_DISABLE)
9713 /* Target doesn't provided special support, fall back and use the
9714 standard support (copy memory and do the search here). */
9715 return simple_search_memory (ops, start_addr, search_space_len,
9716 pattern, pattern_len, found_addrp);
9719 /* Make sure the remote is pointing at the right process. */
9720 set_general_process ();
9722 /* Insert header. */
9723 i = snprintf (rs->buf, max_size,
9724 "qSearch:memory:%s;%s;",
9725 phex_nz (start_addr, addr_size),
9726 phex_nz (search_space_len, sizeof (search_space_len)));
9727 max_size -= (i + 1);
9729 /* Escape as much data as fits into rs->buf. */
9730 escaped_pattern_len =
9731 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
9732 &used_pattern_len, max_size);
9734 /* Bail if the pattern is too large. */
9735 if (used_pattern_len != pattern_len)
9736 error (_("Pattern is too large to transmit to remote target."));
9738 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9739 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9740 || packet_ok (rs->buf, packet) != PACKET_OK)
9742 /* The request may not have worked because the command is not
9743 supported. If so, fall back to the simple way. */
9744 if (packet->support == PACKET_DISABLE)
9746 return simple_search_memory (ops, start_addr, search_space_len,
9747 pattern, pattern_len, found_addrp);
9752 if (rs->buf[0] == '0')
9754 else if (rs->buf[0] == '1')
9757 if (rs->buf[1] != ',')
9758 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9759 unpack_varlen_hex (rs->buf + 2, &found_addr);
9760 *found_addrp = found_addr;
9763 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9769 remote_rcmd (struct target_ops *self, const char *command,
9770 struct ui_file *outbuf)
9772 struct remote_state *rs = get_remote_state ();
9775 if (!rs->remote_desc)
9776 error (_("remote rcmd is only available after target open"));
9778 /* Send a NULL command across as an empty command. */
9779 if (command == NULL)
9782 /* The query prefix. */
9783 strcpy (rs->buf, "qRcmd,");
9784 p = strchr (rs->buf, '\0');
9786 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9787 > get_remote_packet_size ())
9788 error (_("\"monitor\" command ``%s'' is too long."), command);
9790 /* Encode the actual command. */
9791 bin2hex ((const gdb_byte *) command, p, strlen (command));
9793 if (putpkt (rs->buf) < 0)
9794 error (_("Communication problem with target."));
9796 /* get/display the response */
9801 /* XXX - see also remote_get_noisy_reply(). */
9802 QUIT; /* Allow user to bail out with ^C. */
9804 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9806 /* Timeout. Continue to (try to) read responses.
9807 This is better than stopping with an error, assuming the stub
9808 is still executing the (long) monitor command.
9809 If needed, the user can interrupt gdb using C-c, obtaining
9810 an effect similar to stop on timeout. */
9815 error (_("Target does not support this command."));
9816 if (buf[0] == 'O' && buf[1] != 'K')
9818 remote_console_output (buf + 1); /* 'O' message from stub. */
9821 if (strcmp (buf, "OK") == 0)
9823 if (strlen (buf) == 3 && buf[0] == 'E'
9824 && isdigit (buf[1]) && isdigit (buf[2]))
9826 error (_("Protocol error with Rcmd"));
9828 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9830 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9832 fputc_unfiltered (c, outbuf);
9838 static VEC(mem_region_s) *
9839 remote_memory_map (struct target_ops *ops)
9841 VEC(mem_region_s) *result = NULL;
9842 char *text = target_read_stralloc (¤t_target,
9843 TARGET_OBJECT_MEMORY_MAP, NULL);
9847 struct cleanup *back_to = make_cleanup (xfree, text);
9849 result = parse_memory_map (text);
9850 do_cleanups (back_to);
9857 packet_command (char *args, int from_tty)
9859 struct remote_state *rs = get_remote_state ();
9861 if (!rs->remote_desc)
9862 error (_("command can only be used with remote target"));
9865 error (_("remote-packet command requires packet text as argument"));
9867 puts_filtered ("sending: ");
9868 print_packet (args);
9869 puts_filtered ("\n");
9872 getpkt (&rs->buf, &rs->buf_size, 0);
9873 puts_filtered ("received: ");
9874 print_packet (rs->buf);
9875 puts_filtered ("\n");
9879 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9881 static void display_thread_info (struct gdb_ext_thread_info *info);
9883 static void threadset_test_cmd (char *cmd, int tty);
9885 static void threadalive_test (char *cmd, int tty);
9887 static void threadlist_test_cmd (char *cmd, int tty);
9889 int get_and_display_threadinfo (threadref *ref);
9891 static void threadinfo_test_cmd (char *cmd, int tty);
9893 static int thread_display_step (threadref *ref, void *context);
9895 static void threadlist_update_test_cmd (char *cmd, int tty);
9897 static void init_remote_threadtests (void);
9899 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9902 threadset_test_cmd (char *cmd, int tty)
9904 int sample_thread = SAMPLE_THREAD;
9906 printf_filtered (_("Remote threadset test\n"));
9907 set_general_thread (sample_thread);
9912 threadalive_test (char *cmd, int tty)
9914 int sample_thread = SAMPLE_THREAD;
9915 int pid = ptid_get_pid (inferior_ptid);
9916 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9918 if (remote_thread_alive (ptid))
9919 printf_filtered ("PASS: Thread alive test\n");
9921 printf_filtered ("FAIL: Thread alive test\n");
9924 void output_threadid (char *title, threadref *ref);
9927 output_threadid (char *title, threadref *ref)
9931 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9933 printf_filtered ("%s %s\n", title, (&hexid[0]));
9937 threadlist_test_cmd (char *cmd, int tty)
9940 threadref nextthread;
9941 int done, result_count;
9942 threadref threadlist[3];
9944 printf_filtered ("Remote Threadlist test\n");
9945 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9946 &result_count, &threadlist[0]))
9947 printf_filtered ("FAIL: threadlist test\n");
9950 threadref *scan = threadlist;
9951 threadref *limit = scan + result_count;
9953 while (scan < limit)
9954 output_threadid (" thread ", scan++);
9959 display_thread_info (struct gdb_ext_thread_info *info)
9961 output_threadid ("Threadid: ", &info->threadid);
9962 printf_filtered ("Name: %s\n ", info->shortname);
9963 printf_filtered ("State: %s\n", info->display);
9964 printf_filtered ("other: %s\n\n", info->more_display);
9968 get_and_display_threadinfo (threadref *ref)
9972 struct gdb_ext_thread_info threadinfo;
9974 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9975 | TAG_MOREDISPLAY | TAG_DISPLAY;
9976 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9977 display_thread_info (&threadinfo);
9982 threadinfo_test_cmd (char *cmd, int tty)
9984 int athread = SAMPLE_THREAD;
9988 int_to_threadref (&thread, athread);
9989 printf_filtered ("Remote Threadinfo test\n");
9990 if (!get_and_display_threadinfo (&thread))
9991 printf_filtered ("FAIL cannot get thread info\n");
9995 thread_display_step (threadref *ref, void *context)
9997 /* output_threadid(" threadstep ",ref); *//* simple test */
9998 return get_and_display_threadinfo (ref);
10002 threadlist_update_test_cmd (char *cmd, int tty)
10004 printf_filtered ("Remote Threadlist update test\n");
10005 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10009 init_remote_threadtests (void)
10011 add_com ("tlist", class_obscure, threadlist_test_cmd,
10012 _("Fetch and print the remote list of "
10013 "thread identifiers, one pkt only"));
10014 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10015 _("Fetch and display info about one thread"));
10016 add_com ("tset", class_obscure, threadset_test_cmd,
10017 _("Test setting to a different thread"));
10018 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10019 _("Iterate through updating all remote thread info"));
10020 add_com ("talive", class_obscure, threadalive_test,
10021 _(" Remote thread alive test "));
10026 /* Convert a thread ID to a string. Returns the string in a static
10030 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10032 static char buf[64];
10033 struct remote_state *rs = get_remote_state ();
10035 if (ptid_equal (ptid, null_ptid))
10036 return normal_pid_to_str (ptid);
10037 else if (ptid_is_pid (ptid))
10039 /* Printing an inferior target id. */
10041 /* When multi-process extensions are off, there's no way in the
10042 remote protocol to know the remote process id, if there's any
10043 at all. There's one exception --- when we're connected with
10044 target extended-remote, and we manually attached to a process
10045 with "attach PID". We don't record anywhere a flag that
10046 allows us to distinguish that case from the case of
10047 connecting with extended-remote and the stub already being
10048 attached to a process, and reporting yes to qAttached, hence
10049 no smart special casing here. */
10050 if (!remote_multi_process_p (rs))
10052 xsnprintf (buf, sizeof buf, "Remote target");
10056 return normal_pid_to_str (ptid);
10060 if (ptid_equal (magic_null_ptid, ptid))
10061 xsnprintf (buf, sizeof buf, "Thread <main>");
10062 else if (rs->extended && remote_multi_process_p (rs))
10063 if (ptid_get_lwp (ptid) == 0)
10064 return normal_pid_to_str (ptid);
10066 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10067 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10069 xsnprintf (buf, sizeof buf, "Thread %ld",
10070 ptid_get_lwp (ptid));
10075 /* Get the address of the thread local variable in OBJFILE which is
10076 stored at OFFSET within the thread local storage for thread PTID. */
10079 remote_get_thread_local_address (struct target_ops *ops,
10080 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10082 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10084 struct remote_state *rs = get_remote_state ();
10086 char *endp = rs->buf + get_remote_packet_size ();
10087 enum packet_result result;
10089 strcpy (p, "qGetTLSAddr:");
10091 p = write_ptid (p, endp, ptid);
10093 p += hexnumstr (p, offset);
10095 p += hexnumstr (p, lm);
10099 getpkt (&rs->buf, &rs->buf_size, 0);
10100 result = packet_ok (rs->buf,
10101 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10102 if (result == PACKET_OK)
10106 unpack_varlen_hex (rs->buf, &result);
10109 else if (result == PACKET_UNKNOWN)
10110 throw_error (TLS_GENERIC_ERROR,
10111 _("Remote target doesn't support qGetTLSAddr packet"));
10113 throw_error (TLS_GENERIC_ERROR,
10114 _("Remote target failed to process qGetTLSAddr request"));
10117 throw_error (TLS_GENERIC_ERROR,
10118 _("TLS not supported or disabled on this target"));
10123 /* Provide thread local base, i.e. Thread Information Block address.
10124 Returns 1 if ptid is found and thread_local_base is non zero. */
10127 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10129 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10131 struct remote_state *rs = get_remote_state ();
10133 char *endp = rs->buf + get_remote_packet_size ();
10134 enum packet_result result;
10136 strcpy (p, "qGetTIBAddr:");
10138 p = write_ptid (p, endp, ptid);
10142 getpkt (&rs->buf, &rs->buf_size, 0);
10143 result = packet_ok (rs->buf,
10144 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10145 if (result == PACKET_OK)
10149 unpack_varlen_hex (rs->buf, &result);
10151 *addr = (CORE_ADDR) result;
10154 else if (result == PACKET_UNKNOWN)
10155 error (_("Remote target doesn't support qGetTIBAddr packet"));
10157 error (_("Remote target failed to process qGetTIBAddr request"));
10160 error (_("qGetTIBAddr not supported or disabled on this target"));
10165 /* Support for inferring a target description based on the current
10166 architecture and the size of a 'g' packet. While the 'g' packet
10167 can have any size (since optional registers can be left off the
10168 end), some sizes are easily recognizable given knowledge of the
10169 approximate architecture. */
10171 struct remote_g_packet_guess
10174 const struct target_desc *tdesc;
10176 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10177 DEF_VEC_O(remote_g_packet_guess_s);
10179 struct remote_g_packet_data
10181 VEC(remote_g_packet_guess_s) *guesses;
10184 static struct gdbarch_data *remote_g_packet_data_handle;
10187 remote_g_packet_data_init (struct obstack *obstack)
10189 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10193 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10194 const struct target_desc *tdesc)
10196 struct remote_g_packet_data *data
10197 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10198 struct remote_g_packet_guess new_guess, *guess;
10201 gdb_assert (tdesc != NULL);
10204 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10206 if (guess->bytes == bytes)
10207 internal_error (__FILE__, __LINE__,
10208 _("Duplicate g packet description added for size %d"),
10211 new_guess.bytes = bytes;
10212 new_guess.tdesc = tdesc;
10213 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10216 /* Return 1 if remote_read_description would do anything on this target
10217 and architecture, 0 otherwise. */
10220 remote_read_description_p (struct target_ops *target)
10222 struct remote_g_packet_data *data
10223 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10225 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10231 static const struct target_desc *
10232 remote_read_description (struct target_ops *target)
10234 struct remote_g_packet_data *data
10235 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10237 /* Do not try this during initial connection, when we do not know
10238 whether there is a running but stopped thread. */
10239 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10240 return target->beneath->to_read_description (target->beneath);
10242 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10244 struct remote_g_packet_guess *guess;
10246 int bytes = send_g_packet ();
10249 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10251 if (guess->bytes == bytes)
10252 return guess->tdesc;
10254 /* We discard the g packet. A minor optimization would be to
10255 hold on to it, and fill the register cache once we have selected
10256 an architecture, but it's too tricky to do safely. */
10259 return target->beneath->to_read_description (target->beneath);
10262 /* Remote file transfer support. This is host-initiated I/O, not
10263 target-initiated; for target-initiated, see remote-fileio.c. */
10265 /* If *LEFT is at least the length of STRING, copy STRING to
10266 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10267 decrease *LEFT. Otherwise raise an error. */
10270 remote_buffer_add_string (char **buffer, int *left, char *string)
10272 int len = strlen (string);
10275 error (_("Packet too long for target."));
10277 memcpy (*buffer, string, len);
10281 /* NUL-terminate the buffer as a convenience, if there is
10287 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10288 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10289 decrease *LEFT. Otherwise raise an error. */
10292 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10295 if (2 * len > *left)
10296 error (_("Packet too long for target."));
10298 bin2hex (bytes, *buffer, len);
10299 *buffer += 2 * len;
10302 /* NUL-terminate the buffer as a convenience, if there is
10308 /* If *LEFT is large enough, convert VALUE to hex and add it to
10309 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10310 decrease *LEFT. Otherwise raise an error. */
10313 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10315 int len = hexnumlen (value);
10318 error (_("Packet too long for target."));
10320 hexnumstr (*buffer, value);
10324 /* NUL-terminate the buffer as a convenience, if there is
10330 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10331 value, *REMOTE_ERRNO to the remote error number or zero if none
10332 was included, and *ATTACHMENT to point to the start of the annex
10333 if any. The length of the packet isn't needed here; there may
10334 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10336 Return 0 if the packet could be parsed, -1 if it could not. If
10337 -1 is returned, the other variables may not be initialized. */
10340 remote_hostio_parse_result (char *buffer, int *retcode,
10341 int *remote_errno, char **attachment)
10346 *attachment = NULL;
10348 if (buffer[0] != 'F')
10352 *retcode = strtol (&buffer[1], &p, 16);
10353 if (errno != 0 || p == &buffer[1])
10356 /* Check for ",errno". */
10360 *remote_errno = strtol (p + 1, &p2, 16);
10361 if (errno != 0 || p + 1 == p2)
10366 /* Check for ";attachment". If there is no attachment, the
10367 packet should end here. */
10370 *attachment = p + 1;
10373 else if (*p == '\0')
10379 /* Send a prepared I/O packet to the target and read its response.
10380 The prepared packet is in the global RS->BUF before this function
10381 is called, and the answer is there when we return.
10383 COMMAND_BYTES is the length of the request to send, which may include
10384 binary data. WHICH_PACKET is the packet configuration to check
10385 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10386 is set to the error number and -1 is returned. Otherwise the value
10387 returned by the function is returned.
10389 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10390 attachment is expected; an error will be reported if there's a
10391 mismatch. If one is found, *ATTACHMENT will be set to point into
10392 the packet buffer and *ATTACHMENT_LEN will be set to the
10393 attachment's length. */
10396 remote_hostio_send_command (int command_bytes, int which_packet,
10397 int *remote_errno, char **attachment,
10398 int *attachment_len)
10400 struct remote_state *rs = get_remote_state ();
10401 int ret, bytes_read;
10402 char *attachment_tmp;
10404 if (!rs->remote_desc
10405 || packet_support (which_packet) == PACKET_DISABLE)
10407 *remote_errno = FILEIO_ENOSYS;
10411 putpkt_binary (rs->buf, command_bytes);
10412 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10414 /* If it timed out, something is wrong. Don't try to parse the
10416 if (bytes_read < 0)
10418 *remote_errno = FILEIO_EINVAL;
10422 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10425 *remote_errno = FILEIO_EINVAL;
10427 case PACKET_UNKNOWN:
10428 *remote_errno = FILEIO_ENOSYS;
10434 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10437 *remote_errno = FILEIO_EINVAL;
10441 /* Make sure we saw an attachment if and only if we expected one. */
10442 if ((attachment_tmp == NULL && attachment != NULL)
10443 || (attachment_tmp != NULL && attachment == NULL))
10445 *remote_errno = FILEIO_EINVAL;
10449 /* If an attachment was found, it must point into the packet buffer;
10450 work out how many bytes there were. */
10451 if (attachment_tmp != NULL)
10453 *attachment = attachment_tmp;
10454 *attachment_len = bytes_read - (*attachment - rs->buf);
10460 /* Invalidate the readahead cache. */
10463 readahead_cache_invalidate (void)
10465 struct remote_state *rs = get_remote_state ();
10467 rs->readahead_cache.fd = -1;
10470 /* Invalidate the readahead cache if it is holding data for FD. */
10473 readahead_cache_invalidate_fd (int fd)
10475 struct remote_state *rs = get_remote_state ();
10477 if (rs->readahead_cache.fd == fd)
10478 rs->readahead_cache.fd = -1;
10481 /* Set the filesystem remote_hostio functions that take FILENAME
10482 arguments will use. Return 0 on success, or -1 if an error
10483 occurs (and set *REMOTE_ERRNO). */
10486 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10488 struct remote_state *rs = get_remote_state ();
10489 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10491 int left = get_remote_packet_size () - 1;
10495 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10498 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10501 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10503 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10504 remote_buffer_add_string (&p, &left, arg);
10506 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10507 remote_errno, NULL, NULL);
10509 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10513 rs->fs_pid = required_pid;
10518 /* Implementation of to_fileio_open. */
10521 remote_hostio_open (struct target_ops *self,
10522 struct inferior *inf, const char *filename,
10523 int flags, int mode, int warn_if_slow,
10526 struct remote_state *rs = get_remote_state ();
10528 int left = get_remote_packet_size () - 1;
10532 static int warning_issued = 0;
10534 printf_unfiltered (_("Reading %s from remote target...\n"),
10537 if (!warning_issued)
10539 warning (_("File transfers from remote targets can be slow."
10540 " Use \"set sysroot\" to access files locally"
10542 warning_issued = 1;
10546 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10549 remote_buffer_add_string (&p, &left, "vFile:open:");
10551 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10552 strlen (filename));
10553 remote_buffer_add_string (&p, &left, ",");
10555 remote_buffer_add_int (&p, &left, flags);
10556 remote_buffer_add_string (&p, &left, ",");
10558 remote_buffer_add_int (&p, &left, mode);
10560 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10561 remote_errno, NULL, NULL);
10564 /* Implementation of to_fileio_pwrite. */
10567 remote_hostio_pwrite (struct target_ops *self,
10568 int fd, const gdb_byte *write_buf, int len,
10569 ULONGEST offset, int *remote_errno)
10571 struct remote_state *rs = get_remote_state ();
10573 int left = get_remote_packet_size ();
10576 readahead_cache_invalidate_fd (fd);
10578 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10580 remote_buffer_add_int (&p, &left, fd);
10581 remote_buffer_add_string (&p, &left, ",");
10583 remote_buffer_add_int (&p, &left, offset);
10584 remote_buffer_add_string (&p, &left, ",");
10586 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10587 get_remote_packet_size () - (p - rs->buf));
10589 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10590 remote_errno, NULL, NULL);
10593 /* Helper for the implementation of to_fileio_pread. Read the file
10594 from the remote side with vFile:pread. */
10597 remote_hostio_pread_vFile (struct target_ops *self,
10598 int fd, gdb_byte *read_buf, int len,
10599 ULONGEST offset, int *remote_errno)
10601 struct remote_state *rs = get_remote_state ();
10604 int left = get_remote_packet_size ();
10605 int ret, attachment_len;
10608 remote_buffer_add_string (&p, &left, "vFile:pread:");
10610 remote_buffer_add_int (&p, &left, fd);
10611 remote_buffer_add_string (&p, &left, ",");
10613 remote_buffer_add_int (&p, &left, len);
10614 remote_buffer_add_string (&p, &left, ",");
10616 remote_buffer_add_int (&p, &left, offset);
10618 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10619 remote_errno, &attachment,
10625 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10627 if (read_len != ret)
10628 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10633 /* Serve pread from the readahead cache. Returns number of bytes
10634 read, or 0 if the request can't be served from the cache. */
10637 remote_hostio_pread_from_cache (struct remote_state *rs,
10638 int fd, gdb_byte *read_buf, size_t len,
10641 struct readahead_cache *cache = &rs->readahead_cache;
10643 if (cache->fd == fd
10644 && cache->offset <= offset
10645 && offset < cache->offset + cache->bufsize)
10647 ULONGEST max = cache->offset + cache->bufsize;
10649 if (offset + len > max)
10650 len = max - offset;
10652 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10659 /* Implementation of to_fileio_pread. */
10662 remote_hostio_pread (struct target_ops *self,
10663 int fd, gdb_byte *read_buf, int len,
10664 ULONGEST offset, int *remote_errno)
10667 struct remote_state *rs = get_remote_state ();
10668 struct readahead_cache *cache = &rs->readahead_cache;
10670 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10673 cache->hit_count++;
10676 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10677 pulongest (cache->hit_count));
10681 cache->miss_count++;
10683 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10684 pulongest (cache->miss_count));
10687 cache->offset = offset;
10688 cache->bufsize = get_remote_packet_size ();
10689 cache->buf = xrealloc (cache->buf, cache->bufsize);
10691 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10692 cache->offset, remote_errno);
10695 readahead_cache_invalidate_fd (fd);
10699 cache->bufsize = ret;
10700 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10703 /* Implementation of to_fileio_close. */
10706 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
10708 struct remote_state *rs = get_remote_state ();
10710 int left = get_remote_packet_size () - 1;
10712 readahead_cache_invalidate_fd (fd);
10714 remote_buffer_add_string (&p, &left, "vFile:close:");
10716 remote_buffer_add_int (&p, &left, fd);
10718 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10719 remote_errno, NULL, NULL);
10722 /* Implementation of to_fileio_unlink. */
10725 remote_hostio_unlink (struct target_ops *self,
10726 struct inferior *inf, const char *filename,
10729 struct remote_state *rs = get_remote_state ();
10731 int left = get_remote_packet_size () - 1;
10733 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10736 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10738 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10739 strlen (filename));
10741 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10742 remote_errno, NULL, NULL);
10745 /* Implementation of to_fileio_readlink. */
10748 remote_hostio_readlink (struct target_ops *self,
10749 struct inferior *inf, const char *filename,
10752 struct remote_state *rs = get_remote_state ();
10755 int left = get_remote_packet_size ();
10756 int len, attachment_len;
10760 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10763 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10765 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10766 strlen (filename));
10768 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10769 remote_errno, &attachment,
10775 ret = xmalloc (len + 1);
10777 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10778 (gdb_byte *) ret, len);
10779 if (read_len != len)
10780 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10786 /* Implementation of to_fileio_fstat. */
10789 remote_hostio_fstat (struct target_ops *self,
10790 int fd, struct stat *st,
10793 struct remote_state *rs = get_remote_state ();
10795 int left = get_remote_packet_size ();
10796 int attachment_len, ret;
10798 struct fio_stat fst;
10801 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10803 remote_buffer_add_int (&p, &left, fd);
10805 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10806 remote_errno, &attachment,
10810 if (*remote_errno != FILEIO_ENOSYS)
10813 /* Strictly we should return -1, ENOSYS here, but when
10814 "set sysroot remote:" was implemented in August 2008
10815 BFD's need for a stat function was sidestepped with
10816 this hack. This was not remedied until March 2015
10817 so we retain the previous behavior to avoid breaking
10820 Note that the memset is a March 2015 addition; older
10821 GDBs set st_size *and nothing else* so the structure
10822 would have garbage in all other fields. This might
10823 break something but retaining the previous behavior
10824 here would be just too wrong. */
10826 memset (st, 0, sizeof (struct stat));
10827 st->st_size = INT_MAX;
10831 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10832 (gdb_byte *) &fst, sizeof (fst));
10834 if (read_len != ret)
10835 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10837 if (read_len != sizeof (fst))
10838 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10839 read_len, (int) sizeof (fst));
10841 remote_fileio_to_host_stat (&fst, st);
10846 /* Implementation of to_filesystem_is_local. */
10849 remote_filesystem_is_local (struct target_ops *self)
10851 /* Valgrind GDB presents itself as a remote target but works
10852 on the local filesystem: it does not implement remote get
10853 and users are not expected to set a sysroot. To handle
10854 this case we treat the remote filesystem as local if the
10855 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10856 does not support vFile:open. */
10857 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
10859 enum packet_support ps = packet_support (PACKET_vFile_open);
10861 if (ps == PACKET_SUPPORT_UNKNOWN)
10863 int fd, remote_errno;
10865 /* Try opening a file to probe support. The supplied
10866 filename is irrelevant, we only care about whether
10867 the stub recognizes the packet or not. */
10868 fd = remote_hostio_open (self, NULL, "just probing",
10869 FILEIO_O_RDONLY, 0700, 0,
10873 remote_hostio_close (self, fd, &remote_errno);
10875 ps = packet_support (PACKET_vFile_open);
10878 if (ps == PACKET_DISABLE)
10880 static int warning_issued = 0;
10882 if (!warning_issued)
10884 warning (_("remote target does not support file"
10885 " transfer, attempting to access files"
10886 " from local filesystem."));
10887 warning_issued = 1;
10898 remote_fileio_errno_to_host (int errnum)
10904 case FILEIO_ENOENT:
10912 case FILEIO_EACCES:
10914 case FILEIO_EFAULT:
10918 case FILEIO_EEXIST:
10920 case FILEIO_ENODEV:
10922 case FILEIO_ENOTDIR:
10924 case FILEIO_EISDIR:
10926 case FILEIO_EINVAL:
10928 case FILEIO_ENFILE:
10930 case FILEIO_EMFILE:
10934 case FILEIO_ENOSPC:
10936 case FILEIO_ESPIPE:
10940 case FILEIO_ENOSYS:
10942 case FILEIO_ENAMETOOLONG:
10943 return ENAMETOOLONG;
10949 remote_hostio_error (int errnum)
10951 int host_error = remote_fileio_errno_to_host (errnum);
10953 if (host_error == -1)
10954 error (_("Unknown remote I/O error %d"), errnum);
10956 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10960 remote_hostio_close_cleanup (void *opaque)
10962 int fd = *(int *) opaque;
10965 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10969 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10971 struct cleanup *back_to, *close_cleanup;
10972 int retcode, fd, remote_errno, bytes, io_size;
10975 int bytes_in_buffer;
10978 struct remote_state *rs = get_remote_state ();
10980 if (!rs->remote_desc)
10981 error (_("command can only be used with remote target"));
10983 file = gdb_fopen_cloexec (local_file, "rb");
10985 perror_with_name (local_file);
10986 back_to = make_cleanup_fclose (file);
10988 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
10989 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10991 0700, 0, &remote_errno);
10993 remote_hostio_error (remote_errno);
10995 /* Send up to this many bytes at once. They won't all fit in the
10996 remote packet limit, so we'll transfer slightly fewer. */
10997 io_size = get_remote_packet_size ();
10998 buffer = xmalloc (io_size);
10999 make_cleanup (xfree, buffer);
11001 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11003 bytes_in_buffer = 0;
11006 while (bytes_in_buffer || !saw_eof)
11010 bytes = fread (buffer + bytes_in_buffer, 1,
11011 io_size - bytes_in_buffer,
11016 error (_("Error reading %s."), local_file);
11019 /* EOF. Unless there is something still in the
11020 buffer from the last iteration, we are done. */
11022 if (bytes_in_buffer == 0)
11030 bytes += bytes_in_buffer;
11031 bytes_in_buffer = 0;
11033 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11035 offset, &remote_errno);
11038 remote_hostio_error (remote_errno);
11039 else if (retcode == 0)
11040 error (_("Remote write of %d bytes returned 0!"), bytes);
11041 else if (retcode < bytes)
11043 /* Short write. Save the rest of the read data for the next
11045 bytes_in_buffer = bytes - retcode;
11046 memmove (buffer, buffer + retcode, bytes_in_buffer);
11052 discard_cleanups (close_cleanup);
11053 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11054 remote_hostio_error (remote_errno);
11057 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11058 do_cleanups (back_to);
11062 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11064 struct cleanup *back_to, *close_cleanup;
11065 int fd, remote_errno, bytes, io_size;
11069 struct remote_state *rs = get_remote_state ();
11071 if (!rs->remote_desc)
11072 error (_("command can only be used with remote target"));
11074 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11075 remote_file, FILEIO_O_RDONLY, 0, 0,
11078 remote_hostio_error (remote_errno);
11080 file = gdb_fopen_cloexec (local_file, "wb");
11082 perror_with_name (local_file);
11083 back_to = make_cleanup_fclose (file);
11085 /* Send up to this many bytes at once. They won't all fit in the
11086 remote packet limit, so we'll transfer slightly fewer. */
11087 io_size = get_remote_packet_size ();
11088 buffer = xmalloc (io_size);
11089 make_cleanup (xfree, buffer);
11091 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11096 bytes = remote_hostio_pread (find_target_at (process_stratum),
11097 fd, buffer, io_size, offset, &remote_errno);
11099 /* Success, but no bytes, means end-of-file. */
11102 remote_hostio_error (remote_errno);
11106 bytes = fwrite (buffer, 1, bytes, file);
11108 perror_with_name (local_file);
11111 discard_cleanups (close_cleanup);
11112 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11113 remote_hostio_error (remote_errno);
11116 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11117 do_cleanups (back_to);
11121 remote_file_delete (const char *remote_file, int from_tty)
11123 int retcode, remote_errno;
11124 struct remote_state *rs = get_remote_state ();
11126 if (!rs->remote_desc)
11127 error (_("command can only be used with remote target"));
11129 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11130 NULL, remote_file, &remote_errno);
11132 remote_hostio_error (remote_errno);
11135 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11139 remote_put_command (char *args, int from_tty)
11141 struct cleanup *back_to;
11145 error_no_arg (_("file to put"));
11147 argv = gdb_buildargv (args);
11148 back_to = make_cleanup_freeargv (argv);
11149 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11150 error (_("Invalid parameters to remote put"));
11152 remote_file_put (argv[0], argv[1], from_tty);
11154 do_cleanups (back_to);
11158 remote_get_command (char *args, int from_tty)
11160 struct cleanup *back_to;
11164 error_no_arg (_("file to get"));
11166 argv = gdb_buildargv (args);
11167 back_to = make_cleanup_freeargv (argv);
11168 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11169 error (_("Invalid parameters to remote get"));
11171 remote_file_get (argv[0], argv[1], from_tty);
11173 do_cleanups (back_to);
11177 remote_delete_command (char *args, int from_tty)
11179 struct cleanup *back_to;
11183 error_no_arg (_("file to delete"));
11185 argv = gdb_buildargv (args);
11186 back_to = make_cleanup_freeargv (argv);
11187 if (argv[0] == NULL || argv[1] != NULL)
11188 error (_("Invalid parameters to remote delete"));
11190 remote_file_delete (argv[0], from_tty);
11192 do_cleanups (back_to);
11196 remote_command (char *args, int from_tty)
11198 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11202 remote_can_execute_reverse (struct target_ops *self)
11204 if (packet_support (PACKET_bs) == PACKET_ENABLE
11205 || packet_support (PACKET_bc) == PACKET_ENABLE)
11212 remote_supports_non_stop (struct target_ops *self)
11218 remote_supports_disable_randomization (struct target_ops *self)
11220 /* Only supported in extended mode. */
11225 remote_supports_multi_process (struct target_ops *self)
11227 struct remote_state *rs = get_remote_state ();
11229 /* Only extended-remote handles being attached to multiple
11230 processes, even though plain remote can use the multi-process
11231 thread id extensions, so that GDB knows the target process's
11233 return rs->extended && remote_multi_process_p (rs);
11237 remote_supports_cond_tracepoints (void)
11239 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11243 remote_supports_cond_breakpoints (struct target_ops *self)
11245 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11249 remote_supports_fast_tracepoints (void)
11251 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11255 remote_supports_static_tracepoints (void)
11257 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11261 remote_supports_install_in_trace (void)
11263 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11267 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11269 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11274 remote_supports_string_tracing (struct target_ops *self)
11276 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11280 remote_can_run_breakpoint_commands (struct target_ops *self)
11282 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11286 remote_trace_init (struct target_ops *self)
11289 remote_get_noisy_reply (&target_buf, &target_buf_size);
11290 if (strcmp (target_buf, "OK") != 0)
11291 error (_("Target does not support this command."));
11294 static void free_actions_list (char **actions_list);
11295 static void free_actions_list_cleanup_wrapper (void *);
11297 free_actions_list_cleanup_wrapper (void *al)
11299 free_actions_list (al);
11303 free_actions_list (char **actions_list)
11307 if (actions_list == 0)
11310 for (ndx = 0; actions_list[ndx]; ndx++)
11311 xfree (actions_list[ndx]);
11313 xfree (actions_list);
11316 /* Recursive routine to walk through command list including loops, and
11317 download packets for each command. */
11320 remote_download_command_source (int num, ULONGEST addr,
11321 struct command_line *cmds)
11323 struct remote_state *rs = get_remote_state ();
11324 struct command_line *cmd;
11326 for (cmd = cmds; cmd; cmd = cmd->next)
11328 QUIT; /* Allow user to bail out with ^C. */
11329 strcpy (rs->buf, "QTDPsrc:");
11330 encode_source_string (num, addr, "cmd", cmd->line,
11331 rs->buf + strlen (rs->buf),
11332 rs->buf_size - strlen (rs->buf));
11334 remote_get_noisy_reply (&target_buf, &target_buf_size);
11335 if (strcmp (target_buf, "OK"))
11336 warning (_("Target does not support source download."));
11338 if (cmd->control_type == while_control
11339 || cmd->control_type == while_stepping_control)
11341 remote_download_command_source (num, addr, *cmd->body_list);
11343 QUIT; /* Allow user to bail out with ^C. */
11344 strcpy (rs->buf, "QTDPsrc:");
11345 encode_source_string (num, addr, "cmd", "end",
11346 rs->buf + strlen (rs->buf),
11347 rs->buf_size - strlen (rs->buf));
11349 remote_get_noisy_reply (&target_buf, &target_buf_size);
11350 if (strcmp (target_buf, "OK"))
11351 warning (_("Target does not support source download."));
11357 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11359 #define BUF_SIZE 2048
11363 char buf[BUF_SIZE];
11364 char **tdp_actions;
11365 char **stepping_actions;
11367 struct cleanup *old_chain = NULL;
11368 struct agent_expr *aexpr;
11369 struct cleanup *aexpr_chain = NULL;
11371 struct breakpoint *b = loc->owner;
11372 struct tracepoint *t = (struct tracepoint *) b;
11374 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11375 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11377 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11380 tpaddr = loc->address;
11381 sprintf_vma (addrbuf, tpaddr);
11382 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11383 addrbuf, /* address */
11384 (b->enable_state == bp_enabled ? 'E' : 'D'),
11385 t->step_count, t->pass_count);
11386 /* Fast tracepoints are mostly handled by the target, but we can
11387 tell the target how big of an instruction block should be moved
11389 if (b->type == bp_fast_tracepoint)
11391 /* Only test for support at download time; we may not know
11392 target capabilities at definition time. */
11393 if (remote_supports_fast_tracepoints ())
11395 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11397 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11398 gdb_insn_length (loc->gdbarch, tpaddr));
11400 /* If it passed validation at definition but fails now,
11401 something is very wrong. */
11402 internal_error (__FILE__, __LINE__,
11403 _("Fast tracepoint not "
11404 "valid during download"));
11407 /* Fast tracepoints are functionally identical to regular
11408 tracepoints, so don't take lack of support as a reason to
11409 give up on the trace run. */
11410 warning (_("Target does not support fast tracepoints, "
11411 "downloading %d as regular tracepoint"), b->number);
11413 else if (b->type == bp_static_tracepoint)
11415 /* Only test for support at download time; we may not know
11416 target capabilities at definition time. */
11417 if (remote_supports_static_tracepoints ())
11419 struct static_tracepoint_marker marker;
11421 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11422 strcat (buf, ":S");
11424 error (_("Static tracepoint not valid during download"));
11427 /* Fast tracepoints are functionally identical to regular
11428 tracepoints, so don't take lack of support as a reason
11429 to give up on the trace run. */
11430 error (_("Target does not support static tracepoints"));
11432 /* If the tracepoint has a conditional, make it into an agent
11433 expression and append to the definition. */
11436 /* Only test support at download time, we may not know target
11437 capabilities at definition time. */
11438 if (remote_supports_cond_tracepoints ())
11440 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11441 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11442 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11444 pkt = buf + strlen (buf);
11445 for (ndx = 0; ndx < aexpr->len; ++ndx)
11446 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11448 do_cleanups (aexpr_chain);
11451 warning (_("Target does not support conditional tracepoints, "
11452 "ignoring tp %d cond"), b->number);
11455 if (b->commands || *default_collect)
11458 remote_get_noisy_reply (&target_buf, &target_buf_size);
11459 if (strcmp (target_buf, "OK"))
11460 error (_("Target does not support tracepoints."));
11462 /* do_single_steps (t); */
11465 for (ndx = 0; tdp_actions[ndx]; ndx++)
11467 QUIT; /* Allow user to bail out with ^C. */
11468 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11469 b->number, addrbuf, /* address */
11471 ((tdp_actions[ndx + 1] || stepping_actions)
11474 remote_get_noisy_reply (&target_buf,
11476 if (strcmp (target_buf, "OK"))
11477 error (_("Error on target while setting tracepoints."));
11480 if (stepping_actions)
11482 for (ndx = 0; stepping_actions[ndx]; ndx++)
11484 QUIT; /* Allow user to bail out with ^C. */
11485 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11486 b->number, addrbuf, /* address */
11487 ((ndx == 0) ? "S" : ""),
11488 stepping_actions[ndx],
11489 (stepping_actions[ndx + 1] ? "-" : ""));
11491 remote_get_noisy_reply (&target_buf,
11493 if (strcmp (target_buf, "OK"))
11494 error (_("Error on target while setting tracepoints."));
11498 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11500 if (b->location != NULL)
11502 strcpy (buf, "QTDPsrc:");
11503 encode_source_string (b->number, loc->address, "at",
11504 event_location_to_string (b->location),
11505 buf + strlen (buf), 2048 - strlen (buf));
11507 remote_get_noisy_reply (&target_buf, &target_buf_size);
11508 if (strcmp (target_buf, "OK"))
11509 warning (_("Target does not support source download."));
11511 if (b->cond_string)
11513 strcpy (buf, "QTDPsrc:");
11514 encode_source_string (b->number, loc->address,
11515 "cond", b->cond_string, buf + strlen (buf),
11516 2048 - strlen (buf));
11518 remote_get_noisy_reply (&target_buf, &target_buf_size);
11519 if (strcmp (target_buf, "OK"))
11520 warning (_("Target does not support source download."));
11522 remote_download_command_source (b->number, loc->address,
11523 breakpoint_commands (b));
11526 do_cleanups (old_chain);
11530 remote_can_download_tracepoint (struct target_ops *self)
11532 struct remote_state *rs = get_remote_state ();
11533 struct trace_status *ts;
11536 /* Don't try to install tracepoints until we've relocated our
11537 symbols, and fetched and merged the target's tracepoint list with
11539 if (rs->starting_up)
11542 ts = current_trace_status ();
11543 status = remote_get_trace_status (self, ts);
11545 if (status == -1 || !ts->running_known || !ts->running)
11548 /* If we are in a tracing experiment, but remote stub doesn't support
11549 installing tracepoint in trace, we have to return. */
11550 if (!remote_supports_install_in_trace ())
11558 remote_download_trace_state_variable (struct target_ops *self,
11559 struct trace_state_variable *tsv)
11561 struct remote_state *rs = get_remote_state ();
11564 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11565 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11567 p = rs->buf + strlen (rs->buf);
11568 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11569 error (_("Trace state variable name too long for tsv definition packet"));
11570 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11573 remote_get_noisy_reply (&target_buf, &target_buf_size);
11574 if (*target_buf == '\0')
11575 error (_("Target does not support this command."));
11576 if (strcmp (target_buf, "OK") != 0)
11577 error (_("Error on target while downloading trace state variable."));
11581 remote_enable_tracepoint (struct target_ops *self,
11582 struct bp_location *location)
11584 struct remote_state *rs = get_remote_state ();
11587 sprintf_vma (addr_buf, location->address);
11588 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11589 location->owner->number, addr_buf);
11591 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11592 if (*rs->buf == '\0')
11593 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11594 if (strcmp (rs->buf, "OK") != 0)
11595 error (_("Error on target while enabling tracepoint."));
11599 remote_disable_tracepoint (struct target_ops *self,
11600 struct bp_location *location)
11602 struct remote_state *rs = get_remote_state ();
11605 sprintf_vma (addr_buf, location->address);
11606 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11607 location->owner->number, addr_buf);
11609 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11610 if (*rs->buf == '\0')
11611 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11612 if (strcmp (rs->buf, "OK") != 0)
11613 error (_("Error on target while disabling tracepoint."));
11617 remote_trace_set_readonly_regions (struct target_ops *self)
11621 bfd_size_type size;
11627 return; /* No information to give. */
11629 strcpy (target_buf, "QTro");
11630 offset = strlen (target_buf);
11631 for (s = exec_bfd->sections; s; s = s->next)
11633 char tmp1[40], tmp2[40];
11636 if ((s->flags & SEC_LOAD) == 0 ||
11637 /* (s->flags & SEC_CODE) == 0 || */
11638 (s->flags & SEC_READONLY) == 0)
11642 vma = bfd_get_section_vma (abfd, s);
11643 size = bfd_get_section_size (s);
11644 sprintf_vma (tmp1, vma);
11645 sprintf_vma (tmp2, vma + size);
11646 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11647 if (offset + sec_length + 1 > target_buf_size)
11649 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
11651 Too many sections for read-only sections definition packet."));
11654 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11656 offset += sec_length;
11660 putpkt (target_buf);
11661 getpkt (&target_buf, &target_buf_size, 0);
11666 remote_trace_start (struct target_ops *self)
11668 putpkt ("QTStart");
11669 remote_get_noisy_reply (&target_buf, &target_buf_size);
11670 if (*target_buf == '\0')
11671 error (_("Target does not support this command."));
11672 if (strcmp (target_buf, "OK") != 0)
11673 error (_("Bogus reply from target: %s"), target_buf);
11677 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11679 /* Initialize it just to avoid a GCC false warning. */
11681 /* FIXME we need to get register block size some other way. */
11682 extern int trace_regblock_size;
11683 enum packet_result result;
11685 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11688 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11690 putpkt ("qTStatus");
11694 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11696 CATCH (ex, RETURN_MASK_ERROR)
11698 if (ex.error != TARGET_CLOSE_ERROR)
11700 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11703 throw_exception (ex);
11707 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11709 /* If the remote target doesn't do tracing, flag it. */
11710 if (result == PACKET_UNKNOWN)
11713 /* We're working with a live target. */
11714 ts->filename = NULL;
11717 error (_("Bogus trace status reply from target: %s"), target_buf);
11719 /* Function 'parse_trace_status' sets default value of each field of
11720 'ts' at first, so we don't have to do it here. */
11721 parse_trace_status (p, ts);
11723 return ts->running;
11727 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
11728 struct uploaded_tp *utp)
11730 struct remote_state *rs = get_remote_state ();
11732 struct bp_location *loc;
11733 struct tracepoint *tp = (struct tracepoint *) bp;
11734 size_t size = get_remote_packet_size ();
11738 tp->base.hit_count = 0;
11739 tp->traceframe_usage = 0;
11740 for (loc = tp->base.loc; loc; loc = loc->next)
11742 /* If the tracepoint was never downloaded, don't go asking for
11744 if (tp->number_on_target == 0)
11746 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11747 phex_nz (loc->address, 0));
11749 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11750 if (reply && *reply)
11753 parse_tracepoint_status (reply + 1, bp, utp);
11759 utp->hit_count = 0;
11760 utp->traceframe_usage = 0;
11761 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11762 phex_nz (utp->addr, 0));
11764 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11765 if (reply && *reply)
11768 parse_tracepoint_status (reply + 1, bp, utp);
11774 remote_trace_stop (struct target_ops *self)
11777 remote_get_noisy_reply (&target_buf, &target_buf_size);
11778 if (*target_buf == '\0')
11779 error (_("Target does not support this command."));
11780 if (strcmp (target_buf, "OK") != 0)
11781 error (_("Bogus reply from target: %s"), target_buf);
11785 remote_trace_find (struct target_ops *self,
11786 enum trace_find_type type, int num,
11787 CORE_ADDR addr1, CORE_ADDR addr2,
11790 struct remote_state *rs = get_remote_state ();
11791 char *endbuf = rs->buf + get_remote_packet_size ();
11793 int target_frameno = -1, target_tracept = -1;
11795 /* Lookups other than by absolute frame number depend on the current
11796 trace selected, so make sure it is correct on the remote end
11798 if (type != tfind_number)
11799 set_remote_traceframe ();
11802 strcpy (p, "QTFrame:");
11803 p = strchr (p, '\0');
11807 xsnprintf (p, endbuf - p, "%x", num);
11810 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11813 xsnprintf (p, endbuf - p, "tdp:%x", num);
11816 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11817 phex_nz (addr2, 0));
11819 case tfind_outside:
11820 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11821 phex_nz (addr2, 0));
11824 error (_("Unknown trace find type %d"), type);
11828 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11829 if (*reply == '\0')
11830 error (_("Target does not support this command."));
11832 while (reply && *reply)
11837 target_frameno = (int) strtol (p, &reply, 16);
11839 error (_("Unable to parse trace frame number"));
11840 /* Don't update our remote traceframe number cache on failure
11841 to select a remote traceframe. */
11842 if (target_frameno == -1)
11847 target_tracept = (int) strtol (p, &reply, 16);
11849 error (_("Unable to parse tracepoint number"));
11851 case 'O': /* "OK"? */
11852 if (reply[1] == 'K' && reply[2] == '\0')
11855 error (_("Bogus reply from target: %s"), reply);
11858 error (_("Bogus reply from target: %s"), reply);
11861 *tpp = target_tracept;
11863 rs->remote_traceframe_number = target_frameno;
11864 return target_frameno;
11868 remote_get_trace_state_variable_value (struct target_ops *self,
11869 int tsvnum, LONGEST *val)
11871 struct remote_state *rs = get_remote_state ();
11875 set_remote_traceframe ();
11877 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11879 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11880 if (reply && *reply)
11884 unpack_varlen_hex (reply + 1, &uval);
11885 *val = (LONGEST) uval;
11893 remote_save_trace_data (struct target_ops *self, const char *filename)
11895 struct remote_state *rs = get_remote_state ();
11899 strcpy (p, "QTSave:");
11901 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11902 error (_("Remote file name too long for trace save packet"));
11903 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11906 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11907 if (*reply == '\0')
11908 error (_("Target does not support this command."));
11909 if (strcmp (reply, "OK") != 0)
11910 error (_("Bogus reply from target: %s"), reply);
11914 /* This is basically a memory transfer, but needs to be its own packet
11915 because we don't know how the target actually organizes its trace
11916 memory, plus we want to be able to ask for as much as possible, but
11917 not be unhappy if we don't get as much as we ask for. */
11920 remote_get_raw_trace_data (struct target_ops *self,
11921 gdb_byte *buf, ULONGEST offset, LONGEST len)
11923 struct remote_state *rs = get_remote_state ();
11929 strcpy (p, "qTBuffer:");
11931 p += hexnumstr (p, offset);
11933 p += hexnumstr (p, len);
11937 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11938 if (reply && *reply)
11940 /* 'l' by itself means we're at the end of the buffer and
11941 there is nothing more to get. */
11945 /* Convert the reply into binary. Limit the number of bytes to
11946 convert according to our passed-in buffer size, rather than
11947 what was returned in the packet; if the target is
11948 unexpectedly generous and gives us a bigger reply than we
11949 asked for, we don't want to crash. */
11950 rslt = hex2bin (target_buf, buf, len);
11954 /* Something went wrong, flag as an error. */
11959 remote_set_disconnected_tracing (struct target_ops *self, int val)
11961 struct remote_state *rs = get_remote_state ();
11963 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11967 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11969 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11970 if (*reply == '\0')
11971 error (_("Target does not support this command."));
11972 if (strcmp (reply, "OK") != 0)
11973 error (_("Bogus reply from target: %s"), reply);
11976 warning (_("Target does not support disconnected tracing."));
11980 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11982 struct thread_info *info = find_thread_ptid (ptid);
11984 if (info && info->priv)
11985 return info->priv->core;
11990 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11992 struct remote_state *rs = get_remote_state ();
11995 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11997 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11998 if (*reply == '\0')
11999 error (_("Target does not support this command."));
12000 if (strcmp (reply, "OK") != 0)
12001 error (_("Bogus reply from target: %s"), reply);
12004 static struct traceframe_info *
12005 remote_traceframe_info (struct target_ops *self)
12009 text = target_read_stralloc (¤t_target,
12010 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12013 struct traceframe_info *info;
12014 struct cleanup *back_to = make_cleanup (xfree, text);
12016 info = parse_traceframe_info (text);
12017 do_cleanups (back_to);
12024 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12025 instruction on which a fast tracepoint may be placed. Returns -1
12026 if the packet is not supported, and 0 if the minimum instruction
12027 length is unknown. */
12030 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12032 struct remote_state *rs = get_remote_state ();
12035 /* If we're not debugging a process yet, the IPA can't be
12037 if (!target_has_execution)
12040 /* Make sure the remote is pointing at the right process. */
12041 set_general_process ();
12043 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12045 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12046 if (*reply == '\0')
12050 ULONGEST min_insn_len;
12052 unpack_varlen_hex (reply, &min_insn_len);
12054 return (int) min_insn_len;
12059 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12061 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12063 struct remote_state *rs = get_remote_state ();
12064 char *buf = rs->buf;
12065 char *endbuf = rs->buf + get_remote_packet_size ();
12066 enum packet_result result;
12068 gdb_assert (val >= 0 || val == -1);
12069 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12070 /* Send -1 as literal "-1" to avoid host size dependency. */
12074 buf += hexnumstr (buf, (ULONGEST) -val);
12077 buf += hexnumstr (buf, (ULONGEST) val);
12080 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12081 result = packet_ok (rs->buf,
12082 &remote_protocol_packets[PACKET_QTBuffer_size]);
12084 if (result != PACKET_OK)
12085 warning (_("Bogus reply from target: %s"), rs->buf);
12090 remote_set_trace_notes (struct target_ops *self,
12091 const char *user, const char *notes,
12092 const char *stop_notes)
12094 struct remote_state *rs = get_remote_state ();
12096 char *buf = rs->buf;
12097 char *endbuf = rs->buf + get_remote_packet_size ();
12100 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12103 buf += xsnprintf (buf, endbuf - buf, "user:");
12104 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12110 buf += xsnprintf (buf, endbuf - buf, "notes:");
12111 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12117 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12118 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12122 /* Ensure the buffer is terminated. */
12126 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12127 if (*reply == '\0')
12130 if (strcmp (reply, "OK") != 0)
12131 error (_("Bogus reply from target: %s"), reply);
12137 remote_use_agent (struct target_ops *self, int use)
12139 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12141 struct remote_state *rs = get_remote_state ();
12143 /* If the stub supports QAgent. */
12144 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12146 getpkt (&rs->buf, &rs->buf_size, 0);
12148 if (strcmp (rs->buf, "OK") == 0)
12159 remote_can_use_agent (struct target_ops *self)
12161 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12164 struct btrace_target_info
12166 /* The ptid of the traced thread. */
12169 /* The obtained branch trace configuration. */
12170 struct btrace_config conf;
12173 /* Reset our idea of our target's btrace configuration. */
12176 remote_btrace_reset (void)
12178 struct remote_state *rs = get_remote_state ();
12180 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12183 /* Check whether the target supports branch tracing. */
12186 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12188 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12190 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12195 case BTRACE_FORMAT_NONE:
12198 case BTRACE_FORMAT_BTS:
12199 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12201 case BTRACE_FORMAT_PT:
12202 /* The trace is decoded on the host. Even if our target supports it,
12203 we still need to have libipt to decode the trace. */
12204 #if defined (HAVE_LIBIPT)
12205 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12206 #else /* !defined (HAVE_LIBIPT) */
12208 #endif /* !defined (HAVE_LIBIPT) */
12211 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12214 /* Synchronize the configuration with the target. */
12217 btrace_sync_conf (const struct btrace_config *conf)
12219 struct packet_config *packet;
12220 struct remote_state *rs;
12221 char *buf, *pos, *endbuf;
12223 rs = get_remote_state ();
12225 endbuf = buf + get_remote_packet_size ();
12227 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12228 if (packet_config_support (packet) == PACKET_ENABLE
12229 && conf->bts.size != rs->btrace_config.bts.size)
12232 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12236 getpkt (&buf, &rs->buf_size, 0);
12238 if (packet_ok (buf, packet) == PACKET_ERROR)
12240 if (buf[0] == 'E' && buf[1] == '.')
12241 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12243 error (_("Failed to configure the BTS buffer size."));
12246 rs->btrace_config.bts.size = conf->bts.size;
12249 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12250 if (packet_config_support (packet) == PACKET_ENABLE
12251 && conf->pt.size != rs->btrace_config.pt.size)
12254 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12258 getpkt (&buf, &rs->buf_size, 0);
12260 if (packet_ok (buf, packet) == PACKET_ERROR)
12262 if (buf[0] == 'E' && buf[1] == '.')
12263 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12265 error (_("Failed to configure the trace buffer size."));
12268 rs->btrace_config.pt.size = conf->pt.size;
12272 /* Read the current thread's btrace configuration from the target and
12273 store it into CONF. */
12276 btrace_read_config (struct btrace_config *conf)
12280 xml = target_read_stralloc (¤t_target,
12281 TARGET_OBJECT_BTRACE_CONF, "");
12284 struct cleanup *cleanup;
12286 cleanup = make_cleanup (xfree, xml);
12287 parse_xml_btrace_conf (conf, xml);
12288 do_cleanups (cleanup);
12292 /* Enable branch tracing. */
12294 static struct btrace_target_info *
12295 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12296 const struct btrace_config *conf)
12298 struct btrace_target_info *tinfo = NULL;
12299 struct packet_config *packet = NULL;
12300 struct remote_state *rs = get_remote_state ();
12301 char *buf = rs->buf;
12302 char *endbuf = rs->buf + get_remote_packet_size ();
12304 switch (conf->format)
12306 case BTRACE_FORMAT_BTS:
12307 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12310 case BTRACE_FORMAT_PT:
12311 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12315 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12316 error (_("Target does not support branch tracing."));
12318 btrace_sync_conf (conf);
12320 set_general_thread (ptid);
12322 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12324 getpkt (&rs->buf, &rs->buf_size, 0);
12326 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12328 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12329 error (_("Could not enable branch tracing for %s: %s"),
12330 target_pid_to_str (ptid), rs->buf + 2);
12332 error (_("Could not enable branch tracing for %s."),
12333 target_pid_to_str (ptid));
12336 tinfo = XCNEW (struct btrace_target_info);
12337 tinfo->ptid = ptid;
12339 /* If we fail to read the configuration, we lose some information, but the
12340 tracing itself is not impacted. */
12343 btrace_read_config (&tinfo->conf);
12345 CATCH (err, RETURN_MASK_ERROR)
12347 if (err.message != NULL)
12348 warning ("%s", err.message);
12355 /* Disable branch tracing. */
12358 remote_disable_btrace (struct target_ops *self,
12359 struct btrace_target_info *tinfo)
12361 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12362 struct remote_state *rs = get_remote_state ();
12363 char *buf = rs->buf;
12364 char *endbuf = rs->buf + get_remote_packet_size ();
12366 if (packet_config_support (packet) != PACKET_ENABLE)
12367 error (_("Target does not support branch tracing."));
12369 set_general_thread (tinfo->ptid);
12371 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12373 getpkt (&rs->buf, &rs->buf_size, 0);
12375 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12377 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12378 error (_("Could not disable branch tracing for %s: %s"),
12379 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12381 error (_("Could not disable branch tracing for %s."),
12382 target_pid_to_str (tinfo->ptid));
12388 /* Teardown branch tracing. */
12391 remote_teardown_btrace (struct target_ops *self,
12392 struct btrace_target_info *tinfo)
12394 /* We must not talk to the target during teardown. */
12398 /* Read the branch trace. */
12400 static enum btrace_error
12401 remote_read_btrace (struct target_ops *self,
12402 struct btrace_data *btrace,
12403 struct btrace_target_info *tinfo,
12404 enum btrace_read_type type)
12406 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12407 struct remote_state *rs = get_remote_state ();
12408 struct cleanup *cleanup;
12412 if (packet_config_support (packet) != PACKET_ENABLE)
12413 error (_("Target does not support branch tracing."));
12415 #if !defined(HAVE_LIBEXPAT)
12416 error (_("Cannot process branch tracing result. XML parsing not supported."));
12421 case BTRACE_READ_ALL:
12424 case BTRACE_READ_NEW:
12427 case BTRACE_READ_DELTA:
12431 internal_error (__FILE__, __LINE__,
12432 _("Bad branch tracing read type: %u."),
12433 (unsigned int) type);
12436 xml = target_read_stralloc (¤t_target,
12437 TARGET_OBJECT_BTRACE, annex);
12439 return BTRACE_ERR_UNKNOWN;
12441 cleanup = make_cleanup (xfree, xml);
12442 parse_xml_btrace (btrace, xml);
12443 do_cleanups (cleanup);
12445 return BTRACE_ERR_NONE;
12448 static const struct btrace_config *
12449 remote_btrace_conf (struct target_ops *self,
12450 const struct btrace_target_info *tinfo)
12452 return &tinfo->conf;
12456 remote_augmented_libraries_svr4_read (struct target_ops *self)
12458 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12462 /* Implementation of to_load. */
12465 remote_load (struct target_ops *self, const char *name, int from_tty)
12467 generic_load (name, from_tty);
12470 /* Accepts an integer PID; returns a string representing a file that
12471 can be opened on the remote side to get the symbols for the child
12472 process. Returns NULL if the operation is not supported. */
12475 remote_pid_to_exec_file (struct target_ops *self, int pid)
12477 static char *filename = NULL;
12478 struct inferior *inf;
12479 char *annex = NULL;
12481 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12484 if (filename != NULL)
12487 inf = find_inferior_pid (pid);
12489 internal_error (__FILE__, __LINE__,
12490 _("not currently attached to process %d"), pid);
12492 if (!inf->fake_pid_p)
12494 const int annex_size = 9;
12496 annex = alloca (annex_size);
12497 xsnprintf (annex, annex_size, "%x", pid);
12500 filename = target_read_stralloc (¤t_target,
12501 TARGET_OBJECT_EXEC_FILE, annex);
12507 init_remote_ops (void)
12509 remote_ops.to_shortname = "remote";
12510 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12511 remote_ops.to_doc =
12512 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12513 Specify the serial device it is connected to\n\
12514 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12515 remote_ops.to_open = remote_open;
12516 remote_ops.to_close = remote_close;
12517 remote_ops.to_detach = remote_detach;
12518 remote_ops.to_disconnect = remote_disconnect;
12519 remote_ops.to_resume = remote_resume;
12520 remote_ops.to_wait = remote_wait;
12521 remote_ops.to_fetch_registers = remote_fetch_registers;
12522 remote_ops.to_store_registers = remote_store_registers;
12523 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12524 remote_ops.to_files_info = remote_files_info;
12525 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12526 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12527 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12528 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12529 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12530 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12531 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12532 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12533 remote_ops.to_watchpoint_addr_within_range =
12534 remote_watchpoint_addr_within_range;
12535 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12536 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12537 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12538 remote_ops.to_region_ok_for_hw_watchpoint
12539 = remote_region_ok_for_hw_watchpoint;
12540 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12541 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12542 remote_ops.to_kill = remote_kill;
12543 remote_ops.to_load = remote_load;
12544 remote_ops.to_mourn_inferior = remote_mourn;
12545 remote_ops.to_pass_signals = remote_pass_signals;
12546 remote_ops.to_program_signals = remote_program_signals;
12547 remote_ops.to_thread_alive = remote_thread_alive;
12548 remote_ops.to_update_thread_list = remote_update_thread_list;
12549 remote_ops.to_pid_to_str = remote_pid_to_str;
12550 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12551 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12552 remote_ops.to_stop = remote_stop;
12553 remote_ops.to_interrupt = remote_interrupt;
12554 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12555 remote_ops.to_xfer_partial = remote_xfer_partial;
12556 remote_ops.to_rcmd = remote_rcmd;
12557 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12558 remote_ops.to_log_command = serial_log_command;
12559 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12560 remote_ops.to_stratum = process_stratum;
12561 remote_ops.to_has_all_memory = default_child_has_all_memory;
12562 remote_ops.to_has_memory = default_child_has_memory;
12563 remote_ops.to_has_stack = default_child_has_stack;
12564 remote_ops.to_has_registers = default_child_has_registers;
12565 remote_ops.to_has_execution = default_child_has_execution;
12566 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12567 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12568 remote_ops.to_magic = OPS_MAGIC;
12569 remote_ops.to_memory_map = remote_memory_map;
12570 remote_ops.to_flash_erase = remote_flash_erase;
12571 remote_ops.to_flash_done = remote_flash_done;
12572 remote_ops.to_read_description = remote_read_description;
12573 remote_ops.to_search_memory = remote_search_memory;
12574 remote_ops.to_can_async_p = remote_can_async_p;
12575 remote_ops.to_is_async_p = remote_is_async_p;
12576 remote_ops.to_async = remote_async;
12577 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12578 remote_ops.to_terminal_ours = remote_terminal_ours;
12579 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12580 remote_ops.to_supports_multi_process = remote_supports_multi_process;
12581 remote_ops.to_supports_disable_randomization
12582 = remote_supports_disable_randomization;
12583 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12584 remote_ops.to_fileio_open = remote_hostio_open;
12585 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12586 remote_ops.to_fileio_pread = remote_hostio_pread;
12587 remote_ops.to_fileio_fstat = remote_hostio_fstat;
12588 remote_ops.to_fileio_close = remote_hostio_close;
12589 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12590 remote_ops.to_fileio_readlink = remote_hostio_readlink;
12591 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12592 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12593 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12594 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12595 remote_ops.to_trace_init = remote_trace_init;
12596 remote_ops.to_download_tracepoint = remote_download_tracepoint;
12597 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12598 remote_ops.to_download_trace_state_variable
12599 = remote_download_trace_state_variable;
12600 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12601 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12602 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12603 remote_ops.to_trace_start = remote_trace_start;
12604 remote_ops.to_get_trace_status = remote_get_trace_status;
12605 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12606 remote_ops.to_trace_stop = remote_trace_stop;
12607 remote_ops.to_trace_find = remote_trace_find;
12608 remote_ops.to_get_trace_state_variable_value
12609 = remote_get_trace_state_variable_value;
12610 remote_ops.to_save_trace_data = remote_save_trace_data;
12611 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
12612 remote_ops.to_upload_trace_state_variables
12613 = remote_upload_trace_state_variables;
12614 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
12615 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
12616 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12617 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
12618 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
12619 remote_ops.to_set_trace_notes = remote_set_trace_notes;
12620 remote_ops.to_core_of_thread = remote_core_of_thread;
12621 remote_ops.to_verify_memory = remote_verify_memory;
12622 remote_ops.to_get_tib_address = remote_get_tib_address;
12623 remote_ops.to_set_permissions = remote_set_permissions;
12624 remote_ops.to_static_tracepoint_marker_at
12625 = remote_static_tracepoint_marker_at;
12626 remote_ops.to_static_tracepoint_markers_by_strid
12627 = remote_static_tracepoint_markers_by_strid;
12628 remote_ops.to_traceframe_info = remote_traceframe_info;
12629 remote_ops.to_use_agent = remote_use_agent;
12630 remote_ops.to_can_use_agent = remote_can_use_agent;
12631 remote_ops.to_supports_btrace = remote_supports_btrace;
12632 remote_ops.to_enable_btrace = remote_enable_btrace;
12633 remote_ops.to_disable_btrace = remote_disable_btrace;
12634 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12635 remote_ops.to_read_btrace = remote_read_btrace;
12636 remote_ops.to_btrace_conf = remote_btrace_conf;
12637 remote_ops.to_augmented_libraries_svr4_read =
12638 remote_augmented_libraries_svr4_read;
12641 /* Set up the extended remote vector by making a copy of the standard
12642 remote vector and adding to it. */
12645 init_extended_remote_ops (void)
12647 extended_remote_ops = remote_ops;
12649 extended_remote_ops.to_shortname = "extended-remote";
12650 extended_remote_ops.to_longname =
12651 "Extended remote serial target in gdb-specific protocol";
12652 extended_remote_ops.to_doc =
12653 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12654 Specify the serial device it is connected to (e.g. /dev/ttya).";
12655 extended_remote_ops.to_open = extended_remote_open;
12656 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12657 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
12658 extended_remote_ops.to_detach = extended_remote_detach;
12659 extended_remote_ops.to_attach = extended_remote_attach;
12660 extended_remote_ops.to_post_attach = extended_remote_post_attach;
12661 extended_remote_ops.to_kill = extended_remote_kill;
12662 extended_remote_ops.to_supports_disable_randomization
12663 = extended_remote_supports_disable_randomization;
12664 extended_remote_ops.to_follow_fork = remote_follow_fork;
12665 extended_remote_ops.to_insert_fork_catchpoint
12666 = remote_insert_fork_catchpoint;
12667 extended_remote_ops.to_remove_fork_catchpoint
12668 = remote_remove_fork_catchpoint;
12669 extended_remote_ops.to_insert_vfork_catchpoint
12670 = remote_insert_vfork_catchpoint;
12671 extended_remote_ops.to_remove_vfork_catchpoint
12672 = remote_remove_vfork_catchpoint;
12676 remote_can_async_p (struct target_ops *ops)
12678 struct remote_state *rs = get_remote_state ();
12680 if (!target_async_permitted)
12681 /* We only enable async when the user specifically asks for it. */
12684 /* We're async whenever the serial device is. */
12685 return serial_can_async_p (rs->remote_desc);
12689 remote_is_async_p (struct target_ops *ops)
12691 struct remote_state *rs = get_remote_state ();
12693 if (!target_async_permitted)
12694 /* We only enable async when the user specifically asks for it. */
12697 /* We're async whenever the serial device is. */
12698 return serial_is_async_p (rs->remote_desc);
12701 /* Pass the SERIAL event on and up to the client. One day this code
12702 will be able to delay notifying the client of an event until the
12703 point where an entire packet has been received. */
12705 static serial_event_ftype remote_async_serial_handler;
12708 remote_async_serial_handler (struct serial *scb, void *context)
12710 struct remote_state *rs = context;
12712 /* Don't propogate error information up to the client. Instead let
12713 the client find out about the error by querying the target. */
12714 inferior_event_handler (INF_REG_EVENT, NULL);
12718 remote_async_inferior_event_handler (gdb_client_data data)
12720 inferior_event_handler (INF_REG_EVENT, NULL);
12724 remote_async (struct target_ops *ops, int enable)
12726 struct remote_state *rs = get_remote_state ();
12730 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
12732 /* If there are pending events in the stop reply queue tell the
12733 event loop to process them. */
12734 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12735 mark_async_event_handler (remote_async_inferior_event_token);
12739 serial_async (rs->remote_desc, NULL, NULL);
12740 clear_async_event_handler (remote_async_inferior_event_token);
12745 set_remote_cmd (char *args, int from_tty)
12747 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
12751 show_remote_cmd (char *args, int from_tty)
12753 /* We can't just use cmd_show_list here, because we want to skip
12754 the redundant "show remote Z-packet" and the legacy aliases. */
12755 struct cleanup *showlist_chain;
12756 struct cmd_list_element *list = remote_show_cmdlist;
12757 struct ui_out *uiout = current_uiout;
12759 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12760 for (; list != NULL; list = list->next)
12761 if (strcmp (list->name, "Z-packet") == 0)
12763 else if (list->type == not_set_cmd)
12764 /* Alias commands are exactly like the original, except they
12765 don't have the normal type. */
12769 struct cleanup *option_chain
12770 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
12772 ui_out_field_string (uiout, "name", list->name);
12773 ui_out_text (uiout, ": ");
12774 if (list->type == show_cmd)
12775 do_show_command ((char *) NULL, from_tty, list);
12777 cmd_func (list, NULL, from_tty);
12778 /* Close the tuple. */
12779 do_cleanups (option_chain);
12782 /* Close the tuple. */
12783 do_cleanups (showlist_chain);
12787 /* Function to be called whenever a new objfile (shlib) is detected. */
12789 remote_new_objfile (struct objfile *objfile)
12791 struct remote_state *rs = get_remote_state ();
12793 if (rs->remote_desc != 0) /* Have a remote connection. */
12794 remote_check_symbols ();
12797 /* Pull all the tracepoints defined on the target and create local
12798 data structures representing them. We don't want to create real
12799 tracepoints yet, we don't want to mess up the user's existing
12803 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
12805 struct remote_state *rs = get_remote_state ();
12808 /* Ask for a first packet of tracepoint definition. */
12810 getpkt (&rs->buf, &rs->buf_size, 0);
12812 while (*p && *p != 'l')
12814 parse_tracepoint_definition (p, utpp);
12815 /* Ask for another packet of tracepoint definition. */
12817 getpkt (&rs->buf, &rs->buf_size, 0);
12824 remote_upload_trace_state_variables (struct target_ops *self,
12825 struct uploaded_tsv **utsvp)
12827 struct remote_state *rs = get_remote_state ();
12830 /* Ask for a first packet of variable definition. */
12832 getpkt (&rs->buf, &rs->buf_size, 0);
12834 while (*p && *p != 'l')
12836 parse_tsv_definition (p, utsvp);
12837 /* Ask for another packet of variable definition. */
12839 getpkt (&rs->buf, &rs->buf_size, 0);
12845 /* The "set/show range-stepping" show hook. */
12848 show_range_stepping (struct ui_file *file, int from_tty,
12849 struct cmd_list_element *c,
12852 fprintf_filtered (file,
12853 _("Debugger's willingness to use range stepping "
12854 "is %s.\n"), value);
12857 /* The "set/show range-stepping" set hook. */
12860 set_range_stepping (char *ignore_args, int from_tty,
12861 struct cmd_list_element *c)
12863 struct remote_state *rs = get_remote_state ();
12865 /* Whene enabling, check whether range stepping is actually
12866 supported by the target, and warn if not. */
12867 if (use_range_stepping)
12869 if (rs->remote_desc != NULL)
12871 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12872 remote_vcont_probe (rs);
12874 if (packet_support (PACKET_vCont) == PACKET_ENABLE
12875 && rs->supports_vCont.r)
12879 warning (_("Range stepping is not supported by the current target"));
12884 _initialize_remote (void)
12886 struct remote_state *rs;
12887 struct cmd_list_element *cmd;
12888 const char *cmd_name;
12890 /* architecture specific data */
12891 remote_gdbarch_data_handle =
12892 gdbarch_data_register_post_init (init_remote_state);
12893 remote_g_packet_data_handle =
12894 gdbarch_data_register_pre_init (remote_g_packet_data_init);
12896 /* Initialize the per-target state. At the moment there is only one
12897 of these, not one per target. Only one target is active at a
12899 remote_state = new_remote_state ();
12901 init_remote_ops ();
12902 add_target (&remote_ops);
12904 init_extended_remote_ops ();
12905 add_target (&extended_remote_ops);
12907 /* Hook into new objfile notification. */
12908 observer_attach_new_objfile (remote_new_objfile);
12909 /* We're no longer interested in notification events of an inferior
12911 observer_attach_inferior_exit (discard_pending_stop_replies);
12913 /* Set up signal handlers. */
12914 async_sigint_remote_token =
12915 create_async_signal_handler (async_remote_interrupt, NULL);
12916 async_sigint_remote_twice_token =
12917 create_async_signal_handler (async_remote_interrupt_twice, NULL);
12920 init_remote_threadtests ();
12923 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
12924 /* set/show remote ... */
12926 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12927 Remote protocol specific variables\n\
12928 Configure various remote-protocol specific variables such as\n\
12929 the packets being used"),
12930 &remote_set_cmdlist, "set remote ",
12931 0 /* allow-unknown */, &setlist);
12932 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12933 Remote protocol specific variables\n\
12934 Configure various remote-protocol specific variables such as\n\
12935 the packets being used"),
12936 &remote_show_cmdlist, "show remote ",
12937 0 /* allow-unknown */, &showlist);
12939 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12940 Compare section data on target to the exec file.\n\
12941 Argument is a single section name (default: all loaded sections).\n\
12942 To compare only read-only loaded sections, specify the -r option."),
12945 add_cmd ("packet", class_maintenance, packet_command, _("\
12946 Send an arbitrary packet to a remote target.\n\
12947 maintenance packet TEXT\n\
12948 If GDB is talking to an inferior via the GDB serial protocol, then\n\
12949 this command sends the string TEXT to the inferior, and displays the\n\
12950 response packet. GDB supplies the initial `$' character, and the\n\
12951 terminating `#' character and checksum."),
12954 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12955 Set whether to send break if interrupted."), _("\
12956 Show whether to send break if interrupted."), _("\
12957 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12958 set_remotebreak, show_remotebreak,
12959 &setlist, &showlist);
12960 cmd_name = "remotebreak";
12961 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12962 deprecate_cmd (cmd, "set remote interrupt-sequence");
12963 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12964 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12965 deprecate_cmd (cmd, "show remote interrupt-sequence");
12967 add_setshow_enum_cmd ("interrupt-sequence", class_support,
12968 interrupt_sequence_modes, &interrupt_sequence_mode,
12970 Set interrupt sequence to remote target."), _("\
12971 Show interrupt sequence to remote target."), _("\
12972 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12973 NULL, show_interrupt_sequence,
12974 &remote_set_cmdlist,
12975 &remote_show_cmdlist);
12977 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12978 &interrupt_on_connect, _("\
12979 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12980 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12981 If set, interrupt sequence is sent to remote target."),
12983 &remote_set_cmdlist, &remote_show_cmdlist);
12985 /* Install commands for configuring memory read/write packets. */
12987 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12988 Set the maximum number of bytes per memory write packet (deprecated)."),
12990 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12991 Show the maximum number of bytes per memory write packet (deprecated)."),
12993 add_cmd ("memory-write-packet-size", no_class,
12994 set_memory_write_packet_size, _("\
12995 Set the maximum number of bytes per memory-write packet.\n\
12996 Specify the number of bytes in a packet or 0 (zero) for the\n\
12997 default packet size. The actual limit is further reduced\n\
12998 dependent on the target. Specify ``fixed'' to disable the\n\
12999 further restriction and ``limit'' to enable that restriction."),
13000 &remote_set_cmdlist);
13001 add_cmd ("memory-read-packet-size", no_class,
13002 set_memory_read_packet_size, _("\
13003 Set the maximum number of bytes per memory-read packet.\n\
13004 Specify the number of bytes in a packet or 0 (zero) for the\n\
13005 default packet size. The actual limit is further reduced\n\
13006 dependent on the target. Specify ``fixed'' to disable the\n\
13007 further restriction and ``limit'' to enable that restriction."),
13008 &remote_set_cmdlist);
13009 add_cmd ("memory-write-packet-size", no_class,
13010 show_memory_write_packet_size,
13011 _("Show the maximum number of bytes per memory-write packet."),
13012 &remote_show_cmdlist);
13013 add_cmd ("memory-read-packet-size", no_class,
13014 show_memory_read_packet_size,
13015 _("Show the maximum number of bytes per memory-read packet."),
13016 &remote_show_cmdlist);
13018 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13019 &remote_hw_watchpoint_limit, _("\
13020 Set the maximum number of target hardware watchpoints."), _("\
13021 Show the maximum number of target hardware watchpoints."), _("\
13022 Specify a negative limit for unlimited."),
13023 NULL, NULL, /* FIXME: i18n: The maximum
13024 number of target hardware
13025 watchpoints is %s. */
13026 &remote_set_cmdlist, &remote_show_cmdlist);
13027 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13028 &remote_hw_watchpoint_length_limit, _("\
13029 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13030 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13031 Specify a negative limit for unlimited."),
13032 NULL, NULL, /* FIXME: i18n: The maximum
13033 length (in bytes) of a target
13034 hardware watchpoint is %s. */
13035 &remote_set_cmdlist, &remote_show_cmdlist);
13036 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13037 &remote_hw_breakpoint_limit, _("\
13038 Set the maximum number of target hardware breakpoints."), _("\
13039 Show the maximum number of target hardware breakpoints."), _("\
13040 Specify a negative limit for unlimited."),
13041 NULL, NULL, /* FIXME: i18n: The maximum
13042 number of target hardware
13043 breakpoints is %s. */
13044 &remote_set_cmdlist, &remote_show_cmdlist);
13046 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13047 &remote_address_size, _("\
13048 Set the maximum size of the address (in bits) in a memory packet."), _("\
13049 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13051 NULL, /* FIXME: i18n: */
13052 &setlist, &showlist);
13054 init_all_packet_configs ();
13056 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13057 "X", "binary-download", 1);
13059 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13060 "vCont", "verbose-resume", 0);
13062 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13063 "QPassSignals", "pass-signals", 0);
13065 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13066 "QProgramSignals", "program-signals", 0);
13068 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13069 "qSymbol", "symbol-lookup", 0);
13071 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13072 "P", "set-register", 1);
13074 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13075 "p", "fetch-register", 1);
13077 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13078 "Z0", "software-breakpoint", 0);
13080 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13081 "Z1", "hardware-breakpoint", 0);
13083 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13084 "Z2", "write-watchpoint", 0);
13086 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13087 "Z3", "read-watchpoint", 0);
13089 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13090 "Z4", "access-watchpoint", 0);
13092 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13093 "qXfer:auxv:read", "read-aux-vector", 0);
13095 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13096 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13098 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13099 "qXfer:features:read", "target-features", 0);
13101 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13102 "qXfer:libraries:read", "library-info", 0);
13104 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13105 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13107 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13108 "qXfer:memory-map:read", "memory-map", 0);
13110 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13111 "qXfer:spu:read", "read-spu-object", 0);
13113 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13114 "qXfer:spu:write", "write-spu-object", 0);
13116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13117 "qXfer:osdata:read", "osdata", 0);
13119 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13120 "qXfer:threads:read", "threads", 0);
13122 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13123 "qXfer:siginfo:read", "read-siginfo-object", 0);
13125 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13126 "qXfer:siginfo:write", "write-siginfo-object", 0);
13128 add_packet_config_cmd
13129 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13130 "qXfer:traceframe-info:read", "traceframe-info", 0);
13132 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13133 "qXfer:uib:read", "unwind-info-block", 0);
13135 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13136 "qGetTLSAddr", "get-thread-local-storage-address",
13139 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13140 "qGetTIBAddr", "get-thread-information-block-address",
13143 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13144 "bc", "reverse-continue", 0);
13146 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13147 "bs", "reverse-step", 0);
13149 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13150 "qSupported", "supported-packets", 0);
13152 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13153 "qSearch:memory", "search-memory", 0);
13155 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13156 "qTStatus", "trace-status", 0);
13158 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13159 "vFile:setfs", "hostio-setfs", 0);
13161 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13162 "vFile:open", "hostio-open", 0);
13164 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13165 "vFile:pread", "hostio-pread", 0);
13167 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13168 "vFile:pwrite", "hostio-pwrite", 0);
13170 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13171 "vFile:close", "hostio-close", 0);
13173 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13174 "vFile:unlink", "hostio-unlink", 0);
13176 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13177 "vFile:readlink", "hostio-readlink", 0);
13179 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13180 "vFile:fstat", "hostio-fstat", 0);
13182 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13183 "vAttach", "attach", 0);
13185 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13188 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13189 "QStartNoAckMode", "noack", 0);
13191 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13192 "vKill", "kill", 0);
13194 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13195 "qAttached", "query-attached", 0);
13197 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13198 "ConditionalTracepoints",
13199 "conditional-tracepoints", 0);
13201 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13202 "ConditionalBreakpoints",
13203 "conditional-breakpoints", 0);
13205 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13206 "BreakpointCommands",
13207 "breakpoint-commands", 0);
13209 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13210 "FastTracepoints", "fast-tracepoints", 0);
13212 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13213 "TracepointSource", "TracepointSource", 0);
13215 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13216 "QAllow", "allow", 0);
13218 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13219 "StaticTracepoints", "static-tracepoints", 0);
13221 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13222 "InstallInTrace", "install-in-trace", 0);
13224 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13225 "qXfer:statictrace:read", "read-sdata-object", 0);
13227 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13228 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13230 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13231 "QDisableRandomization", "disable-randomization", 0);
13233 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13234 "QAgent", "agent", 0);
13236 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13237 "QTBuffer:size", "trace-buffer-size", 0);
13239 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13240 "Qbtrace:off", "disable-btrace", 0);
13242 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13243 "Qbtrace:bts", "enable-btrace-bts", 0);
13245 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13246 "Qbtrace:pt", "enable-btrace-pt", 0);
13248 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13249 "qXfer:btrace", "read-btrace", 0);
13251 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13252 "qXfer:btrace-conf", "read-btrace-conf", 0);
13254 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13255 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13257 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13258 "multiprocess-feature", "multiprocess-feature", 0);
13260 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13261 "swbreak-feature", "swbreak-feature", 0);
13263 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13264 "hwbreak-feature", "hwbreak-feature", 0);
13266 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13267 "fork-event-feature", "fork-event-feature", 0);
13269 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13270 "vfork-event-feature", "vfork-event-feature", 0);
13272 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13273 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13275 /* Assert that we've registered "set remote foo-packet" commands
13276 for all packet configs. */
13280 for (i = 0; i < PACKET_MAX; i++)
13282 /* Ideally all configs would have a command associated. Some
13283 still don't though. */
13288 case PACKET_QNonStop:
13289 case PACKET_EnableDisableTracepoints_feature:
13290 case PACKET_tracenz_feature:
13291 case PACKET_DisconnectedTracing_feature:
13292 case PACKET_augmented_libraries_svr4_read_feature:
13294 /* Additions to this list need to be well justified:
13295 pre-existing packets are OK; new packets are not. */
13303 /* This catches both forgetting to add a config command, and
13304 forgetting to remove a packet from the exception list. */
13305 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13309 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13310 Z sub-packet has its own set and show commands, but users may
13311 have sets to this variable in their .gdbinit files (or in their
13313 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13314 &remote_Z_packet_detect, _("\
13315 Set use of remote protocol `Z' packets"), _("\
13316 Show use of remote protocol `Z' packets "), _("\
13317 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13319 set_remote_protocol_Z_packet_cmd,
13320 show_remote_protocol_Z_packet_cmd,
13321 /* FIXME: i18n: Use of remote protocol
13322 `Z' packets is %s. */
13323 &remote_set_cmdlist, &remote_show_cmdlist);
13325 add_prefix_cmd ("remote", class_files, remote_command, _("\
13326 Manipulate files on the remote system\n\
13327 Transfer files to and from the remote target system."),
13328 &remote_cmdlist, "remote ",
13329 0 /* allow-unknown */, &cmdlist);
13331 add_cmd ("put", class_files, remote_put_command,
13332 _("Copy a local file to the remote system."),
13335 add_cmd ("get", class_files, remote_get_command,
13336 _("Copy a remote file to the local system."),
13339 add_cmd ("delete", class_files, remote_delete_command,
13340 _("Delete a remote file."),
13343 remote_exec_file = xstrdup ("");
13344 add_setshow_string_noescape_cmd ("exec-file", class_files,
13345 &remote_exec_file, _("\
13346 Set the remote pathname for \"run\""), _("\
13347 Show the remote pathname for \"run\""), NULL, NULL, NULL,
13348 &remote_set_cmdlist, &remote_show_cmdlist);
13350 add_setshow_boolean_cmd ("range-stepping", class_run,
13351 &use_range_stepping, _("\
13352 Enable or disable range stepping."), _("\
13353 Show whether target-assisted range stepping is enabled."), _("\
13354 If on, and the target supports it, when stepping a source line, GDB\n\
13355 tells the target to step the corresponding range of addresses itself instead\n\
13356 of issuing multiple single-steps. This speeds up source level\n\
13357 stepping. If off, GDB always issues single-steps, even if range\n\
13358 stepping is supported by the target. The default is on."),
13359 set_range_stepping,
13360 show_range_stepping,
13364 /* Eventually initialize fileio. See fileio.c */
13365 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13367 /* Take advantage of the fact that the TID field is not used, to tag
13368 special ptids with it set to != 0. */
13369 magic_null_ptid = ptid_build (42000, -1, 1);
13370 not_sent_ptid = ptid_build (42000, -2, 1);
13371 any_thread_ptid = ptid_build (42000, 0, 1);
13373 target_buf_size = 2048;
13374 target_buf = xmalloc (target_buf_size);