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 /* Compute the current size of a read/write packet. Since this makes
925 use of ``actual_register_packet_size'' the computation is dynamic. */
928 get_memory_packet_size (struct memory_packet_config *config)
930 struct remote_state *rs = get_remote_state ();
931 struct remote_arch_state *rsa = get_remote_arch_state ();
933 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
934 law?) that some hosts don't cope very well with large alloca()
935 calls. Eventually the alloca() code will be replaced by calls to
936 xmalloc() and make_cleanups() allowing this restriction to either
937 be lifted or removed. */
938 #ifndef MAX_REMOTE_PACKET_SIZE
939 #define MAX_REMOTE_PACKET_SIZE 16384
941 /* NOTE: 20 ensures we can write at least one byte. */
942 #ifndef MIN_REMOTE_PACKET_SIZE
943 #define MIN_REMOTE_PACKET_SIZE 20
948 if (config->size <= 0)
949 what_they_get = MAX_REMOTE_PACKET_SIZE;
951 what_they_get = config->size;
955 what_they_get = get_remote_packet_size ();
956 /* Limit the packet to the size specified by the user. */
958 && what_they_get > config->size)
959 what_they_get = config->size;
961 /* Limit it to the size of the targets ``g'' response unless we have
962 permission from the stub to use a larger packet size. */
963 if (rs->explicit_packet_size == 0
964 && rsa->actual_register_packet_size > 0
965 && what_they_get > rsa->actual_register_packet_size)
966 what_they_get = rsa->actual_register_packet_size;
968 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
969 what_they_get = MAX_REMOTE_PACKET_SIZE;
970 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
971 what_they_get = MIN_REMOTE_PACKET_SIZE;
973 /* Make sure there is room in the global buffer for this packet
974 (including its trailing NUL byte). */
975 if (rs->buf_size < what_they_get + 1)
977 rs->buf_size = 2 * what_they_get;
978 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
981 return what_they_get;
984 /* Update the size of a read/write packet. If they user wants
985 something really big then do a sanity check. */
988 set_memory_packet_size (char *args, struct memory_packet_config *config)
990 int fixed_p = config->fixed_p;
991 long size = config->size;
994 error (_("Argument required (integer, `fixed' or `limited')."));
995 else if (strcmp (args, "hard") == 0
996 || strcmp (args, "fixed") == 0)
998 else if (strcmp (args, "soft") == 0
999 || strcmp (args, "limit") == 0)
1005 size = strtoul (args, &end, 0);
1007 error (_("Invalid %s (bad syntax)."), config->name);
1009 /* Instead of explicitly capping the size of a packet to
1010 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
1011 instead allowed to set the size to something arbitrarily
1013 if (size > MAX_REMOTE_PACKET_SIZE)
1014 error (_("Invalid %s (too large)."), config->name);
1018 if (fixed_p && !config->fixed_p)
1020 if (! query (_("The target may not be able to correctly handle a %s\n"
1021 "of %ld bytes. Change the packet size? "),
1022 config->name, size))
1023 error (_("Packet size not changed."));
1025 /* Update the config. */
1026 config->fixed_p = fixed_p;
1027 config->size = size;
1031 show_memory_packet_size (struct memory_packet_config *config)
1033 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1034 if (config->fixed_p)
1035 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1036 get_memory_packet_size (config));
1038 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1039 get_memory_packet_size (config));
1042 static struct memory_packet_config memory_write_packet_config =
1044 "memory-write-packet-size",
1048 set_memory_write_packet_size (char *args, int from_tty)
1050 set_memory_packet_size (args, &memory_write_packet_config);
1054 show_memory_write_packet_size (char *args, int from_tty)
1056 show_memory_packet_size (&memory_write_packet_config);
1060 get_memory_write_packet_size (void)
1062 return get_memory_packet_size (&memory_write_packet_config);
1065 static struct memory_packet_config memory_read_packet_config =
1067 "memory-read-packet-size",
1071 set_memory_read_packet_size (char *args, int from_tty)
1073 set_memory_packet_size (args, &memory_read_packet_config);
1077 show_memory_read_packet_size (char *args, int from_tty)
1079 show_memory_packet_size (&memory_read_packet_config);
1083 get_memory_read_packet_size (void)
1085 long size = get_memory_packet_size (&memory_read_packet_config);
1087 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1088 extra buffer size argument before the memory read size can be
1089 increased beyond this. */
1090 if (size > get_remote_packet_size ())
1091 size = get_remote_packet_size ();
1096 /* Generic configuration support for packets the stub optionally
1097 supports. Allows the user to specify the use of the packet as well
1098 as allowing GDB to auto-detect support in the remote stub. */
1102 PACKET_SUPPORT_UNKNOWN = 0,
1107 struct packet_config
1112 /* If auto, GDB auto-detects support for this packet or feature,
1113 either through qSupported, or by trying the packet and looking
1114 at the response. If true, GDB assumes the target supports this
1115 packet. If false, the packet is disabled. Configs that don't
1116 have an associated command always have this set to auto. */
1117 enum auto_boolean detect;
1119 /* Does the target support this packet? */
1120 enum packet_support support;
1123 /* Analyze a packet's return value and update the packet config
1133 static enum packet_support packet_config_support (struct packet_config *config);
1134 static enum packet_support packet_support (int packet);
1137 show_packet_config_cmd (struct packet_config *config)
1139 char *support = "internal-error";
1141 switch (packet_config_support (config))
1144 support = "enabled";
1146 case PACKET_DISABLE:
1147 support = "disabled";
1149 case PACKET_SUPPORT_UNKNOWN:
1150 support = "unknown";
1153 switch (config->detect)
1155 case AUTO_BOOLEAN_AUTO:
1156 printf_filtered (_("Support for the `%s' packet "
1157 "is auto-detected, currently %s.\n"),
1158 config->name, support);
1160 case AUTO_BOOLEAN_TRUE:
1161 case AUTO_BOOLEAN_FALSE:
1162 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1163 config->name, support);
1169 add_packet_config_cmd (struct packet_config *config, const char *name,
1170 const char *title, int legacy)
1176 config->name = name;
1177 config->title = title;
1178 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1180 show_doc = xstrprintf ("Show current use of remote "
1181 "protocol `%s' (%s) packet",
1183 /* set/show TITLE-packet {auto,on,off} */
1184 cmd_name = xstrprintf ("%s-packet", title);
1185 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1186 &config->detect, set_doc,
1187 show_doc, NULL, /* help_doc */
1189 show_remote_protocol_packet_cmd,
1190 &remote_set_cmdlist, &remote_show_cmdlist);
1191 /* The command code copies the documentation strings. */
1194 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1199 legacy_name = xstrprintf ("%s-packet", name);
1200 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1201 &remote_set_cmdlist);
1202 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1203 &remote_show_cmdlist);
1207 static enum packet_result
1208 packet_check_result (const char *buf)
1212 /* The stub recognized the packet request. Check that the
1213 operation succeeded. */
1215 && isxdigit (buf[1]) && isxdigit (buf[2])
1217 /* "Enn" - definitly an error. */
1218 return PACKET_ERROR;
1220 /* Always treat "E." as an error. This will be used for
1221 more verbose error messages, such as E.memtypes. */
1222 if (buf[0] == 'E' && buf[1] == '.')
1223 return PACKET_ERROR;
1225 /* The packet may or may not be OK. Just assume it is. */
1229 /* The stub does not support the packet. */
1230 return PACKET_UNKNOWN;
1233 static enum packet_result
1234 packet_ok (const char *buf, struct packet_config *config)
1236 enum packet_result result;
1238 if (config->detect != AUTO_BOOLEAN_TRUE
1239 && config->support == PACKET_DISABLE)
1240 internal_error (__FILE__, __LINE__,
1241 _("packet_ok: attempt to use a disabled packet"));
1243 result = packet_check_result (buf);
1248 /* The stub recognized the packet request. */
1249 if (config->support == PACKET_SUPPORT_UNKNOWN)
1252 fprintf_unfiltered (gdb_stdlog,
1253 "Packet %s (%s) is supported\n",
1254 config->name, config->title);
1255 config->support = PACKET_ENABLE;
1258 case PACKET_UNKNOWN:
1259 /* The stub does not support the packet. */
1260 if (config->detect == AUTO_BOOLEAN_AUTO
1261 && config->support == PACKET_ENABLE)
1263 /* If the stub previously indicated that the packet was
1264 supported then there is a protocol error. */
1265 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1266 config->name, config->title);
1268 else if (config->detect == AUTO_BOOLEAN_TRUE)
1270 /* The user set it wrong. */
1271 error (_("Enabled packet %s (%s) not recognized by stub"),
1272 config->name, config->title);
1276 fprintf_unfiltered (gdb_stdlog,
1277 "Packet %s (%s) is NOT supported\n",
1278 config->name, config->title);
1279 config->support = PACKET_DISABLE;
1300 PACKET_vFile_pwrite,
1302 PACKET_vFile_unlink,
1303 PACKET_vFile_readlink,
1306 PACKET_qXfer_features,
1307 PACKET_qXfer_exec_file,
1308 PACKET_qXfer_libraries,
1309 PACKET_qXfer_libraries_svr4,
1310 PACKET_qXfer_memory_map,
1311 PACKET_qXfer_spu_read,
1312 PACKET_qXfer_spu_write,
1313 PACKET_qXfer_osdata,
1314 PACKET_qXfer_threads,
1315 PACKET_qXfer_statictrace_read,
1316 PACKET_qXfer_traceframe_info,
1322 PACKET_QPassSignals,
1323 PACKET_QProgramSignals,
1325 PACKET_qSearch_memory,
1328 PACKET_QStartNoAckMode,
1330 PACKET_qXfer_siginfo_read,
1331 PACKET_qXfer_siginfo_write,
1334 /* Support for conditional tracepoints. */
1335 PACKET_ConditionalTracepoints,
1337 /* Support for target-side breakpoint conditions. */
1338 PACKET_ConditionalBreakpoints,
1340 /* Support for target-side breakpoint commands. */
1341 PACKET_BreakpointCommands,
1343 /* Support for fast tracepoints. */
1344 PACKET_FastTracepoints,
1346 /* Support for static tracepoints. */
1347 PACKET_StaticTracepoints,
1349 /* Support for installing tracepoints while a trace experiment is
1351 PACKET_InstallInTrace,
1355 PACKET_TracepointSource,
1358 PACKET_QDisableRandomization,
1360 PACKET_QTBuffer_size,
1364 PACKET_qXfer_btrace,
1366 /* Support for the QNonStop packet. */
1369 /* Support for multi-process extensions. */
1370 PACKET_multiprocess_feature,
1372 /* Support for enabling and disabling tracepoints while a trace
1373 experiment is running. */
1374 PACKET_EnableDisableTracepoints_feature,
1376 /* Support for collecting strings using the tracenz bytecode. */
1377 PACKET_tracenz_feature,
1379 /* Support for continuing to run a trace experiment while GDB is
1381 PACKET_DisconnectedTracing_feature,
1383 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1384 PACKET_augmented_libraries_svr4_read_feature,
1386 /* Support for the qXfer:btrace-conf:read packet. */
1387 PACKET_qXfer_btrace_conf,
1389 /* Support for the Qbtrace-conf:bts:size packet. */
1390 PACKET_Qbtrace_conf_bts_size,
1392 /* Support for swbreak+ feature. */
1393 PACKET_swbreak_feature,
1395 /* Support for hwbreak+ feature. */
1396 PACKET_hwbreak_feature,
1398 /* Support for fork events. */
1399 PACKET_fork_event_feature,
1401 /* Support for vfork events. */
1402 PACKET_vfork_event_feature,
1404 /* Support for the Qbtrace-conf:pt:size packet. */
1405 PACKET_Qbtrace_conf_pt_size,
1410 static struct packet_config remote_protocol_packets[PACKET_MAX];
1412 /* Returns the packet's corresponding "set remote foo-packet" command
1413 state. See struct packet_config for more details. */
1415 static enum auto_boolean
1416 packet_set_cmd_state (int packet)
1418 return remote_protocol_packets[packet].detect;
1421 /* Returns whether a given packet or feature is supported. This takes
1422 into account the state of the corresponding "set remote foo-packet"
1423 command, which may be used to bypass auto-detection. */
1425 static enum packet_support
1426 packet_config_support (struct packet_config *config)
1428 switch (config->detect)
1430 case AUTO_BOOLEAN_TRUE:
1431 return PACKET_ENABLE;
1432 case AUTO_BOOLEAN_FALSE:
1433 return PACKET_DISABLE;
1434 case AUTO_BOOLEAN_AUTO:
1435 return config->support;
1437 gdb_assert_not_reached (_("bad switch"));
1441 /* Same as packet_config_support, but takes the packet's enum value as
1444 static enum packet_support
1445 packet_support (int packet)
1447 struct packet_config *config = &remote_protocol_packets[packet];
1449 return packet_config_support (config);
1453 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1454 struct cmd_list_element *c,
1457 struct packet_config *packet;
1459 for (packet = remote_protocol_packets;
1460 packet < &remote_protocol_packets[PACKET_MAX];
1463 if (&packet->detect == c->var)
1465 show_packet_config_cmd (packet);
1469 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1473 /* Should we try one of the 'Z' requests? */
1477 Z_PACKET_SOFTWARE_BP,
1478 Z_PACKET_HARDWARE_BP,
1485 /* For compatibility with older distributions. Provide a ``set remote
1486 Z-packet ...'' command that updates all the Z packet types. */
1488 static enum auto_boolean remote_Z_packet_detect;
1491 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1492 struct cmd_list_element *c)
1496 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1497 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1501 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1502 struct cmd_list_element *c,
1507 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1509 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1513 /* Returns true if the multi-process extensions are in effect. */
1516 remote_multi_process_p (struct remote_state *rs)
1518 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1521 /* Returns true if fork events are supported. */
1524 remote_fork_event_p (struct remote_state *rs)
1526 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1529 /* Returns true if vfork events are supported. */
1532 remote_vfork_event_p (struct remote_state *rs)
1534 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1537 /* Insert fork catchpoint target routine. If fork events are enabled
1538 then return success, nothing more to do. */
1541 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1543 struct remote_state *rs = get_remote_state ();
1545 return !remote_fork_event_p (rs);
1548 /* Remove fork catchpoint target routine. Nothing to do, just
1552 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1557 /* Insert vfork catchpoint target routine. If vfork events are enabled
1558 then return success, nothing more to do. */
1561 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1563 struct remote_state *rs = get_remote_state ();
1565 return !remote_vfork_event_p (rs);
1568 /* Remove vfork catchpoint target routine. Nothing to do, just
1572 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1577 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1578 static struct async_signal_handler *async_sigint_remote_twice_token;
1579 static struct async_signal_handler *async_sigint_remote_token;
1582 /* Asynchronous signal handle registered as event loop source for
1583 when we have pending events ready to be passed to the core. */
1585 static struct async_event_handler *remote_async_inferior_event_token;
1589 static ptid_t magic_null_ptid;
1590 static ptid_t not_sent_ptid;
1591 static ptid_t any_thread_ptid;
1593 /* Find out if the stub attached to PID (and hence GDB should offer to
1594 detach instead of killing it when bailing out). */
1597 remote_query_attached (int pid)
1599 struct remote_state *rs = get_remote_state ();
1600 size_t size = get_remote_packet_size ();
1602 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1605 if (remote_multi_process_p (rs))
1606 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1608 xsnprintf (rs->buf, size, "qAttached");
1611 getpkt (&rs->buf, &rs->buf_size, 0);
1613 switch (packet_ok (rs->buf,
1614 &remote_protocol_packets[PACKET_qAttached]))
1617 if (strcmp (rs->buf, "1") == 0)
1621 warning (_("Remote failure reply: %s"), rs->buf);
1623 case PACKET_UNKNOWN:
1630 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1631 has been invented by GDB, instead of reported by the target. Since
1632 we can be connected to a remote system before before knowing about
1633 any inferior, mark the target with execution when we find the first
1634 inferior. If ATTACHED is 1, then we had just attached to this
1635 inferior. If it is 0, then we just created this inferior. If it
1636 is -1, then try querying the remote stub to find out if it had
1637 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1638 attempt to open this inferior's executable as the main executable
1639 if no main executable is open already. */
1641 static struct inferior *
1642 remote_add_inferior (int fake_pid_p, int pid, int attached,
1645 struct inferior *inf;
1647 /* Check whether this process we're learning about is to be
1648 considered attached, or if is to be considered to have been
1649 spawned by the stub. */
1651 attached = remote_query_attached (pid);
1653 if (gdbarch_has_global_solist (target_gdbarch ()))
1655 /* If the target shares code across all inferiors, then every
1656 attach adds a new inferior. */
1657 inf = add_inferior (pid);
1659 /* ... and every inferior is bound to the same program space.
1660 However, each inferior may still have its own address
1662 inf->aspace = maybe_new_address_space ();
1663 inf->pspace = current_program_space;
1667 /* In the traditional debugging scenario, there's a 1-1 match
1668 between program/address spaces. We simply bind the inferior
1669 to the program space's address space. */
1670 inf = current_inferior ();
1671 inferior_appeared (inf, pid);
1674 inf->attach_flag = attached;
1675 inf->fake_pid_p = fake_pid_p;
1677 /* If no main executable is currently open then attempt to
1678 open the file that was executed to create this inferior. */
1679 if (try_open_exec && get_exec_file (0) == NULL)
1680 exec_file_locate_attach (pid, 1);
1685 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1686 according to RUNNING. */
1689 remote_add_thread (ptid_t ptid, int running)
1691 struct remote_state *rs = get_remote_state ();
1693 /* GDB historically didn't pull threads in the initial connection
1694 setup. If the remote target doesn't even have a concept of
1695 threads (e.g., a bare-metal target), even if internally we
1696 consider that a single-threaded target, mentioning a new thread
1697 might be confusing to the user. Be silent then, preserving the
1698 age old behavior. */
1699 if (rs->starting_up)
1700 add_thread_silent (ptid);
1704 set_executing (ptid, running);
1705 set_running (ptid, running);
1708 /* Come here when we learn about a thread id from the remote target.
1709 It may be the first time we hear about such thread, so take the
1710 opportunity to add it to GDB's thread list. In case this is the
1711 first time we're noticing its corresponding inferior, add it to
1712 GDB's inferior list as well. */
1715 remote_notice_new_inferior (ptid_t currthread, int running)
1717 /* If this is a new thread, add it to GDB's thread list.
1718 If we leave it up to WFI to do this, bad things will happen. */
1720 if (in_thread_list (currthread) && is_exited (currthread))
1722 /* We're seeing an event on a thread id we knew had exited.
1723 This has to be a new thread reusing the old id. Add it. */
1724 remote_add_thread (currthread, running);
1728 if (!in_thread_list (currthread))
1730 struct inferior *inf = NULL;
1731 int pid = ptid_get_pid (currthread);
1733 if (ptid_is_pid (inferior_ptid)
1734 && pid == ptid_get_pid (inferior_ptid))
1736 /* inferior_ptid has no thread member yet. This can happen
1737 with the vAttach -> remote_wait,"TAAthread:" path if the
1738 stub doesn't support qC. This is the first stop reported
1739 after an attach, so this is the main thread. Update the
1740 ptid in the thread list. */
1741 if (in_thread_list (pid_to_ptid (pid)))
1742 thread_change_ptid (inferior_ptid, currthread);
1745 remote_add_thread (currthread, running);
1746 inferior_ptid = currthread;
1751 if (ptid_equal (magic_null_ptid, inferior_ptid))
1753 /* inferior_ptid is not set yet. This can happen with the
1754 vRun -> remote_wait,"TAAthread:" path if the stub
1755 doesn't support qC. This is the first stop reported
1756 after an attach, so this is the main thread. Update the
1757 ptid in the thread list. */
1758 thread_change_ptid (inferior_ptid, currthread);
1762 /* When connecting to a target remote, or to a target
1763 extended-remote which already was debugging an inferior, we
1764 may not know about it yet. Add it before adding its child
1765 thread, so notifications are emitted in a sensible order. */
1766 if (!in_inferior_list (ptid_get_pid (currthread)))
1768 struct remote_state *rs = get_remote_state ();
1769 int fake_pid_p = !remote_multi_process_p (rs);
1771 inf = remote_add_inferior (fake_pid_p,
1772 ptid_get_pid (currthread), -1, 1);
1775 /* This is really a new thread. Add it. */
1776 remote_add_thread (currthread, running);
1778 /* If we found a new inferior, let the common code do whatever
1779 it needs to with it (e.g., read shared libraries, insert
1780 breakpoints), unless we're just setting up an all-stop
1784 struct remote_state *rs = get_remote_state ();
1786 if (non_stop || !rs->starting_up)
1787 notice_new_inferior (currthread, running, 0);
1792 /* Return the private thread data, creating it if necessary. */
1794 static struct private_thread_info *
1795 demand_private_info (ptid_t ptid)
1797 struct thread_info *info = find_thread_ptid (ptid);
1803 info->priv = XNEW (struct private_thread_info);
1804 info->private_dtor = free_private_thread_info;
1805 info->priv->core = -1;
1806 info->priv->extra = 0;
1812 /* Call this function as a result of
1813 1) A halt indication (T packet) containing a thread id
1814 2) A direct query of currthread
1815 3) Successful execution of set thread */
1818 record_currthread (struct remote_state *rs, ptid_t currthread)
1820 rs->general_thread = currthread;
1823 /* If 'QPassSignals' is supported, tell the remote stub what signals
1824 it can simply pass through to the inferior without reporting. */
1827 remote_pass_signals (struct target_ops *self,
1828 int numsigs, unsigned char *pass_signals)
1830 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1832 char *pass_packet, *p;
1834 struct remote_state *rs = get_remote_state ();
1836 gdb_assert (numsigs < 256);
1837 for (i = 0; i < numsigs; i++)
1839 if (pass_signals[i])
1842 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1843 strcpy (pass_packet, "QPassSignals:");
1844 p = pass_packet + strlen (pass_packet);
1845 for (i = 0; i < numsigs; i++)
1847 if (pass_signals[i])
1850 *p++ = tohex (i >> 4);
1851 *p++ = tohex (i & 15);
1860 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1862 putpkt (pass_packet);
1863 getpkt (&rs->buf, &rs->buf_size, 0);
1864 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1865 if (rs->last_pass_packet)
1866 xfree (rs->last_pass_packet);
1867 rs->last_pass_packet = pass_packet;
1870 xfree (pass_packet);
1874 /* If 'QProgramSignals' is supported, tell the remote stub what
1875 signals it should pass through to the inferior when detaching. */
1878 remote_program_signals (struct target_ops *self,
1879 int numsigs, unsigned char *signals)
1881 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1885 struct remote_state *rs = get_remote_state ();
1887 gdb_assert (numsigs < 256);
1888 for (i = 0; i < numsigs; i++)
1893 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1894 strcpy (packet, "QProgramSignals:");
1895 p = packet + strlen (packet);
1896 for (i = 0; i < numsigs; i++)
1898 if (signal_pass_state (i))
1901 *p++ = tohex (i >> 4);
1902 *p++ = tohex (i & 15);
1911 if (!rs->last_program_signals_packet
1912 || strcmp (rs->last_program_signals_packet, packet) != 0)
1915 getpkt (&rs->buf, &rs->buf_size, 0);
1916 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1917 xfree (rs->last_program_signals_packet);
1918 rs->last_program_signals_packet = packet;
1925 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1926 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1927 thread. If GEN is set, set the general thread, if not, then set
1928 the step/continue thread. */
1930 set_thread (struct ptid ptid, int gen)
1932 struct remote_state *rs = get_remote_state ();
1933 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1934 char *buf = rs->buf;
1935 char *endbuf = rs->buf + get_remote_packet_size ();
1937 if (ptid_equal (state, ptid))
1941 *buf++ = gen ? 'g' : 'c';
1942 if (ptid_equal (ptid, magic_null_ptid))
1943 xsnprintf (buf, endbuf - buf, "0");
1944 else if (ptid_equal (ptid, any_thread_ptid))
1945 xsnprintf (buf, endbuf - buf, "0");
1946 else if (ptid_equal (ptid, minus_one_ptid))
1947 xsnprintf (buf, endbuf - buf, "-1");
1949 write_ptid (buf, endbuf, ptid);
1951 getpkt (&rs->buf, &rs->buf_size, 0);
1953 rs->general_thread = ptid;
1955 rs->continue_thread = ptid;
1959 set_general_thread (struct ptid ptid)
1961 set_thread (ptid, 1);
1965 set_continue_thread (struct ptid ptid)
1967 set_thread (ptid, 0);
1970 /* Change the remote current process. Which thread within the process
1971 ends up selected isn't important, as long as it is the same process
1972 as what INFERIOR_PTID points to.
1974 This comes from that fact that there is no explicit notion of
1975 "selected process" in the protocol. The selected process for
1976 general operations is the process the selected general thread
1980 set_general_process (void)
1982 struct remote_state *rs = get_remote_state ();
1984 /* If the remote can't handle multiple processes, don't bother. */
1985 if (!rs->extended || !remote_multi_process_p (rs))
1988 /* We only need to change the remote current thread if it's pointing
1989 at some other process. */
1990 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1991 set_general_thread (inferior_ptid);
1995 /* Return nonzero if this is the main thread that we made up ourselves
1996 to model non-threaded targets as single-threaded. */
1999 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2001 struct remote_state *rs = get_remote_state ();
2004 if (ptid_equal (ptid, magic_null_ptid))
2005 /* The main thread is always alive. */
2008 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2009 /* The main thread is always alive. This can happen after a
2010 vAttach, if the remote side doesn't support
2017 /* Return nonzero if the thread PTID is still alive on the remote
2021 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2023 struct remote_state *rs = get_remote_state ();
2026 /* Check if this is a thread that we made up ourselves to model
2027 non-threaded targets as single-threaded. */
2028 if (remote_thread_always_alive (ops, ptid))
2032 endp = rs->buf + get_remote_packet_size ();
2035 write_ptid (p, endp, ptid);
2038 getpkt (&rs->buf, &rs->buf_size, 0);
2039 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2042 /* About these extended threadlist and threadinfo packets. They are
2043 variable length packets but, the fields within them are often fixed
2044 length. They are redundent enough to send over UDP as is the
2045 remote protocol in general. There is a matching unit test module
2048 /* WARNING: This threadref data structure comes from the remote O.S.,
2049 libstub protocol encoding, and remote.c. It is not particularly
2052 /* Right now, the internal structure is int. We want it to be bigger.
2053 Plan to fix this. */
2055 typedef int gdb_threadref; /* Internal GDB thread reference. */
2057 /* gdb_ext_thread_info is an internal GDB data structure which is
2058 equivalent to the reply of the remote threadinfo packet. */
2060 struct gdb_ext_thread_info
2062 threadref threadid; /* External form of thread reference. */
2063 int active; /* Has state interesting to GDB?
2065 char display[256]; /* Brief state display, name,
2066 blocked/suspended. */
2067 char shortname[32]; /* To be used to name threads. */
2068 char more_display[256]; /* Long info, statistics, queue depth,
2072 /* The volume of remote transfers can be limited by submitting
2073 a mask containing bits specifying the desired information.
2074 Use a union of these values as the 'selection' parameter to
2075 get_thread_info. FIXME: Make these TAG names more thread specific. */
2077 #define TAG_THREADID 1
2078 #define TAG_EXISTS 2
2079 #define TAG_DISPLAY 4
2080 #define TAG_THREADNAME 8
2081 #define TAG_MOREDISPLAY 16
2083 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2085 static char *unpack_nibble (char *buf, int *val);
2087 static char *unpack_byte (char *buf, int *value);
2089 static char *pack_int (char *buf, int value);
2091 static char *unpack_int (char *buf, int *value);
2093 static char *unpack_string (char *src, char *dest, int length);
2095 static char *pack_threadid (char *pkt, threadref *id);
2097 static char *unpack_threadid (char *inbuf, threadref *id);
2099 void int_to_threadref (threadref *id, int value);
2101 static int threadref_to_int (threadref *ref);
2103 static void copy_threadref (threadref *dest, threadref *src);
2105 static int threadmatch (threadref *dest, threadref *src);
2107 static char *pack_threadinfo_request (char *pkt, int mode,
2110 static int remote_unpack_thread_info_response (char *pkt,
2111 threadref *expectedref,
2112 struct gdb_ext_thread_info
2116 static int remote_get_threadinfo (threadref *threadid,
2117 int fieldset, /*TAG mask */
2118 struct gdb_ext_thread_info *info);
2120 static char *pack_threadlist_request (char *pkt, int startflag,
2122 threadref *nextthread);
2124 static int parse_threadlist_response (char *pkt,
2126 threadref *original_echo,
2127 threadref *resultlist,
2130 static int remote_get_threadlist (int startflag,
2131 threadref *nextthread,
2135 threadref *threadlist);
2137 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2139 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2140 void *context, int looplimit);
2142 static int remote_newthread_step (threadref *ref, void *context);
2145 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2146 buffer we're allowed to write to. Returns
2147 BUF+CHARACTERS_WRITTEN. */
2150 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2153 struct remote_state *rs = get_remote_state ();
2155 if (remote_multi_process_p (rs))
2157 pid = ptid_get_pid (ptid);
2159 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2161 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2163 tid = ptid_get_lwp (ptid);
2165 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2167 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2172 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2173 passed the last parsed char. Returns null_ptid on error. */
2176 read_ptid (char *buf, char **obuf)
2180 ULONGEST pid = 0, tid = 0;
2184 /* Multi-process ptid. */
2185 pp = unpack_varlen_hex (p + 1, &pid);
2187 error (_("invalid remote ptid: %s"), p);
2190 pp = unpack_varlen_hex (p + 1, &tid);
2193 return ptid_build (pid, tid, 0);
2196 /* No multi-process. Just a tid. */
2197 pp = unpack_varlen_hex (p, &tid);
2199 /* Return null_ptid when no thread id is found. */
2207 /* Since the stub is not sending a process id, then default to
2208 what's in inferior_ptid, unless it's null at this point. If so,
2209 then since there's no way to know the pid of the reported
2210 threads, use the magic number. */
2211 if (ptid_equal (inferior_ptid, null_ptid))
2212 pid = ptid_get_pid (magic_null_ptid);
2214 pid = ptid_get_pid (inferior_ptid);
2218 return ptid_build (pid, tid, 0);
2224 if (ch >= 'a' && ch <= 'f')
2225 return ch - 'a' + 10;
2226 if (ch >= '0' && ch <= '9')
2228 if (ch >= 'A' && ch <= 'F')
2229 return ch - 'A' + 10;
2234 stub_unpack_int (char *buff, int fieldlength)
2241 nibble = stubhex (*buff++);
2245 retval = retval << 4;
2251 unpack_nibble (char *buf, int *val)
2253 *val = fromhex (*buf++);
2258 unpack_byte (char *buf, int *value)
2260 *value = stub_unpack_int (buf, 2);
2265 pack_int (char *buf, int value)
2267 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2268 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2269 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2270 buf = pack_hex_byte (buf, (value & 0xff));
2275 unpack_int (char *buf, int *value)
2277 *value = stub_unpack_int (buf, 8);
2281 #if 0 /* Currently unused, uncomment when needed. */
2282 static char *pack_string (char *pkt, char *string);
2285 pack_string (char *pkt, char *string)
2290 len = strlen (string);
2292 len = 200; /* Bigger than most GDB packets, junk??? */
2293 pkt = pack_hex_byte (pkt, len);
2297 if ((ch == '\0') || (ch == '#'))
2298 ch = '*'; /* Protect encapsulation. */
2303 #endif /* 0 (unused) */
2306 unpack_string (char *src, char *dest, int length)
2315 pack_threadid (char *pkt, threadref *id)
2318 unsigned char *altid;
2320 altid = (unsigned char *) id;
2321 limit = pkt + BUF_THREAD_ID_SIZE;
2323 pkt = pack_hex_byte (pkt, *altid++);
2329 unpack_threadid (char *inbuf, threadref *id)
2332 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2335 altref = (char *) id;
2337 while (inbuf < limit)
2339 x = stubhex (*inbuf++);
2340 y = stubhex (*inbuf++);
2341 *altref++ = (x << 4) | y;
2346 /* Externally, threadrefs are 64 bits but internally, they are still
2347 ints. This is due to a mismatch of specifications. We would like
2348 to use 64bit thread references internally. This is an adapter
2352 int_to_threadref (threadref *id, int value)
2354 unsigned char *scan;
2356 scan = (unsigned char *) id;
2362 *scan++ = (value >> 24) & 0xff;
2363 *scan++ = (value >> 16) & 0xff;
2364 *scan++ = (value >> 8) & 0xff;
2365 *scan++ = (value & 0xff);
2369 threadref_to_int (threadref *ref)
2372 unsigned char *scan;
2378 value = (value << 8) | ((*scan++) & 0xff);
2383 copy_threadref (threadref *dest, threadref *src)
2386 unsigned char *csrc, *cdest;
2388 csrc = (unsigned char *) src;
2389 cdest = (unsigned char *) dest;
2396 threadmatch (threadref *dest, threadref *src)
2398 /* Things are broken right now, so just assume we got a match. */
2400 unsigned char *srcp, *destp;
2402 srcp = (char *) src;
2403 destp = (char *) dest;
2407 result &= (*srcp++ == *destp++) ? 1 : 0;
2414 threadid:1, # always request threadid
2421 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2424 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2426 *pkt++ = 'q'; /* Info Query */
2427 *pkt++ = 'P'; /* process or thread info */
2428 pkt = pack_int (pkt, mode); /* mode */
2429 pkt = pack_threadid (pkt, id); /* threadid */
2430 *pkt = '\0'; /* terminate */
2434 /* These values tag the fields in a thread info response packet. */
2435 /* Tagging the fields allows us to request specific fields and to
2436 add more fields as time goes by. */
2438 #define TAG_THREADID 1 /* Echo the thread identifier. */
2439 #define TAG_EXISTS 2 /* Is this process defined enough to
2440 fetch registers and its stack? */
2441 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2442 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2443 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2447 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2448 struct gdb_ext_thread_info *info)
2450 struct remote_state *rs = get_remote_state ();
2454 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2457 /* info->threadid = 0; FIXME: implement zero_threadref. */
2459 info->display[0] = '\0';
2460 info->shortname[0] = '\0';
2461 info->more_display[0] = '\0';
2463 /* Assume the characters indicating the packet type have been
2465 pkt = unpack_int (pkt, &mask); /* arg mask */
2466 pkt = unpack_threadid (pkt, &ref);
2469 warning (_("Incomplete response to threadinfo request."));
2470 if (!threadmatch (&ref, expectedref))
2471 { /* This is an answer to a different request. */
2472 warning (_("ERROR RMT Thread info mismatch."));
2475 copy_threadref (&info->threadid, &ref);
2477 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2479 /* Packets are terminated with nulls. */
2480 while ((pkt < limit) && mask && *pkt)
2482 pkt = unpack_int (pkt, &tag); /* tag */
2483 pkt = unpack_byte (pkt, &length); /* length */
2484 if (!(tag & mask)) /* Tags out of synch with mask. */
2486 warning (_("ERROR RMT: threadinfo tag mismatch."));
2490 if (tag == TAG_THREADID)
2494 warning (_("ERROR RMT: length of threadid is not 16."));
2498 pkt = unpack_threadid (pkt, &ref);
2499 mask = mask & ~TAG_THREADID;
2502 if (tag == TAG_EXISTS)
2504 info->active = stub_unpack_int (pkt, length);
2506 mask = mask & ~(TAG_EXISTS);
2509 warning (_("ERROR RMT: 'exists' length too long."));
2515 if (tag == TAG_THREADNAME)
2517 pkt = unpack_string (pkt, &info->shortname[0], length);
2518 mask = mask & ~TAG_THREADNAME;
2521 if (tag == TAG_DISPLAY)
2523 pkt = unpack_string (pkt, &info->display[0], length);
2524 mask = mask & ~TAG_DISPLAY;
2527 if (tag == TAG_MOREDISPLAY)
2529 pkt = unpack_string (pkt, &info->more_display[0], length);
2530 mask = mask & ~TAG_MOREDISPLAY;
2533 warning (_("ERROR RMT: unknown thread info tag."));
2534 break; /* Not a tag we know about. */
2540 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2541 struct gdb_ext_thread_info *info)
2543 struct remote_state *rs = get_remote_state ();
2546 pack_threadinfo_request (rs->buf, fieldset, threadid);
2548 getpkt (&rs->buf, &rs->buf_size, 0);
2550 if (rs->buf[0] == '\0')
2553 result = remote_unpack_thread_info_response (rs->buf + 2,
2558 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2561 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2562 threadref *nextthread)
2564 *pkt++ = 'q'; /* info query packet */
2565 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2566 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2567 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2568 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2573 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2576 parse_threadlist_response (char *pkt, int result_limit,
2577 threadref *original_echo, threadref *resultlist,
2580 struct remote_state *rs = get_remote_state ();
2582 int count, resultcount, done;
2585 /* Assume the 'q' and 'M chars have been stripped. */
2586 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2587 /* done parse past here */
2588 pkt = unpack_byte (pkt, &count); /* count field */
2589 pkt = unpack_nibble (pkt, &done);
2590 /* The first threadid is the argument threadid. */
2591 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2592 while ((count-- > 0) && (pkt < limit))
2594 pkt = unpack_threadid (pkt, resultlist++);
2595 if (resultcount++ >= result_limit)
2603 /* Fetch the next batch of threads from the remote. Returns -1 if the
2604 qL packet is not supported, 0 on error and 1 on success. */
2607 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2608 int *done, int *result_count, threadref *threadlist)
2610 struct remote_state *rs = get_remote_state ();
2613 /* Trancate result limit to be smaller than the packet size. */
2614 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2615 >= get_remote_packet_size ())
2616 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2618 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2620 getpkt (&rs->buf, &rs->buf_size, 0);
2621 if (*rs->buf == '\0')
2623 /* Packet not supported. */
2628 parse_threadlist_response (rs->buf + 2, result_limit,
2629 &rs->echo_nextthread, threadlist, done);
2631 if (!threadmatch (&rs->echo_nextthread, nextthread))
2633 /* FIXME: This is a good reason to drop the packet. */
2634 /* Possably, there is a duplicate response. */
2636 retransmit immediatly - race conditions
2637 retransmit after timeout - yes
2639 wait for packet, then exit
2641 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2642 return 0; /* I choose simply exiting. */
2644 if (*result_count <= 0)
2648 warning (_("RMT ERROR : failed to get remote thread list."));
2651 return result; /* break; */
2653 if (*result_count > result_limit)
2656 warning (_("RMT ERROR: threadlist response longer than requested."));
2662 /* Fetch the list of remote threads, with the qL packet, and call
2663 STEPFUNCTION for each thread found. Stops iterating and returns 1
2664 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2665 STEPFUNCTION returns false. If the packet is not supported,
2669 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2672 struct remote_state *rs = get_remote_state ();
2673 int done, i, result_count;
2681 if (loopcount++ > looplimit)
2684 warning (_("Remote fetch threadlist -infinite loop-."));
2687 result = remote_get_threadlist (startflag, &rs->nextthread,
2688 MAXTHREADLISTRESULTS,
2689 &done, &result_count,
2690 rs->resultthreadlist);
2693 /* Clear for later iterations. */
2695 /* Setup to resume next batch of thread references, set nextthread. */
2696 if (result_count >= 1)
2697 copy_threadref (&rs->nextthread,
2698 &rs->resultthreadlist[result_count - 1]);
2700 while (result_count--)
2702 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2712 /* A thread found on the remote target. */
2714 typedef struct thread_item
2716 /* The thread's PTID. */
2719 /* The thread's extra info. May be NULL. */
2722 /* The core the thread was running on. -1 if not known. */
2725 DEF_VEC_O(thread_item_t);
2727 /* Context passed around to the various methods listing remote
2728 threads. As new threads are found, they're added to the ITEMS
2731 struct threads_listing_context
2733 /* The threads found on the remote target. */
2734 VEC (thread_item_t) *items;
2737 /* Discard the contents of the constructed thread listing context. */
2740 clear_threads_listing_context (void *p)
2742 struct threads_listing_context *context = p;
2744 struct thread_item *item;
2746 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2747 xfree (item->extra);
2749 VEC_free (thread_item_t, context->items);
2752 /* Remove the thread specified as the related_pid field of WS
2753 from the CONTEXT list. */
2756 threads_listing_context_remove (struct target_waitstatus *ws,
2757 struct threads_listing_context *context)
2759 struct thread_item *item;
2761 ptid_t child_ptid = ws->value.related_pid;
2763 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2765 if (ptid_equal (item->ptid, child_ptid))
2767 VEC_ordered_remove (thread_item_t, context->items, i);
2774 remote_newthread_step (threadref *ref, void *data)
2776 struct threads_listing_context *context = data;
2777 struct thread_item item;
2778 int pid = ptid_get_pid (inferior_ptid);
2780 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2784 VEC_safe_push (thread_item_t, context->items, &item);
2786 return 1; /* continue iterator */
2789 #define CRAZY_MAX_THREADS 1000
2792 remote_current_thread (ptid_t oldpid)
2794 struct remote_state *rs = get_remote_state ();
2797 getpkt (&rs->buf, &rs->buf_size, 0);
2798 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2803 result = read_ptid (&rs->buf[2], &obuf);
2804 if (*obuf != '\0' && remote_debug)
2805 fprintf_unfiltered (gdb_stdlog,
2806 "warning: garbage in qC reply\n");
2814 /* List remote threads using the deprecated qL packet. */
2817 remote_get_threads_with_ql (struct target_ops *ops,
2818 struct threads_listing_context *context)
2820 if (remote_threadlist_iterator (remote_newthread_step, context,
2821 CRAZY_MAX_THREADS) >= 0)
2827 #if defined(HAVE_LIBEXPAT)
2830 start_thread (struct gdb_xml_parser *parser,
2831 const struct gdb_xml_element *element,
2832 void *user_data, VEC(gdb_xml_value_s) *attributes)
2834 struct threads_listing_context *data = user_data;
2836 struct thread_item item;
2838 struct gdb_xml_value *attr;
2840 id = xml_find_attribute (attributes, "id")->value;
2841 item.ptid = read_ptid (id, NULL);
2843 attr = xml_find_attribute (attributes, "core");
2845 item.core = *(ULONGEST *) attr->value;
2851 VEC_safe_push (thread_item_t, data->items, &item);
2855 end_thread (struct gdb_xml_parser *parser,
2856 const struct gdb_xml_element *element,
2857 void *user_data, const char *body_text)
2859 struct threads_listing_context *data = user_data;
2861 if (body_text && *body_text)
2862 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2865 const struct gdb_xml_attribute thread_attributes[] = {
2866 { "id", GDB_XML_AF_NONE, NULL, NULL },
2867 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2868 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2871 const struct gdb_xml_element thread_children[] = {
2872 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2875 const struct gdb_xml_element threads_children[] = {
2876 { "thread", thread_attributes, thread_children,
2877 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2878 start_thread, end_thread },
2879 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2882 const struct gdb_xml_element threads_elements[] = {
2883 { "threads", NULL, threads_children,
2884 GDB_XML_EF_NONE, NULL, NULL },
2885 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2890 /* List remote threads using qXfer:threads:read. */
2893 remote_get_threads_with_qxfer (struct target_ops *ops,
2894 struct threads_listing_context *context)
2896 #if defined(HAVE_LIBEXPAT)
2897 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2899 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2900 struct cleanup *back_to = make_cleanup (xfree, xml);
2902 if (xml != NULL && *xml != '\0')
2904 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2905 threads_elements, xml, context);
2908 do_cleanups (back_to);
2916 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2919 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2920 struct threads_listing_context *context)
2922 struct remote_state *rs = get_remote_state ();
2924 if (rs->use_threadinfo_query)
2928 putpkt ("qfThreadInfo");
2929 getpkt (&rs->buf, &rs->buf_size, 0);
2931 if (bufp[0] != '\0') /* q packet recognized */
2933 while (*bufp++ == 'm') /* reply contains one or more TID */
2937 struct thread_item item;
2939 item.ptid = read_ptid (bufp, &bufp);
2943 VEC_safe_push (thread_item_t, context->items, &item);
2945 while (*bufp++ == ','); /* comma-separated list */
2946 putpkt ("qsThreadInfo");
2947 getpkt (&rs->buf, &rs->buf_size, 0);
2954 /* Packet not recognized. */
2955 rs->use_threadinfo_query = 0;
2962 /* Implement the to_update_thread_list function for the remote
2966 remote_update_thread_list (struct target_ops *ops)
2968 struct remote_state *rs = get_remote_state ();
2969 struct threads_listing_context context;
2970 struct cleanup *old_chain;
2973 context.items = NULL;
2974 old_chain = make_cleanup (clear_threads_listing_context, &context);
2976 /* We have a few different mechanisms to fetch the thread list. Try
2977 them all, starting with the most preferred one first, falling
2978 back to older methods. */
2979 if (remote_get_threads_with_qxfer (ops, &context)
2980 || remote_get_threads_with_qthreadinfo (ops, &context)
2981 || remote_get_threads_with_ql (ops, &context))
2984 struct thread_item *item;
2985 struct thread_info *tp, *tmp;
2989 if (VEC_empty (thread_item_t, context.items)
2990 && remote_thread_always_alive (ops, inferior_ptid))
2992 /* Some targets don't really support threads, but still
2993 reply an (empty) thread list in response to the thread
2994 listing packets, instead of replying "packet not
2995 supported". Exit early so we don't delete the main
2997 do_cleanups (old_chain);
3001 /* CONTEXT now holds the current thread list on the remote
3002 target end. Delete GDB-side threads no longer found on the
3004 ALL_THREADS_SAFE (tp, tmp)
3007 VEC_iterate (thread_item_t, context.items, i, item);
3010 if (ptid_equal (item->ptid, tp->ptid))
3014 if (i == VEC_length (thread_item_t, context.items))
3017 delete_thread (tp->ptid);
3021 /* Remove any unreported fork child threads from CONTEXT so
3022 that we don't interfere with follow fork, which is where
3023 creation of such threads is handled. */
3024 remove_new_fork_children (&context);
3026 /* And now add threads we don't know about yet to our list. */
3028 VEC_iterate (thread_item_t, context.items, i, item);
3031 if (!ptid_equal (item->ptid, null_ptid))
3033 struct private_thread_info *info;
3034 /* In non-stop mode, we assume new found threads are
3035 running until proven otherwise with a stop reply. In
3036 all-stop, we can only get here if all threads are
3038 int running = non_stop ? 1 : 0;
3040 remote_notice_new_inferior (item->ptid, running);
3042 info = demand_private_info (item->ptid);
3043 info->core = item->core;
3044 info->extra = item->extra;
3052 /* If no thread listing method is supported, then query whether
3053 each known thread is alive, one by one, with the T packet.
3054 If the target doesn't support threads at all, then this is a
3055 no-op. See remote_thread_alive. */
3059 do_cleanups (old_chain);
3063 * Collect a descriptive string about the given thread.
3064 * The target may say anything it wants to about the thread
3065 * (typically info about its blocked / runnable state, name, etc.).
3066 * This string will appear in the info threads display.
3068 * Optional: targets are not required to implement this function.
3072 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3074 struct remote_state *rs = get_remote_state ();
3078 struct gdb_ext_thread_info threadinfo;
3079 static char display_buf[100]; /* arbitrary... */
3080 int n = 0; /* position in display_buf */
3082 if (rs->remote_desc == 0) /* paranoia */
3083 internal_error (__FILE__, __LINE__,
3084 _("remote_threads_extra_info"));
3086 if (ptid_equal (tp->ptid, magic_null_ptid)
3087 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3088 /* This is the main thread which was added by GDB. The remote
3089 server doesn't know about it. */
3092 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3094 struct thread_info *info = find_thread_ptid (tp->ptid);
3096 if (info && info->priv)
3097 return info->priv->extra;
3102 if (rs->use_threadextra_query)
3105 char *endb = rs->buf + get_remote_packet_size ();
3107 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3109 write_ptid (b, endb, tp->ptid);
3112 getpkt (&rs->buf, &rs->buf_size, 0);
3113 if (rs->buf[0] != 0)
3115 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3116 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3117 display_buf [result] = '\0';
3122 /* If the above query fails, fall back to the old method. */
3123 rs->use_threadextra_query = 0;
3124 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3125 | TAG_MOREDISPLAY | TAG_DISPLAY;
3126 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3127 if (remote_get_threadinfo (&id, set, &threadinfo))
3128 if (threadinfo.active)
3130 if (*threadinfo.shortname)
3131 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3132 " Name: %s,", threadinfo.shortname);
3133 if (*threadinfo.display)
3134 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3135 " State: %s,", threadinfo.display);
3136 if (*threadinfo.more_display)
3137 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3138 " Priority: %s", threadinfo.more_display);
3142 /* For purely cosmetic reasons, clear up trailing commas. */
3143 if (',' == display_buf[n-1])
3144 display_buf[n-1] = ' ';
3153 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3154 struct static_tracepoint_marker *marker)
3156 struct remote_state *rs = get_remote_state ();
3159 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3161 p += hexnumstr (p, addr);
3163 getpkt (&rs->buf, &rs->buf_size, 0);
3167 error (_("Remote failure reply: %s"), p);
3171 parse_static_tracepoint_marker_definition (p, &p, marker);
3178 static VEC(static_tracepoint_marker_p) *
3179 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3182 struct remote_state *rs = get_remote_state ();
3183 VEC(static_tracepoint_marker_p) *markers = NULL;
3184 struct static_tracepoint_marker *marker = NULL;
3185 struct cleanup *old_chain;
3188 /* Ask for a first packet of static tracepoint marker
3191 getpkt (&rs->buf, &rs->buf_size, 0);
3194 error (_("Remote failure reply: %s"), p);
3196 old_chain = make_cleanup (free_current_marker, &marker);
3201 marker = XCNEW (struct static_tracepoint_marker);
3205 parse_static_tracepoint_marker_definition (p, &p, marker);
3207 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3209 VEC_safe_push (static_tracepoint_marker_p,
3215 release_static_tracepoint_marker (marker);
3216 memset (marker, 0, sizeof (*marker));
3219 while (*p++ == ','); /* comma-separated list */
3220 /* Ask for another packet of static tracepoint definition. */
3222 getpkt (&rs->buf, &rs->buf_size, 0);
3226 do_cleanups (old_chain);
3231 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3234 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3236 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3240 /* Restart the remote side; this is an extended protocol operation. */
3243 extended_remote_restart (void)
3245 struct remote_state *rs = get_remote_state ();
3247 /* Send the restart command; for reasons I don't understand the
3248 remote side really expects a number after the "R". */
3249 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3252 remote_fileio_reset ();
3255 /* Clean up connection to a remote debugger. */
3258 remote_close (struct target_ops *self)
3260 struct remote_state *rs = get_remote_state ();
3262 if (rs->remote_desc == NULL)
3263 return; /* already closed */
3265 /* Make sure we leave stdin registered in the event loop, and we
3266 don't leave the async SIGINT signal handler installed. */
3267 remote_terminal_ours (self);
3269 serial_close (rs->remote_desc);
3270 rs->remote_desc = NULL;
3272 /* We don't have a connection to the remote stub anymore. Get rid
3273 of all the inferiors and their threads we were controlling.
3274 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3275 will be unable to find the thread corresponding to (pid, 0, 0). */
3276 inferior_ptid = null_ptid;
3277 discard_all_inferiors ();
3279 /* We are closing the remote target, so we should discard
3280 everything of this target. */
3281 discard_pending_stop_replies_in_queue (rs);
3283 if (remote_async_inferior_event_token)
3284 delete_async_event_handler (&remote_async_inferior_event_token);
3286 remote_notif_state_xfree (rs->notif_state);
3288 trace_reset_local_state ();
3291 /* Query the remote side for the text, data and bss offsets. */
3296 struct remote_state *rs = get_remote_state ();
3299 int lose, num_segments = 0, do_sections, do_segments;
3300 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3301 struct section_offsets *offs;
3302 struct symfile_segment_data *data;
3304 if (symfile_objfile == NULL)
3307 putpkt ("qOffsets");
3308 getpkt (&rs->buf, &rs->buf_size, 0);
3311 if (buf[0] == '\000')
3312 return; /* Return silently. Stub doesn't support
3316 warning (_("Remote failure reply: %s"), buf);
3320 /* Pick up each field in turn. This used to be done with scanf, but
3321 scanf will make trouble if CORE_ADDR size doesn't match
3322 conversion directives correctly. The following code will work
3323 with any size of CORE_ADDR. */
3324 text_addr = data_addr = bss_addr = 0;
3328 if (startswith (ptr, "Text="))
3331 /* Don't use strtol, could lose on big values. */
3332 while (*ptr && *ptr != ';')
3333 text_addr = (text_addr << 4) + fromhex (*ptr++);
3335 if (startswith (ptr, ";Data="))
3338 while (*ptr && *ptr != ';')
3339 data_addr = (data_addr << 4) + fromhex (*ptr++);
3344 if (!lose && startswith (ptr, ";Bss="))
3347 while (*ptr && *ptr != ';')
3348 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3350 if (bss_addr != data_addr)
3351 warning (_("Target reported unsupported offsets: %s"), buf);
3356 else if (startswith (ptr, "TextSeg="))
3359 /* Don't use strtol, could lose on big values. */
3360 while (*ptr && *ptr != ';')
3361 text_addr = (text_addr << 4) + fromhex (*ptr++);
3364 if (startswith (ptr, ";DataSeg="))
3367 while (*ptr && *ptr != ';')
3368 data_addr = (data_addr << 4) + fromhex (*ptr++);
3376 error (_("Malformed response to offset query, %s"), buf);
3377 else if (*ptr != '\0')
3378 warning (_("Target reported unsupported offsets: %s"), buf);
3380 offs = ((struct section_offsets *)
3381 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3382 memcpy (offs, symfile_objfile->section_offsets,
3383 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3385 data = get_symfile_segment_data (symfile_objfile->obfd);
3386 do_segments = (data != NULL);
3387 do_sections = num_segments == 0;
3389 if (num_segments > 0)
3391 segments[0] = text_addr;
3392 segments[1] = data_addr;
3394 /* If we have two segments, we can still try to relocate everything
3395 by assuming that the .text and .data offsets apply to the whole
3396 text and data segments. Convert the offsets given in the packet
3397 to base addresses for symfile_map_offsets_to_segments. */
3398 else if (data && data->num_segments == 2)
3400 segments[0] = data->segment_bases[0] + text_addr;
3401 segments[1] = data->segment_bases[1] + data_addr;
3404 /* If the object file has only one segment, assume that it is text
3405 rather than data; main programs with no writable data are rare,
3406 but programs with no code are useless. Of course the code might
3407 have ended up in the data segment... to detect that we would need
3408 the permissions here. */
3409 else if (data && data->num_segments == 1)
3411 segments[0] = data->segment_bases[0] + text_addr;
3414 /* There's no way to relocate by segment. */
3420 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3421 offs, num_segments, segments);
3423 if (ret == 0 && !do_sections)
3424 error (_("Can not handle qOffsets TextSeg "
3425 "response with this symbol file"));
3432 free_symfile_segment_data (data);
3436 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3438 /* This is a temporary kludge to force data and bss to use the
3439 same offsets because that's what nlmconv does now. The real
3440 solution requires changes to the stub and remote.c that I
3441 don't have time to do right now. */
3443 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3444 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3447 objfile_relocate (symfile_objfile, offs);
3450 /* Send interrupt_sequence to remote target. */
3452 send_interrupt_sequence (void)
3454 struct remote_state *rs = get_remote_state ();
3456 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3457 remote_serial_write ("\x03", 1);
3458 else if (interrupt_sequence_mode == interrupt_sequence_break)
3459 serial_send_break (rs->remote_desc);
3460 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3462 serial_send_break (rs->remote_desc);
3463 remote_serial_write ("g", 1);
3466 internal_error (__FILE__, __LINE__,
3467 _("Invalid value for interrupt_sequence_mode: %s."),
3468 interrupt_sequence_mode);
3472 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3473 and extract the PTID. Returns NULL_PTID if not found. */
3476 stop_reply_extract_thread (char *stop_reply)
3478 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3482 /* Txx r:val ; r:val (...) */
3485 /* Look for "register" named "thread". */
3490 p1 = strchr (p, ':');
3494 if (strncmp (p, "thread", p1 - p) == 0)
3495 return read_ptid (++p1, &p);
3497 p1 = strchr (p, ';');
3509 /* Determine the remote side's current thread. If we have a stop
3510 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3511 "thread" register we can extract the current thread from. If not,
3512 ask the remote which is the current thread with qC. The former
3513 method avoids a roundtrip. */
3516 get_current_thread (char *wait_status)
3518 ptid_t ptid = null_ptid;
3520 /* Note we don't use remote_parse_stop_reply as that makes use of
3521 the target architecture, which we haven't yet fully determined at
3523 if (wait_status != NULL)
3524 ptid = stop_reply_extract_thread (wait_status);
3525 if (ptid_equal (ptid, null_ptid))
3526 ptid = remote_current_thread (inferior_ptid);
3531 /* Query the remote target for which is the current thread/process,
3532 add it to our tables, and update INFERIOR_PTID. The caller is
3533 responsible for setting the state such that the remote end is ready
3534 to return the current thread.
3536 This function is called after handling the '?' or 'vRun' packets,
3537 whose response is a stop reply from which we can also try
3538 extracting the thread. If the target doesn't support the explicit
3539 qC query, we infer the current thread from that stop reply, passed
3540 in in WAIT_STATUS, which may be NULL. */
3543 add_current_inferior_and_thread (char *wait_status)
3545 struct remote_state *rs = get_remote_state ();
3549 inferior_ptid = null_ptid;
3551 /* Now, if we have thread information, update inferior_ptid. */
3552 ptid = get_current_thread (wait_status);
3554 if (!ptid_equal (ptid, null_ptid))
3556 if (!remote_multi_process_p (rs))
3559 inferior_ptid = ptid;
3563 /* Without this, some commands which require an active target
3564 (such as kill) won't work. This variable serves (at least)
3565 double duty as both the pid of the target process (if it has
3566 such), and as a flag indicating that a target is active. */
3567 inferior_ptid = magic_null_ptid;
3571 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3573 /* Add the main thread. */
3574 add_thread_silent (inferior_ptid);
3577 /* Process all initial stop replies the remote side sent in response
3578 to the ? packet. These indicate threads that were already stopped
3579 on initial connection. We mark these threads as stopped and print
3580 their current frame before giving the user the prompt. */
3583 process_initial_stop_replies (void)
3585 int pending_stop_replies = stop_reply_queue_length ();
3587 /* Consume the initial pending events. */
3588 while (pending_stop_replies-- > 0)
3590 ptid_t waiton_ptid = minus_one_ptid;
3592 struct target_waitstatus ws;
3593 int ignore_event = 0;
3595 memset (&ws, 0, sizeof (ws));
3596 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3598 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3602 case TARGET_WAITKIND_IGNORE:
3603 case TARGET_WAITKIND_NO_RESUMED:
3604 case TARGET_WAITKIND_SIGNALLED:
3605 case TARGET_WAITKIND_EXITED:
3606 /* We shouldn't see these, but if we do, just ignore. */
3608 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3612 case TARGET_WAITKIND_EXECD:
3613 xfree (ws.value.execd_pathname);
3622 switch_to_thread (event_ptid);
3623 set_executing (event_ptid, 0);
3624 set_running (event_ptid, 0);
3626 stop_pc = get_frame_pc (get_current_frame ());
3627 set_current_sal_from_frame (get_current_frame ());
3629 if (ws.kind == TARGET_WAITKIND_STOPPED)
3631 enum gdb_signal sig = ws.value.sig;
3633 /* Stubs traditionally report SIGTRAP as initial signal,
3634 instead of signal 0. Suppress it. */
3635 if (sig == GDB_SIGNAL_TRAP)
3637 inferior_thread ()->suspend.stop_signal = sig;
3639 if (signal_print_state (sig))
3640 observer_notify_signal_received (sig);
3643 print_stop_event (&ws);
3644 observer_notify_normal_stop (NULL, 1);
3649 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3651 struct remote_state *rs = get_remote_state ();
3652 struct packet_config *noack_config;
3653 char *wait_status = NULL;
3655 immediate_quit++; /* Allow user to interrupt it. */
3658 if (interrupt_on_connect)
3659 send_interrupt_sequence ();
3661 /* Ack any packet which the remote side has already sent. */
3662 serial_write (rs->remote_desc, "+", 1);
3664 /* Signal other parts that we're going through the initial setup,
3665 and so things may not be stable yet. */
3666 rs->starting_up = 1;
3668 /* The first packet we send to the target is the optional "supported
3669 packets" request. If the target can answer this, it will tell us
3670 which later probes to skip. */
3671 remote_query_supported ();
3673 /* If the stub wants to get a QAllow, compose one and send it. */
3674 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3675 remote_set_permissions (target);
3677 /* Next, we possibly activate noack mode.
3679 If the QStartNoAckMode packet configuration is set to AUTO,
3680 enable noack mode if the stub reported a wish for it with
3683 If set to TRUE, then enable noack mode even if the stub didn't
3684 report it in qSupported. If the stub doesn't reply OK, the
3685 session ends with an error.
3687 If FALSE, then don't activate noack mode, regardless of what the
3688 stub claimed should be the default with qSupported. */
3690 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3691 if (packet_config_support (noack_config) != PACKET_DISABLE)
3693 putpkt ("QStartNoAckMode");
3694 getpkt (&rs->buf, &rs->buf_size, 0);
3695 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3701 /* Tell the remote that we are using the extended protocol. */
3703 getpkt (&rs->buf, &rs->buf_size, 0);
3706 /* Let the target know which signals it is allowed to pass down to
3708 update_signals_program_target ();
3710 /* Next, if the target can specify a description, read it. We do
3711 this before anything involving memory or registers. */
3712 target_find_description ();
3714 /* Next, now that we know something about the target, update the
3715 address spaces in the program spaces. */
3716 update_address_spaces ();
3718 /* On OSs where the list of libraries is global to all
3719 processes, we fetch them early. */
3720 if (gdbarch_has_global_solist (target_gdbarch ()))
3721 solib_add (NULL, from_tty, target, auto_solib_add);
3725 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3726 error (_("Non-stop mode requested, but remote "
3727 "does not support non-stop"));
3729 putpkt ("QNonStop:1");
3730 getpkt (&rs->buf, &rs->buf_size, 0);
3732 if (strcmp (rs->buf, "OK") != 0)
3733 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3735 /* Find about threads and processes the stub is already
3736 controlling. We default to adding them in the running state.
3737 The '?' query below will then tell us about which threads are
3739 remote_update_thread_list (target);
3741 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3743 /* Don't assume that the stub can operate in all-stop mode.
3744 Request it explicitly. */
3745 putpkt ("QNonStop:0");
3746 getpkt (&rs->buf, &rs->buf_size, 0);
3748 if (strcmp (rs->buf, "OK") != 0)
3749 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3752 /* Upload TSVs regardless of whether the target is running or not. The
3753 remote stub, such as GDBserver, may have some predefined or builtin
3754 TSVs, even if the target is not running. */
3755 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3757 struct uploaded_tsv *uploaded_tsvs = NULL;
3759 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3760 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3763 /* Check whether the target is running now. */
3765 getpkt (&rs->buf, &rs->buf_size, 0);
3771 struct inferior *inf;
3773 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3776 error (_("The target is not running (try extended-remote?)"));
3778 /* We're connected, but not running. Drop out before we
3779 call start_remote. */
3780 rs->starting_up = 0;
3785 /* Save the reply for later. */
3786 wait_status = alloca (strlen (rs->buf) + 1);
3787 strcpy (wait_status, rs->buf);
3790 /* Fetch thread list. */
3791 target_update_thread_list ();
3793 /* Let the stub know that we want it to return the thread. */
3794 set_continue_thread (minus_one_ptid);
3796 if (thread_count () == 0)
3798 /* Target has no concept of threads at all. GDB treats
3799 non-threaded target as single-threaded; add a main
3801 add_current_inferior_and_thread (wait_status);
3805 /* We have thread information; select the thread the target
3806 says should be current. If we're reconnecting to a
3807 multi-threaded program, this will ideally be the thread
3808 that last reported an event before GDB disconnected. */
3809 inferior_ptid = get_current_thread (wait_status);
3810 if (ptid_equal (inferior_ptid, null_ptid))
3812 /* Odd... The target was able to list threads, but not
3813 tell us which thread was current (no "thread"
3814 register in T stop reply?). Just pick the first
3815 thread in the thread list then. */
3818 fprintf_unfiltered (gdb_stdlog,
3819 "warning: couldn't determine remote "
3820 "current thread; picking first in list.\n");
3822 inferior_ptid = thread_list->ptid;
3826 /* init_wait_for_inferior should be called before get_offsets in order
3827 to manage `inserted' flag in bp loc in a correct state.
3828 breakpoint_init_inferior, called from init_wait_for_inferior, set
3829 `inserted' flag to 0, while before breakpoint_re_set, called from
3830 start_remote, set `inserted' flag to 1. In the initialization of
3831 inferior, breakpoint_init_inferior should be called first, and then
3832 breakpoint_re_set can be called. If this order is broken, state of
3833 `inserted' flag is wrong, and cause some problems on breakpoint
3835 init_wait_for_inferior ();
3837 get_offsets (); /* Get text, data & bss offsets. */
3839 /* If we could not find a description using qXfer, and we know
3840 how to do it some other way, try again. This is not
3841 supported for non-stop; it could be, but it is tricky if
3842 there are no stopped threads when we connect. */
3843 if (remote_read_description_p (target)
3844 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3846 target_clear_description ();
3847 target_find_description ();
3850 /* Use the previously fetched status. */
3851 gdb_assert (wait_status != NULL);
3852 strcpy (rs->buf, wait_status);
3853 rs->cached_wait_status = 1;
3856 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3860 ptid_t current_ptid;
3862 /* Clear WFI global state. Do this before finding about new
3863 threads and inferiors, and setting the current inferior.
3864 Otherwise we would clear the proceed status of the current
3865 inferior when we want its stop_soon state to be preserved
3866 (see notice_new_inferior). */
3867 init_wait_for_inferior ();
3869 /* In non-stop, we will either get an "OK", meaning that there
3870 are no stopped threads at this time; or, a regular stop
3871 reply. In the latter case, there may be more than one thread
3872 stopped --- we pull them all out using the vStopped
3874 if (strcmp (rs->buf, "OK") != 0)
3876 struct notif_client *notif = ¬if_client_stop;
3878 /* remote_notif_get_pending_replies acks this one, and gets
3880 rs->notif_state->pending_event[notif_client_stop.id]
3881 = remote_notif_parse (notif, rs->buf);
3882 remote_notif_get_pending_events (notif);
3885 if (thread_count () == 0)
3888 error (_("The target is not running (try extended-remote?)"));
3890 /* We're connected, but not running. Drop out before we
3891 call start_remote. */
3892 rs->starting_up = 0;
3896 /* Let the stub know that we want it to return the thread. */
3898 /* Force the stub to choose a thread. */
3899 set_general_thread (null_ptid);
3902 current_ptid = remote_current_thread (minus_one_ptid);
3903 if (ptid_equal (inferior_ptid, minus_one_ptid))
3904 error (_("remote didn't report the current thread in non-stop mode"));
3906 inferior_ptid = current_ptid;
3907 get_offsets (); /* Get text, data & bss offsets. */
3909 /* In non-stop mode, any cached wait status will be stored in
3910 the stop reply queue. */
3911 gdb_assert (wait_status == NULL);
3913 /* Report all signals during attach/startup. */
3914 remote_pass_signals (target, 0, NULL);
3916 /* If there are already stopped threads, mark them stopped and
3917 report their stops before giving the prompt to the user. */
3918 process_initial_stop_replies ();
3920 switch_to_thread (current_ptid);
3922 if (target_can_async_p ())
3926 /* If we connected to a live target, do some additional setup. */
3927 if (target_has_execution)
3929 if (symfile_objfile) /* No use without a symbol-file. */
3930 remote_check_symbols ();
3933 /* Possibly the target has been engaged in a trace run started
3934 previously; find out where things are at. */
3935 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3937 struct uploaded_tp *uploaded_tps = NULL;
3939 if (current_trace_status ()->running)
3940 printf_filtered (_("Trace is already running on the target.\n"));
3942 remote_upload_tracepoints (target, &uploaded_tps);
3944 merge_uploaded_tracepoints (&uploaded_tps);
3947 /* The thread and inferior lists are now synchronized with the
3948 target, our symbols have been relocated, and we're merged the
3949 target's tracepoints with ours. We're done with basic start
3951 rs->starting_up = 0;
3953 /* Maybe breakpoints are global and need to be inserted now. */
3954 if (breakpoints_should_be_inserted_now ())
3955 insert_breakpoints ();
3958 /* Open a connection to a remote debugger.
3959 NAME is the filename used for communication. */
3962 remote_open (const char *name, int from_tty)
3964 remote_open_1 (name, from_tty, &remote_ops, 0);
3967 /* Open a connection to a remote debugger using the extended
3968 remote gdb protocol. NAME is the filename used for communication. */
3971 extended_remote_open (const char *name, int from_tty)
3973 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3976 /* Reset all packets back to "unknown support". Called when opening a
3977 new connection to a remote target. */
3980 reset_all_packet_configs_support (void)
3984 for (i = 0; i < PACKET_MAX; i++)
3985 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3988 /* Initialize all packet configs. */
3991 init_all_packet_configs (void)
3995 for (i = 0; i < PACKET_MAX; i++)
3997 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3998 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4002 /* Symbol look-up. */
4005 remote_check_symbols (void)
4007 struct remote_state *rs = get_remote_state ();
4008 char *msg, *reply, *tmp;
4009 struct bound_minimal_symbol sym;
4012 /* The remote side has no concept of inferiors that aren't running
4013 yet, it only knows about running processes. If we're connected
4014 but our current inferior is not running, we should not invite the
4015 remote target to request symbol lookups related to its
4016 (unrelated) current process. */
4017 if (!target_has_execution)
4020 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4023 /* Make sure the remote is pointing at the right process. Note
4024 there's no way to select "no process". */
4025 set_general_process ();
4027 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4028 because we need both at the same time. */
4029 msg = alloca (get_remote_packet_size ());
4031 /* Invite target to request symbol lookups. */
4033 putpkt ("qSymbol::");
4034 getpkt (&rs->buf, &rs->buf_size, 0);
4035 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4038 while (startswith (reply, "qSymbol:"))
4040 struct bound_minimal_symbol sym;
4043 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4045 sym = lookup_minimal_symbol (msg, NULL, NULL);
4046 if (sym.minsym == NULL)
4047 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4050 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4051 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4053 /* If this is a function address, return the start of code
4054 instead of any data function descriptor. */
4055 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4059 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4060 phex_nz (sym_addr, addr_size), &reply[8]);
4064 getpkt (&rs->buf, &rs->buf_size, 0);
4069 static struct serial *
4070 remote_serial_open (const char *name)
4072 static int udp_warning = 0;
4074 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4075 of in ser-tcp.c, because it is the remote protocol assuming that the
4076 serial connection is reliable and not the serial connection promising
4078 if (!udp_warning && startswith (name, "udp:"))
4080 warning (_("The remote protocol may be unreliable over UDP.\n"
4081 "Some events may be lost, rendering further debugging "
4086 return serial_open (name);
4089 /* Inform the target of our permission settings. The permission flags
4090 work without this, but if the target knows the settings, it can do
4091 a couple things. First, it can add its own check, to catch cases
4092 that somehow manage to get by the permissions checks in target
4093 methods. Second, if the target is wired to disallow particular
4094 settings (for instance, a system in the field that is not set up to
4095 be able to stop at a breakpoint), it can object to any unavailable
4099 remote_set_permissions (struct target_ops *self)
4101 struct remote_state *rs = get_remote_state ();
4103 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4104 "WriteReg:%x;WriteMem:%x;"
4105 "InsertBreak:%x;InsertTrace:%x;"
4106 "InsertFastTrace:%x;Stop:%x",
4107 may_write_registers, may_write_memory,
4108 may_insert_breakpoints, may_insert_tracepoints,
4109 may_insert_fast_tracepoints, may_stop);
4111 getpkt (&rs->buf, &rs->buf_size, 0);
4113 /* If the target didn't like the packet, warn the user. Do not try
4114 to undo the user's settings, that would just be maddening. */
4115 if (strcmp (rs->buf, "OK") != 0)
4116 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4119 /* This type describes each known response to the qSupported
4121 struct protocol_feature
4123 /* The name of this protocol feature. */
4126 /* The default for this protocol feature. */
4127 enum packet_support default_support;
4129 /* The function to call when this feature is reported, or after
4130 qSupported processing if the feature is not supported.
4131 The first argument points to this structure. The second
4132 argument indicates whether the packet requested support be
4133 enabled, disabled, or probed (or the default, if this function
4134 is being called at the end of processing and this feature was
4135 not reported). The third argument may be NULL; if not NULL, it
4136 is a NUL-terminated string taken from the packet following
4137 this feature's name and an equals sign. */
4138 void (*func) (const struct protocol_feature *, enum packet_support,
4141 /* The corresponding packet for this feature. Only used if
4142 FUNC is remote_supported_packet. */
4147 remote_supported_packet (const struct protocol_feature *feature,
4148 enum packet_support support,
4149 const char *argument)
4153 warning (_("Remote qSupported response supplied an unexpected value for"
4154 " \"%s\"."), feature->name);
4158 remote_protocol_packets[feature->packet].support = support;
4162 remote_packet_size (const struct protocol_feature *feature,
4163 enum packet_support support, const char *value)
4165 struct remote_state *rs = get_remote_state ();
4170 if (support != PACKET_ENABLE)
4173 if (value == NULL || *value == '\0')
4175 warning (_("Remote target reported \"%s\" without a size."),
4181 packet_size = strtol (value, &value_end, 16);
4182 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4184 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4185 feature->name, value);
4189 if (packet_size > MAX_REMOTE_PACKET_SIZE)
4191 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
4192 packet_size, MAX_REMOTE_PACKET_SIZE);
4193 packet_size = MAX_REMOTE_PACKET_SIZE;
4196 /* Record the new maximum packet size. */
4197 rs->explicit_packet_size = packet_size;
4200 static const struct protocol_feature remote_protocol_features[] = {
4201 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4202 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4203 PACKET_qXfer_auxv },
4204 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4205 PACKET_qXfer_exec_file },
4206 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4207 PACKET_qXfer_features },
4208 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4209 PACKET_qXfer_libraries },
4210 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4211 PACKET_qXfer_libraries_svr4 },
4212 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4213 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4214 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4215 PACKET_qXfer_memory_map },
4216 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4217 PACKET_qXfer_spu_read },
4218 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4219 PACKET_qXfer_spu_write },
4220 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4221 PACKET_qXfer_osdata },
4222 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4223 PACKET_qXfer_threads },
4224 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4225 PACKET_qXfer_traceframe_info },
4226 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4227 PACKET_QPassSignals },
4228 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4229 PACKET_QProgramSignals },
4230 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4231 PACKET_QStartNoAckMode },
4232 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4233 PACKET_multiprocess_feature },
4234 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4235 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4236 PACKET_qXfer_siginfo_read },
4237 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4238 PACKET_qXfer_siginfo_write },
4239 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4240 PACKET_ConditionalTracepoints },
4241 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4242 PACKET_ConditionalBreakpoints },
4243 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4244 PACKET_BreakpointCommands },
4245 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4246 PACKET_FastTracepoints },
4247 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4248 PACKET_StaticTracepoints },
4249 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4250 PACKET_InstallInTrace},
4251 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4252 PACKET_DisconnectedTracing_feature },
4253 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4255 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4257 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4258 PACKET_TracepointSource },
4259 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4261 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4262 PACKET_EnableDisableTracepoints_feature },
4263 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4264 PACKET_qXfer_fdpic },
4265 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4267 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4268 PACKET_QDisableRandomization },
4269 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4270 { "QTBuffer:size", PACKET_DISABLE,
4271 remote_supported_packet, PACKET_QTBuffer_size},
4272 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4273 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4274 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4275 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4276 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4277 PACKET_qXfer_btrace },
4278 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4279 PACKET_qXfer_btrace_conf },
4280 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4281 PACKET_Qbtrace_conf_bts_size },
4282 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4283 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4284 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4285 PACKET_fork_event_feature },
4286 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4287 PACKET_vfork_event_feature },
4288 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4289 PACKET_Qbtrace_conf_pt_size }
4292 static char *remote_support_xml;
4294 /* Register string appended to "xmlRegisters=" in qSupported query. */
4297 register_remote_support_xml (const char *xml)
4299 #if defined(HAVE_LIBEXPAT)
4300 if (remote_support_xml == NULL)
4301 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4304 char *copy = xstrdup (remote_support_xml + 13);
4305 char *p = strtok (copy, ",");
4309 if (strcmp (p, xml) == 0)
4316 while ((p = strtok (NULL, ",")) != NULL);
4319 remote_support_xml = reconcat (remote_support_xml,
4320 remote_support_xml, ",", xml,
4327 remote_query_supported_append (char *msg, const char *append)
4330 return reconcat (msg, msg, ";", append, (char *) NULL);
4332 return xstrdup (append);
4336 remote_query_supported (void)
4338 struct remote_state *rs = get_remote_state ();
4341 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4343 /* The packet support flags are handled differently for this packet
4344 than for most others. We treat an error, a disabled packet, and
4345 an empty response identically: any features which must be reported
4346 to be used will be automatically disabled. An empty buffer
4347 accomplishes this, since that is also the representation for a list
4348 containing no features. */
4351 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4354 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4356 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4357 q = remote_query_supported_append (q, "multiprocess+");
4359 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4360 q = remote_query_supported_append (q, "swbreak+");
4361 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4362 q = remote_query_supported_append (q, "hwbreak+");
4364 if (remote_support_xml)
4365 q = remote_query_supported_append (q, remote_support_xml);
4367 q = remote_query_supported_append (q, "qRelocInsn+");
4371 if (packet_set_cmd_state (PACKET_fork_event_feature)
4372 != AUTO_BOOLEAN_FALSE)
4373 q = remote_query_supported_append (q, "fork-events+");
4374 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4375 != AUTO_BOOLEAN_FALSE)
4376 q = remote_query_supported_append (q, "vfork-events+");
4379 q = reconcat (q, "qSupported:", q, (char *) NULL);
4382 do_cleanups (old_chain);
4384 getpkt (&rs->buf, &rs->buf_size, 0);
4386 /* If an error occured, warn, but do not return - just reset the
4387 buffer to empty and go on to disable features. */
4388 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4391 warning (_("Remote failure reply: %s"), rs->buf);
4396 memset (seen, 0, sizeof (seen));
4401 enum packet_support is_supported;
4402 char *p, *end, *name_end, *value;
4404 /* First separate out this item from the rest of the packet. If
4405 there's another item after this, we overwrite the separator
4406 (terminated strings are much easier to work with). */
4408 end = strchr (p, ';');
4411 end = p + strlen (p);
4421 warning (_("empty item in \"qSupported\" response"));
4426 name_end = strchr (p, '=');
4429 /* This is a name=value entry. */
4430 is_supported = PACKET_ENABLE;
4431 value = name_end + 1;
4440 is_supported = PACKET_ENABLE;
4444 is_supported = PACKET_DISABLE;
4448 is_supported = PACKET_SUPPORT_UNKNOWN;
4452 warning (_("unrecognized item \"%s\" "
4453 "in \"qSupported\" response"), p);
4459 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4460 if (strcmp (remote_protocol_features[i].name, p) == 0)
4462 const struct protocol_feature *feature;
4465 feature = &remote_protocol_features[i];
4466 feature->func (feature, is_supported, value);
4471 /* If we increased the packet size, make sure to increase the global
4472 buffer size also. We delay this until after parsing the entire
4473 qSupported packet, because this is the same buffer we were
4475 if (rs->buf_size < rs->explicit_packet_size)
4477 rs->buf_size = rs->explicit_packet_size;
4478 rs->buf = xrealloc (rs->buf, rs->buf_size);
4481 /* Handle the defaults for unmentioned features. */
4482 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4485 const struct protocol_feature *feature;
4487 feature = &remote_protocol_features[i];
4488 feature->func (feature, feature->default_support, NULL);
4492 /* Remove any of the remote.c targets from target stack. Upper targets depend
4493 on it so remove them first. */
4496 remote_unpush_target (void)
4498 pop_all_targets_above (process_stratum - 1);
4502 remote_open_1 (const char *name, int from_tty,
4503 struct target_ops *target, int extended_p)
4505 struct remote_state *rs = get_remote_state ();
4508 error (_("To open a remote debug connection, you need to specify what\n"
4509 "serial device is attached to the remote system\n"
4510 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4512 /* See FIXME above. */
4513 if (!target_async_permitted)
4514 wait_forever_enabled_p = 1;
4516 /* If we're connected to a running target, target_preopen will kill it.
4517 Ask this question first, before target_preopen has a chance to kill
4519 if (rs->remote_desc != NULL && !have_inferiors ())
4522 && !query (_("Already connected to a remote target. Disconnect? ")))
4523 error (_("Still connected."));
4526 /* Here the possibly existing remote target gets unpushed. */
4527 target_preopen (from_tty);
4529 /* Make sure we send the passed signals list the next time we resume. */
4530 xfree (rs->last_pass_packet);
4531 rs->last_pass_packet = NULL;
4533 /* Make sure we send the program signals list the next time we
4535 xfree (rs->last_program_signals_packet);
4536 rs->last_program_signals_packet = NULL;
4538 remote_fileio_reset ();
4539 reopen_exec_file ();
4542 rs->remote_desc = remote_serial_open (name);
4543 if (!rs->remote_desc)
4544 perror_with_name (name);
4546 if (baud_rate != -1)
4548 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4550 /* The requested speed could not be set. Error out to
4551 top level after closing remote_desc. Take care to
4552 set remote_desc to NULL to avoid closing remote_desc
4554 serial_close (rs->remote_desc);
4555 rs->remote_desc = NULL;
4556 perror_with_name (name);
4560 serial_setparity (rs->remote_desc, serial_parity);
4561 serial_raw (rs->remote_desc);
4563 /* If there is something sitting in the buffer we might take it as a
4564 response to a command, which would be bad. */
4565 serial_flush_input (rs->remote_desc);
4569 puts_filtered ("Remote debugging using ");
4570 puts_filtered (name);
4571 puts_filtered ("\n");
4573 push_target (target); /* Switch to using remote target now. */
4575 /* Register extra event sources in the event loop. */
4576 remote_async_inferior_event_token
4577 = create_async_event_handler (remote_async_inferior_event_handler,
4579 rs->notif_state = remote_notif_state_allocate ();
4581 /* Reset the target state; these things will be queried either by
4582 remote_query_supported or as they are needed. */
4583 reset_all_packet_configs_support ();
4584 rs->cached_wait_status = 0;
4585 rs->explicit_packet_size = 0;
4587 rs->extended = extended_p;
4588 rs->waiting_for_stop_reply = 0;
4589 rs->ctrlc_pending_p = 0;
4591 rs->general_thread = not_sent_ptid;
4592 rs->continue_thread = not_sent_ptid;
4593 rs->remote_traceframe_number = -1;
4595 /* Probe for ability to use "ThreadInfo" query, as required. */
4596 rs->use_threadinfo_query = 1;
4597 rs->use_threadextra_query = 1;
4599 readahead_cache_invalidate ();
4601 if (target_async_permitted)
4603 /* With this target we start out by owning the terminal. */
4604 remote_async_terminal_ours_p = 1;
4606 /* FIXME: cagney/1999-09-23: During the initial connection it is
4607 assumed that the target is already ready and able to respond to
4608 requests. Unfortunately remote_start_remote() eventually calls
4609 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4610 around this. Eventually a mechanism that allows
4611 wait_for_inferior() to expect/get timeouts will be
4613 wait_forever_enabled_p = 0;
4616 /* First delete any symbols previously loaded from shared libraries. */
4617 no_shared_libraries (NULL, 0);
4620 init_thread_list ();
4622 /* Start the remote connection. If error() or QUIT, discard this
4623 target (we'd otherwise be in an inconsistent state) and then
4624 propogate the error on up the exception chain. This ensures that
4625 the caller doesn't stumble along blindly assuming that the
4626 function succeeded. The CLI doesn't have this problem but other
4627 UI's, such as MI do.
4629 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4630 this function should return an error indication letting the
4631 caller restore the previous state. Unfortunately the command
4632 ``target remote'' is directly wired to this function making that
4633 impossible. On a positive note, the CLI side of this problem has
4634 been fixed - the function set_cmd_context() makes it possible for
4635 all the ``target ....'' commands to share a common callback
4636 function. See cli-dump.c. */
4641 remote_start_remote (from_tty, target, extended_p);
4643 CATCH (ex, RETURN_MASK_ALL)
4645 /* Pop the partially set up target - unless something else did
4646 already before throwing the exception. */
4647 if (rs->remote_desc != NULL)
4648 remote_unpush_target ();
4649 if (target_async_permitted)
4650 wait_forever_enabled_p = 1;
4651 throw_exception (ex);
4656 remote_btrace_reset ();
4658 if (target_async_permitted)
4659 wait_forever_enabled_p = 1;
4662 /* Detach the specified process. */
4665 remote_detach_pid (int pid)
4667 struct remote_state *rs = get_remote_state ();
4669 if (remote_multi_process_p (rs))
4670 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4672 strcpy (rs->buf, "D");
4675 getpkt (&rs->buf, &rs->buf_size, 0);
4677 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4679 else if (rs->buf[0] == '\0')
4680 error (_("Remote doesn't know how to detach"));
4682 error (_("Can't detach process."));
4685 /* This detaches a program to which we previously attached, using
4686 inferior_ptid to identify the process. After this is done, GDB
4687 can be used to debug some other program. We better not have left
4688 any breakpoints in the target program or it'll die when it hits
4692 remote_detach_1 (const char *args, int from_tty)
4694 int pid = ptid_get_pid (inferior_ptid);
4695 struct remote_state *rs = get_remote_state ();
4696 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4700 error (_("Argument given to \"detach\" when remotely debugging."));
4702 if (!target_has_execution)
4703 error (_("No process to detach from."));
4707 char *exec_file = get_exec_file (0);
4708 if (exec_file == NULL)
4710 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4711 target_pid_to_str (pid_to_ptid (pid)));
4712 gdb_flush (gdb_stdout);
4715 /* Tell the remote target to detach. */
4716 remote_detach_pid (pid);
4718 if (from_tty && !rs->extended)
4719 puts_filtered (_("Ending remote debugging.\n"));
4721 /* Check to see if we are detaching a fork parent. Note that if we
4722 are detaching a fork child, tp == NULL. */
4723 is_fork_parent = (tp != NULL
4724 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4726 /* If doing detach-on-fork, we don't mourn, because that will delete
4727 breakpoints that should be available for the followed inferior. */
4728 if (!is_fork_parent)
4729 target_mourn_inferior ();
4732 inferior_ptid = null_ptid;
4733 detach_inferior (pid);
4738 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4740 remote_detach_1 (args, from_tty);
4744 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4746 remote_detach_1 (args, from_tty);
4749 /* Target follow-fork function for remote targets. On entry, and
4750 at return, the current inferior is the fork parent.
4752 Note that although this is currently only used for extended-remote,
4753 it is named remote_follow_fork in anticipation of using it for the
4754 remote target as well. */
4757 remote_follow_fork (struct target_ops *ops, int follow_child,
4760 struct remote_state *rs = get_remote_state ();
4761 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
4763 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4764 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
4766 /* When following the parent and detaching the child, we detach
4767 the child here. For the case of following the child and
4768 detaching the parent, the detach is done in the target-
4769 independent follow fork code in infrun.c. We can't use
4770 target_detach when detaching an unfollowed child because
4771 the client side doesn't know anything about the child. */
4772 if (detach_fork && !follow_child)
4774 /* Detach the fork child. */
4778 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4779 child_pid = ptid_get_pid (child_ptid);
4781 remote_detach_pid (child_pid);
4782 detach_inferior (child_pid);
4788 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4791 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4794 error (_("Argument given to \"disconnect\" when remotely debugging."));
4796 /* Make sure we unpush even the extended remote targets; mourn
4797 won't do it. So call remote_mourn directly instead of
4798 target_mourn_inferior. */
4799 remote_mourn (target);
4802 puts_filtered ("Ending remote debugging.\n");
4805 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4806 be chatty about it. */
4809 extended_remote_attach (struct target_ops *target, const char *args,
4812 struct remote_state *rs = get_remote_state ();
4814 char *wait_status = NULL;
4816 pid = parse_pid_to_attach (args);
4818 /* Remote PID can be freely equal to getpid, do not check it here the same
4819 way as in other targets. */
4821 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4822 error (_("This target does not support attaching to a process"));
4826 char *exec_file = get_exec_file (0);
4829 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4830 target_pid_to_str (pid_to_ptid (pid)));
4832 printf_unfiltered (_("Attaching to %s\n"),
4833 target_pid_to_str (pid_to_ptid (pid)));
4835 gdb_flush (gdb_stdout);
4838 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4840 getpkt (&rs->buf, &rs->buf_size, 0);
4842 switch (packet_ok (rs->buf,
4843 &remote_protocol_packets[PACKET_vAttach]))
4848 /* Save the reply for later. */
4849 wait_status = alloca (strlen (rs->buf) + 1);
4850 strcpy (wait_status, rs->buf);
4852 else if (strcmp (rs->buf, "OK") != 0)
4853 error (_("Attaching to %s failed with: %s"),
4854 target_pid_to_str (pid_to_ptid (pid)),
4857 case PACKET_UNKNOWN:
4858 error (_("This target does not support attaching to a process"));
4860 error (_("Attaching to %s failed"),
4861 target_pid_to_str (pid_to_ptid (pid)));
4864 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
4866 inferior_ptid = pid_to_ptid (pid);
4870 struct thread_info *thread;
4872 /* Get list of threads. */
4873 remote_update_thread_list (target);
4875 thread = first_thread_of_process (pid);
4877 inferior_ptid = thread->ptid;
4879 inferior_ptid = pid_to_ptid (pid);
4881 /* Invalidate our notion of the remote current thread. */
4882 record_currthread (rs, minus_one_ptid);
4886 /* Now, if we have thread information, update inferior_ptid. */
4887 inferior_ptid = remote_current_thread (inferior_ptid);
4889 /* Add the main thread to the thread list. */
4890 add_thread_silent (inferior_ptid);
4893 /* Next, if the target can specify a description, read it. We do
4894 this before anything involving memory or registers. */
4895 target_find_description ();
4899 /* Use the previously fetched status. */
4900 gdb_assert (wait_status != NULL);
4902 if (target_can_async_p ())
4904 struct notif_event *reply
4905 = remote_notif_parse (¬if_client_stop, wait_status);
4907 push_stop_reply ((struct stop_reply *) reply);
4913 gdb_assert (wait_status != NULL);
4914 strcpy (rs->buf, wait_status);
4915 rs->cached_wait_status = 1;
4919 gdb_assert (wait_status == NULL);
4922 /* Implementation of the to_post_attach method. */
4925 extended_remote_post_attach (struct target_ops *ops, int pid)
4927 /* In certain cases GDB might not have had the chance to start
4928 symbol lookup up until now. This could happen if the debugged
4929 binary is not using shared libraries, the vsyscall page is not
4930 present (on Linux) and the binary itself hadn't changed since the
4931 debugging process was started. */
4932 if (symfile_objfile != NULL)
4933 remote_check_symbols();
4937 /* Check for the availability of vCont. This function should also check
4941 remote_vcont_probe (struct remote_state *rs)
4945 strcpy (rs->buf, "vCont?");
4947 getpkt (&rs->buf, &rs->buf_size, 0);
4950 /* Make sure that the features we assume are supported. */
4951 if (startswith (buf, "vCont"))
4954 int support_s, support_S, support_c, support_C;
4960 rs->supports_vCont.t = 0;
4961 rs->supports_vCont.r = 0;
4962 while (p && *p == ';')
4965 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4967 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4969 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4971 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4973 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4974 rs->supports_vCont.t = 1;
4975 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4976 rs->supports_vCont.r = 1;
4978 p = strchr (p, ';');
4981 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4982 BUF will make packet_ok disable the packet. */
4983 if (!support_s || !support_S || !support_c || !support_C)
4987 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4990 /* Helper function for building "vCont" resumptions. Write a
4991 resumption to P. ENDP points to one-passed-the-end of the buffer
4992 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4993 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4994 resumed thread should be single-stepped and/or signalled. If PTID
4995 equals minus_one_ptid, then all threads are resumed; if PTID
4996 represents a process, then all threads of the process are resumed;
4997 the thread to be stepped and/or signalled is given in the global
5001 append_resumption (char *p, char *endp,
5002 ptid_t ptid, int step, enum gdb_signal siggnal)
5004 struct remote_state *rs = get_remote_state ();
5006 if (step && siggnal != GDB_SIGNAL_0)
5007 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5009 /* GDB is willing to range step. */
5010 && use_range_stepping
5011 /* Target supports range stepping. */
5012 && rs->supports_vCont.r
5013 /* We don't currently support range stepping multiple
5014 threads with a wildcard (though the protocol allows it,
5015 so stubs shouldn't make an active effort to forbid
5017 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5019 struct thread_info *tp;
5021 if (ptid_equal (ptid, minus_one_ptid))
5023 /* If we don't know about the target thread's tid, then
5024 we're resuming magic_null_ptid (see caller). */
5025 tp = find_thread_ptid (magic_null_ptid);
5028 tp = find_thread_ptid (ptid);
5029 gdb_assert (tp != NULL);
5031 if (tp->control.may_range_step)
5033 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5035 p += xsnprintf (p, endp - p, ";r%s,%s",
5036 phex_nz (tp->control.step_range_start,
5038 phex_nz (tp->control.step_range_end,
5042 p += xsnprintf (p, endp - p, ";s");
5045 p += xsnprintf (p, endp - p, ";s");
5046 else if (siggnal != GDB_SIGNAL_0)
5047 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5049 p += xsnprintf (p, endp - p, ";c");
5051 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5055 /* All (-1) threads of process. */
5056 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5058 p += xsnprintf (p, endp - p, ":");
5059 p = write_ptid (p, endp, nptid);
5061 else if (!ptid_equal (ptid, minus_one_ptid))
5063 p += xsnprintf (p, endp - p, ":");
5064 p = write_ptid (p, endp, ptid);
5070 /* Append a vCont continue-with-signal action for threads that have a
5071 non-zero stop signal. */
5074 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5076 struct thread_info *thread;
5078 ALL_NON_EXITED_THREADS (thread)
5079 if (ptid_match (thread->ptid, ptid)
5080 && !ptid_equal (inferior_ptid, thread->ptid)
5081 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5083 p = append_resumption (p, endp, thread->ptid,
5084 0, thread->suspend.stop_signal);
5085 thread->suspend.stop_signal = GDB_SIGNAL_0;
5091 /* Resume the remote inferior by using a "vCont" packet. The thread
5092 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5093 resumed thread should be single-stepped and/or signalled. If PTID
5094 equals minus_one_ptid, then all threads are resumed; the thread to
5095 be stepped and/or signalled is given in the global INFERIOR_PTID.
5096 This function returns non-zero iff it resumes the inferior.
5098 This function issues a strict subset of all possible vCont commands at the
5102 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5104 struct remote_state *rs = get_remote_state ();
5108 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5109 remote_vcont_probe (rs);
5111 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5115 endp = rs->buf + get_remote_packet_size ();
5117 /* If we could generate a wider range of packets, we'd have to worry
5118 about overflowing BUF. Should there be a generic
5119 "multi-part-packet" packet? */
5121 p += xsnprintf (p, endp - p, "vCont");
5123 if (ptid_equal (ptid, magic_null_ptid))
5125 /* MAGIC_NULL_PTID means that we don't have any active threads,
5126 so we don't have any TID numbers the inferior will
5127 understand. Make sure to only send forms that do not specify
5129 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5131 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5133 /* Resume all threads (of all processes, or of a single
5134 process), with preference for INFERIOR_PTID. This assumes
5135 inferior_ptid belongs to the set of all threads we are about
5137 if (step || siggnal != GDB_SIGNAL_0)
5139 /* Step inferior_ptid, with or without signal. */
5140 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5143 /* Also pass down any pending signaled resumption for other
5144 threads not the current. */
5145 p = append_pending_thread_resumptions (p, endp, ptid);
5147 /* And continue others without a signal. */
5148 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5152 /* Scheduler locking; resume only PTID. */
5153 append_resumption (p, endp, ptid, step, siggnal);
5156 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5161 /* In non-stop, the stub replies to vCont with "OK". The stop
5162 reply will be reported asynchronously by means of a `%Stop'
5164 getpkt (&rs->buf, &rs->buf_size, 0);
5165 if (strcmp (rs->buf, "OK") != 0)
5166 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5172 /* Tell the remote machine to resume. */
5175 remote_resume (struct target_ops *ops,
5176 ptid_t ptid, int step, enum gdb_signal siggnal)
5178 struct remote_state *rs = get_remote_state ();
5181 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5182 (explained in remote-notif.c:handle_notification) so
5183 remote_notif_process is not called. We need find a place where
5184 it is safe to start a 'vNotif' sequence. It is good to do it
5185 before resuming inferior, because inferior was stopped and no RSP
5186 traffic at that moment. */
5188 remote_notif_process (rs->notif_state, ¬if_client_stop);
5190 rs->last_sent_signal = siggnal;
5191 rs->last_sent_step = step;
5193 /* The vCont packet doesn't need to specify threads via Hc. */
5194 /* No reverse support (yet) for vCont. */
5195 if (execution_direction != EXEC_REVERSE)
5196 if (remote_vcont_resume (ptid, step, siggnal))
5199 /* All other supported resume packets do use Hc, so set the continue
5201 if (ptid_equal (ptid, minus_one_ptid))
5202 set_continue_thread (any_thread_ptid);
5204 set_continue_thread (ptid);
5207 if (execution_direction == EXEC_REVERSE)
5209 /* We don't pass signals to the target in reverse exec mode. */
5210 if (info_verbose && siggnal != GDB_SIGNAL_0)
5211 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5214 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5215 error (_("Remote reverse-step not supported."));
5216 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5217 error (_("Remote reverse-continue not supported."));
5219 strcpy (buf, step ? "bs" : "bc");
5221 else if (siggnal != GDB_SIGNAL_0)
5223 buf[0] = step ? 'S' : 'C';
5224 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5225 buf[2] = tohex (((int) siggnal) & 0xf);
5229 strcpy (buf, step ? "s" : "c");
5234 /* We are about to start executing the inferior, let's register it
5235 with the event loop. NOTE: this is the one place where all the
5236 execution commands end up. We could alternatively do this in each
5237 of the execution commands in infcmd.c. */
5238 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5239 into infcmd.c in order to allow inferior function calls to work
5240 NOT asynchronously. */
5241 if (target_can_async_p ())
5244 /* We've just told the target to resume. The remote server will
5245 wait for the inferior to stop, and then send a stop reply. In
5246 the mean time, we can't start another command/query ourselves
5247 because the stub wouldn't be ready to process it. This applies
5248 only to the base all-stop protocol, however. In non-stop (which
5249 only supports vCont), the stub replies with an "OK", and is
5250 immediate able to process further serial input. */
5252 rs->waiting_for_stop_reply = 1;
5256 /* Set up the signal handler for SIGINT, while the target is
5257 executing, ovewriting the 'regular' SIGINT signal handler. */
5259 async_initialize_sigint_signal_handler (void)
5261 signal (SIGINT, async_handle_remote_sigint);
5264 /* Signal handler for SIGINT, while the target is executing. */
5266 async_handle_remote_sigint (int sig)
5268 signal (sig, async_handle_remote_sigint_twice);
5269 /* Note we need to go through gdb_call_async_signal_handler in order
5270 to wake up the event loop on Windows. */
5271 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5274 /* Signal handler for SIGINT, installed after SIGINT has already been
5275 sent once. It will take effect the second time that the user sends
5278 async_handle_remote_sigint_twice (int sig)
5280 signal (sig, async_handle_remote_sigint);
5281 /* See note in async_handle_remote_sigint. */
5282 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5285 /* Implementation of to_check_pending_interrupt. */
5288 remote_check_pending_interrupt (struct target_ops *self)
5290 struct async_signal_handler *token = async_sigint_remote_twice_token;
5292 if (async_signal_handler_is_marked (token))
5294 clear_async_signal_handler (token);
5295 call_async_signal_handler (token);
5299 /* Perform the real interruption of the target execution, in response
5302 async_remote_interrupt (gdb_client_data arg)
5305 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5307 target_stop (inferior_ptid);
5310 /* Perform interrupt, if the first attempt did not succeed. Just give
5311 up on the target alltogether. */
5313 async_remote_interrupt_twice (gdb_client_data arg)
5316 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5321 /* Reinstall the usual SIGINT handlers, after the target has
5324 async_cleanup_sigint_signal_handler (void *dummy)
5326 signal (SIGINT, handle_sigint);
5329 /* Send ^C to target to halt it. Target will respond, and send us a
5331 static void (*ofunc) (int);
5333 /* The command line interface's interrupt routine. This function is installed
5334 as a signal handler for SIGINT. The first time a user requests an
5335 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5336 response from the target (it didn't stop when the user requested it),
5337 we ask the user if he'd like to detach from the target. */
5340 sync_remote_interrupt (int signo)
5342 /* If this doesn't work, try more severe steps. */
5343 signal (signo, sync_remote_interrupt_twice);
5345 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5348 /* The user typed ^C twice. */
5351 sync_remote_interrupt_twice (int signo)
5353 signal (signo, ofunc);
5354 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5355 signal (signo, sync_remote_interrupt);
5358 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5359 thread, all threads of a remote process, or all threads of all
5363 remote_stop_ns (ptid_t ptid)
5365 struct remote_state *rs = get_remote_state ();
5367 char *endp = rs->buf + get_remote_packet_size ();
5369 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5370 remote_vcont_probe (rs);
5372 if (!rs->supports_vCont.t)
5373 error (_("Remote server does not support stopping threads"));
5375 if (ptid_equal (ptid, minus_one_ptid)
5376 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5377 p += xsnprintf (p, endp - p, "vCont;t");
5382 p += xsnprintf (p, endp - p, "vCont;t:");
5384 if (ptid_is_pid (ptid))
5385 /* All (-1) threads of process. */
5386 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5389 /* Small optimization: if we already have a stop reply for
5390 this thread, no use in telling the stub we want this
5392 if (peek_stop_reply (ptid))
5398 write_ptid (p, endp, nptid);
5401 /* In non-stop, we get an immediate OK reply. The stop reply will
5402 come in asynchronously by notification. */
5404 getpkt (&rs->buf, &rs->buf_size, 0);
5405 if (strcmp (rs->buf, "OK") != 0)
5406 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5409 /* All-stop version of target_interrupt. Sends a break or a ^C to
5410 interrupt the remote target. It is undefined which thread of which
5411 process reports the interrupt. */
5414 remote_interrupt_as (ptid_t ptid)
5416 struct remote_state *rs = get_remote_state ();
5418 rs->ctrlc_pending_p = 1;
5420 /* If the inferior is stopped already, but the core didn't know
5421 about it yet, just ignore the request. The cached wait status
5422 will be collected in remote_wait. */
5423 if (rs->cached_wait_status)
5426 /* Send interrupt_sequence to remote target. */
5427 send_interrupt_sequence ();
5430 /* Implement the to_stop function for the remote targets. */
5433 remote_stop (struct target_ops *self, ptid_t ptid)
5436 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5439 remote_stop_ns (ptid);
5442 /* We don't currently have a way to transparently pause the
5443 remote target in all-stop mode. Interrupt it instead. */
5444 remote_interrupt_as (ptid);
5448 /* Implement the to_interrupt function for the remote targets. */
5451 remote_interrupt (struct target_ops *self, ptid_t ptid)
5454 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5458 /* We don't currently have a way to ^C the remote target in
5459 non-stop mode. Stop it (with no signal) instead. */
5460 remote_stop_ns (ptid);
5463 remote_interrupt_as (ptid);
5466 /* Ask the user what to do when an interrupt is received. */
5469 interrupt_query (void)
5471 struct remote_state *rs = get_remote_state ();
5472 struct cleanup *old_chain;
5474 old_chain = make_cleanup_restore_target_terminal ();
5475 target_terminal_ours ();
5477 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5479 if (query (_("The target is not responding to interrupt requests.\n"
5480 "Stop debugging it? ")))
5482 remote_unpush_target ();
5483 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5488 if (query (_("Interrupted while waiting for the program.\n"
5489 "Give up waiting? ")))
5493 do_cleanups (old_chain);
5496 /* Enable/disable target terminal ownership. Most targets can use
5497 terminal groups to control terminal ownership. Remote targets are
5498 different in that explicit transfer of ownership to/from GDB/target
5502 remote_terminal_inferior (struct target_ops *self)
5504 if (!target_async_permitted)
5505 /* Nothing to do. */
5508 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5509 idempotent. The event-loop GDB talking to an asynchronous target
5510 with a synchronous command calls this function from both
5511 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5512 transfer the terminal to the target when it shouldn't this guard
5514 if (!remote_async_terminal_ours_p)
5516 delete_file_handler (input_fd);
5517 remote_async_terminal_ours_p = 0;
5518 async_initialize_sigint_signal_handler ();
5519 /* NOTE: At this point we could also register our selves as the
5520 recipient of all input. Any characters typed could then be
5521 passed on down to the target. */
5525 remote_terminal_ours (struct target_ops *self)
5527 if (!target_async_permitted)
5528 /* Nothing to do. */
5531 /* See FIXME in remote_terminal_inferior. */
5532 if (remote_async_terminal_ours_p)
5534 async_cleanup_sigint_signal_handler (NULL);
5535 add_file_handler (input_fd, stdin_event_handler, 0);
5536 remote_async_terminal_ours_p = 1;
5540 remote_console_output (char *msg)
5544 for (p = msg; p[0] && p[1]; p += 2)
5547 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5551 fputs_unfiltered (tb, gdb_stdtarg);
5553 gdb_flush (gdb_stdtarg);
5556 typedef struct cached_reg
5559 gdb_byte data[MAX_REGISTER_SIZE];
5562 DEF_VEC_O(cached_reg_t);
5564 typedef struct stop_reply
5566 struct notif_event base;
5568 /* The identifier of the thread about this event */
5571 /* The remote state this event is associated with. When the remote
5572 connection, represented by a remote_state object, is closed,
5573 all the associated stop_reply events should be released. */
5574 struct remote_state *rs;
5576 struct target_waitstatus ws;
5578 /* Expedited registers. This makes remote debugging a bit more
5579 efficient for those targets that provide critical registers as
5580 part of their normal status mechanism (as another roundtrip to
5581 fetch them is avoided). */
5582 VEC(cached_reg_t) *regcache;
5584 enum target_stop_reason stop_reason;
5586 CORE_ADDR watch_data_address;
5591 DECLARE_QUEUE_P (stop_reply_p);
5592 DEFINE_QUEUE_P (stop_reply_p);
5593 /* The list of already fetched and acknowledged stop events. This
5594 queue is used for notification Stop, and other notifications
5595 don't need queue for their events, because the notification events
5596 of Stop can't be consumed immediately, so that events should be
5597 queued first, and be consumed by remote_wait_{ns,as} one per
5598 time. Other notifications can consume their events immediately,
5599 so queue is not needed for them. */
5600 static QUEUE (stop_reply_p) *stop_reply_queue;
5603 stop_reply_xfree (struct stop_reply *r)
5605 notif_event_xfree ((struct notif_event *) r);
5608 /* Return the length of the stop reply queue. */
5611 stop_reply_queue_length (void)
5613 return QUEUE_length (stop_reply_p, stop_reply_queue);
5617 remote_notif_stop_parse (struct notif_client *self, char *buf,
5618 struct notif_event *event)
5620 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5624 remote_notif_stop_ack (struct notif_client *self, char *buf,
5625 struct notif_event *event)
5627 struct stop_reply *stop_reply = (struct stop_reply *) event;
5630 putpkt ((char *) self->ack_command);
5632 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5633 /* We got an unknown stop reply. */
5634 error (_("Unknown stop reply"));
5636 push_stop_reply (stop_reply);
5640 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5642 /* We can't get pending events in remote_notif_process for
5643 notification stop, and we have to do this in remote_wait_ns
5644 instead. If we fetch all queued events from stub, remote stub
5645 may exit and we have no chance to process them back in
5647 mark_async_event_handler (remote_async_inferior_event_token);
5652 stop_reply_dtr (struct notif_event *event)
5654 struct stop_reply *r = (struct stop_reply *) event;
5656 VEC_free (cached_reg_t, r->regcache);
5659 static struct notif_event *
5660 remote_notif_stop_alloc_reply (void)
5662 /* We cast to a pointer to the "base class". */
5663 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5665 r->dtr = stop_reply_dtr;
5670 /* A client of notification Stop. */
5672 struct notif_client notif_client_stop =
5676 remote_notif_stop_parse,
5677 remote_notif_stop_ack,
5678 remote_notif_stop_can_get_pending_events,
5679 remote_notif_stop_alloc_reply,
5683 /* A parameter to pass data in and out. */
5685 struct queue_iter_param
5688 struct stop_reply *output;
5691 /* Determine if THREAD is a pending fork parent thread. ARG contains
5692 the pid of the process that owns the threads we want to check, or
5693 -1 if we want to check all threads. */
5696 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5699 if (ws->kind == TARGET_WAITKIND_FORKED
5700 || ws->kind == TARGET_WAITKIND_VFORKED)
5702 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5709 /* Check whether EVENT is a fork event, and if it is, remove the
5710 fork child from the context list passed in DATA. */
5713 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5714 QUEUE_ITER (stop_reply_p) *iter,
5718 struct queue_iter_param *param = data;
5719 struct threads_listing_context *context = param->input;
5721 if (event->ws.kind == TARGET_WAITKIND_FORKED
5722 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5724 threads_listing_context_remove (&event->ws, context);
5730 /* If CONTEXT contains any fork child threads that have not been
5731 reported yet, remove them from the CONTEXT list. If such a
5732 thread exists it is because we are stopped at a fork catchpoint
5733 and have not yet called follow_fork, which will set up the
5734 host-side data structures for the new process. */
5737 remove_new_fork_children (struct threads_listing_context *context)
5739 struct thread_info * thread;
5741 struct notif_client *notif = ¬if_client_stop;
5742 struct queue_iter_param param;
5744 /* For any threads stopped at a fork event, remove the corresponding
5745 fork child threads from the CONTEXT list. */
5746 ALL_NON_EXITED_THREADS (thread)
5748 struct target_waitstatus *ws = &thread->pending_follow;
5750 if (is_pending_fork_parent (ws, pid, thread->ptid))
5752 threads_listing_context_remove (ws, context);
5756 /* Check for any pending fork events (not reported or processed yet)
5757 in process PID and remove those fork child threads from the
5758 CONTEXT list as well. */
5759 remote_notif_get_pending_events (notif);
5760 param.input = context;
5761 param.output = NULL;
5762 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5763 remove_child_of_pending_fork, ¶m);
5766 /* Remove stop replies in the queue if its pid is equal to the given
5770 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5771 QUEUE_ITER (stop_reply_p) *iter,
5775 struct queue_iter_param *param = data;
5776 struct inferior *inf = param->input;
5778 if (ptid_get_pid (event->ptid) == inf->pid)
5780 stop_reply_xfree (event);
5781 QUEUE_remove_elem (stop_reply_p, q, iter);
5787 /* Discard all pending stop replies of inferior INF. */
5790 discard_pending_stop_replies (struct inferior *inf)
5793 struct queue_iter_param param;
5794 struct stop_reply *reply;
5795 struct remote_state *rs = get_remote_state ();
5796 struct remote_notif_state *rns = rs->notif_state;
5798 /* This function can be notified when an inferior exists. When the
5799 target is not remote, the notification state is NULL. */
5800 if (rs->remote_desc == NULL)
5803 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5805 /* Discard the in-flight notification. */
5806 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5808 stop_reply_xfree (reply);
5809 rns->pending_event[notif_client_stop.id] = NULL;
5813 param.output = NULL;
5814 /* Discard the stop replies we have already pulled with
5816 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5817 remove_stop_reply_for_inferior, ¶m);
5820 /* If its remote state is equal to the given remote state,
5821 remove EVENT from the stop reply queue. */
5824 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5825 QUEUE_ITER (stop_reply_p) *iter,
5829 struct queue_iter_param *param = data;
5830 struct remote_state *rs = param->input;
5832 if (event->rs == rs)
5834 stop_reply_xfree (event);
5835 QUEUE_remove_elem (stop_reply_p, q, iter);
5841 /* Discard the stop replies for RS in stop_reply_queue. */
5844 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5846 struct queue_iter_param param;
5849 param.output = NULL;
5850 /* Discard the stop replies we have already pulled with
5852 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5853 remove_stop_reply_of_remote_state, ¶m);
5856 /* A parameter to pass data in and out. */
5859 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5860 QUEUE_ITER (stop_reply_p) *iter,
5864 struct queue_iter_param *param = data;
5865 ptid_t *ptid = param->input;
5867 if (ptid_match (event->ptid, *ptid))
5869 param->output = event;
5870 QUEUE_remove_elem (stop_reply_p, q, iter);
5877 /* Remove the first reply in 'stop_reply_queue' which matches
5880 static struct stop_reply *
5881 remote_notif_remove_queued_reply (ptid_t ptid)
5883 struct queue_iter_param param;
5885 param.input = &ptid;
5886 param.output = NULL;
5888 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5889 remote_notif_remove_once_on_match, ¶m);
5891 fprintf_unfiltered (gdb_stdlog,
5892 "notif: discard queued event: 'Stop' in %s\n",
5893 target_pid_to_str (ptid));
5895 return param.output;
5898 /* Look for a queued stop reply belonging to PTID. If one is found,
5899 remove it from the queue, and return it. Returns NULL if none is
5900 found. If there are still queued events left to process, tell the
5901 event loop to get back to target_wait soon. */
5903 static struct stop_reply *
5904 queued_stop_reply (ptid_t ptid)
5906 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5908 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5909 /* There's still at least an event left. */
5910 mark_async_event_handler (remote_async_inferior_event_token);
5915 /* Push a fully parsed stop reply in the stop reply queue. Since we
5916 know that we now have at least one queued event left to pass to the
5917 core side, tell the event loop to get back to target_wait soon. */
5920 push_stop_reply (struct stop_reply *new_event)
5922 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5925 fprintf_unfiltered (gdb_stdlog,
5926 "notif: push 'Stop' %s to queue %d\n",
5927 target_pid_to_str (new_event->ptid),
5928 QUEUE_length (stop_reply_p,
5931 mark_async_event_handler (remote_async_inferior_event_token);
5935 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5936 QUEUE_ITER (stop_reply_p) *iter,
5937 struct stop_reply *event,
5940 ptid_t *ptid = data;
5942 return !(ptid_equal (*ptid, event->ptid)
5943 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5946 /* Returns true if we have a stop reply for PTID. */
5949 peek_stop_reply (ptid_t ptid)
5951 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5952 stop_reply_match_ptid_and_ws, &ptid);
5955 /* Skip PACKET until the next semi-colon (or end of string). */
5958 skip_to_semicolon (char *p)
5960 while (*p != '\0' && *p != ';')
5965 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
5966 starting with P and ending with PEND matches PREFIX. */
5969 strprefix (const char *p, const char *pend, const char *prefix)
5971 for ( ; p < pend; p++, prefix++)
5974 return *prefix == '\0';
5977 /* Parse the stop reply in BUF. Either the function succeeds, and the
5978 result is stored in EVENT, or throws an error. */
5981 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5983 struct remote_arch_state *rsa = get_remote_arch_state ();
5987 event->ptid = null_ptid;
5988 event->rs = get_remote_state ();
5989 event->ws.kind = TARGET_WAITKIND_IGNORE;
5990 event->ws.value.integer = 0;
5991 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5992 event->regcache = NULL;
5997 case 'T': /* Status with PC, SP, FP, ... */
5998 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5999 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6001 n... = register number
6002 r... = register contents
6005 p = &buf[3]; /* after Txx */
6011 p1 = strchr (p, ':');
6013 error (_("Malformed packet(a) (missing colon): %s\n\
6017 error (_("Malformed packet(a) (missing register number): %s\n\
6021 /* Some "registers" are actually extended stop information.
6022 Note if you're adding a new entry here: GDB 7.9 and
6023 earlier assume that all register "numbers" that start
6024 with an hex digit are real register numbers. Make sure
6025 the server only sends such a packet if it knows the
6026 client understands it. */
6028 if (strprefix (p, p1, "thread"))
6029 event->ptid = read_ptid (++p1, &p);
6030 else if (strprefix (p, p1, "watch")
6031 || strprefix (p, p1, "rwatch")
6032 || strprefix (p, p1, "awatch"))
6034 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6035 p = unpack_varlen_hex (++p1, &addr);
6036 event->watch_data_address = (CORE_ADDR) addr;
6038 else if (strprefix (p, p1, "swbreak"))
6040 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6042 /* Make sure the stub doesn't forget to indicate support
6044 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6045 error (_("Unexpected swbreak stop reason"));
6047 /* The value part is documented as "must be empty",
6048 though we ignore it, in case we ever decide to make
6049 use of it in a backward compatible way. */
6050 p = skip_to_semicolon (p1 + 1);
6052 else if (strprefix (p, p1, "hwbreak"))
6054 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6056 /* Make sure the stub doesn't forget to indicate support
6058 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6059 error (_("Unexpected hwbreak stop reason"));
6062 p = skip_to_semicolon (p1 + 1);
6064 else if (strprefix (p, p1, "library"))
6066 event->ws.kind = TARGET_WAITKIND_LOADED;
6067 p = skip_to_semicolon (p1 + 1);
6069 else if (strprefix (p, p1, "replaylog"))
6071 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6072 /* p1 will indicate "begin" or "end", but it makes
6073 no difference for now, so ignore it. */
6074 p = skip_to_semicolon (p1 + 1);
6076 else if (strprefix (p, p1, "core"))
6080 p = unpack_varlen_hex (++p1, &c);
6083 else if (strprefix (p, p1, "fork"))
6085 event->ws.value.related_pid = read_ptid (++p1, &p);
6086 event->ws.kind = TARGET_WAITKIND_FORKED;
6088 else if (strprefix (p, p1, "vfork"))
6090 event->ws.value.related_pid = read_ptid (++p1, &p);
6091 event->ws.kind = TARGET_WAITKIND_VFORKED;
6093 else if (strprefix (p, p1, "vforkdone"))
6095 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6096 p = skip_to_semicolon (p1 + 1);
6103 /* Maybe a real ``P'' register number. */
6104 p_temp = unpack_varlen_hex (p, &pnum);
6105 /* If the first invalid character is the colon, we got a
6106 register number. Otherwise, it's an unknown stop
6110 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6111 cached_reg_t cached_reg;
6114 error (_("Remote sent bad register number %s: %s\n\
6116 hex_string (pnum), p, buf);
6118 cached_reg.num = reg->regnum;
6121 fieldsize = hex2bin (p, cached_reg.data,
6122 register_size (target_gdbarch (),
6125 if (fieldsize < register_size (target_gdbarch (),
6127 warning (_("Remote reply is too short: %s"), buf);
6129 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6133 /* Not a number. Silently skip unknown optional
6135 p = skip_to_semicolon (p1 + 1);
6140 error (_("Remote register badly formatted: %s\nhere: %s"),
6145 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6149 case 'S': /* Old style status, just signal only. */
6153 event->ws.kind = TARGET_WAITKIND_STOPPED;
6154 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6155 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6156 event->ws.value.sig = (enum gdb_signal) sig;
6158 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6161 case 'W': /* Target exited. */
6168 /* GDB used to accept only 2 hex chars here. Stubs should
6169 only send more if they detect GDB supports multi-process
6171 p = unpack_varlen_hex (&buf[1], &value);
6175 /* The remote process exited. */
6176 event->ws.kind = TARGET_WAITKIND_EXITED;
6177 event->ws.value.integer = value;
6181 /* The remote process exited with a signal. */
6182 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6183 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6184 event->ws.value.sig = (enum gdb_signal) value;
6186 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6189 /* If no process is specified, assume inferior_ptid. */
6190 pid = ptid_get_pid (inferior_ptid);
6199 else if (startswith (p, "process:"))
6203 p += sizeof ("process:") - 1;
6204 unpack_varlen_hex (p, &upid);
6208 error (_("unknown stop reply packet: %s"), buf);
6211 error (_("unknown stop reply packet: %s"), buf);
6212 event->ptid = pid_to_ptid (pid);
6217 if (non_stop && ptid_equal (event->ptid, null_ptid))
6218 error (_("No process or thread specified in stop reply: %s"), buf);
6221 /* When the stub wants to tell GDB about a new notification reply, it
6222 sends a notification (%Stop, for example). Those can come it at
6223 any time, hence, we have to make sure that any pending
6224 putpkt/getpkt sequence we're making is finished, before querying
6225 the stub for more events with the corresponding ack command
6226 (vStopped, for example). E.g., if we started a vStopped sequence
6227 immediately upon receiving the notification, something like this
6235 1.6) <-- (registers reply to step #1.3)
6237 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6240 To solve this, whenever we parse a %Stop notification successfully,
6241 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6242 doing whatever we were doing:
6248 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6249 2.5) <-- (registers reply to step #2.3)
6251 Eventualy after step #2.5, we return to the event loop, which
6252 notices there's an event on the
6253 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6254 associated callback --- the function below. At this point, we're
6255 always safe to start a vStopped sequence. :
6258 2.7) <-- T05 thread:2
6264 remote_notif_get_pending_events (struct notif_client *nc)
6266 struct remote_state *rs = get_remote_state ();
6268 if (rs->notif_state->pending_event[nc->id] != NULL)
6271 fprintf_unfiltered (gdb_stdlog,
6272 "notif: process: '%s' ack pending event\n",
6276 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6277 rs->notif_state->pending_event[nc->id] = NULL;
6281 getpkt (&rs->buf, &rs->buf_size, 0);
6282 if (strcmp (rs->buf, "OK") == 0)
6285 remote_notif_ack (nc, rs->buf);
6291 fprintf_unfiltered (gdb_stdlog,
6292 "notif: process: '%s' no pending reply\n",
6297 /* Called when it is decided that STOP_REPLY holds the info of the
6298 event that is to be returned to the core. This function always
6299 destroys STOP_REPLY. */
6302 process_stop_reply (struct stop_reply *stop_reply,
6303 struct target_waitstatus *status)
6307 *status = stop_reply->ws;
6308 ptid = stop_reply->ptid;
6310 /* If no thread/process was reported by the stub, assume the current
6312 if (ptid_equal (ptid, null_ptid))
6313 ptid = inferior_ptid;
6315 if (status->kind != TARGET_WAITKIND_EXITED
6316 && status->kind != TARGET_WAITKIND_SIGNALLED)
6318 struct remote_state *rs = get_remote_state ();
6320 /* Expedited registers. */
6321 if (stop_reply->regcache)
6323 struct regcache *regcache
6324 = get_thread_arch_regcache (ptid, target_gdbarch ());
6329 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6331 regcache_raw_supply (regcache, reg->num, reg->data);
6332 VEC_free (cached_reg_t, stop_reply->regcache);
6335 rs->stop_reason = stop_reply->stop_reason;
6336 rs->remote_watch_data_address = stop_reply->watch_data_address;
6338 remote_notice_new_inferior (ptid, 0);
6339 demand_private_info (ptid)->core = stop_reply->core;
6342 stop_reply_xfree (stop_reply);
6346 /* The non-stop mode version of target_wait. */
6349 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6351 struct remote_state *rs = get_remote_state ();
6352 struct stop_reply *stop_reply;
6356 /* If in non-stop mode, get out of getpkt even if a
6357 notification is received. */
6359 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6360 0 /* forever */, &is_notif);
6363 if (ret != -1 && !is_notif)
6366 case 'E': /* Error of some sort. */
6367 /* We're out of sync with the target now. Did it continue
6368 or not? We can't tell which thread it was in non-stop,
6369 so just ignore this. */
6370 warning (_("Remote failure reply: %s"), rs->buf);
6372 case 'O': /* Console output. */
6373 remote_console_output (rs->buf + 1);
6376 warning (_("Invalid remote reply: %s"), rs->buf);
6380 /* Acknowledge a pending stop reply that may have arrived in the
6382 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6383 remote_notif_get_pending_events (¬if_client_stop);
6385 /* If indeed we noticed a stop reply, we're done. */
6386 stop_reply = queued_stop_reply (ptid);
6387 if (stop_reply != NULL)
6388 return process_stop_reply (stop_reply, status);
6390 /* Still no event. If we're just polling for an event, then
6391 return to the event loop. */
6392 if (options & TARGET_WNOHANG)
6394 status->kind = TARGET_WAITKIND_IGNORE;
6395 return minus_one_ptid;
6398 /* Otherwise do a blocking wait. */
6399 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6400 1 /* forever */, &is_notif);
6404 /* Wait until the remote machine stops, then return, storing status in
6405 STATUS just as `wait' would. */
6408 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6410 struct remote_state *rs = get_remote_state ();
6411 ptid_t event_ptid = null_ptid;
6413 struct stop_reply *stop_reply;
6417 status->kind = TARGET_WAITKIND_IGNORE;
6418 status->value.integer = 0;
6420 stop_reply = queued_stop_reply (ptid);
6421 if (stop_reply != NULL)
6422 return process_stop_reply (stop_reply, status);
6424 if (rs->cached_wait_status)
6425 /* Use the cached wait status, but only once. */
6426 rs->cached_wait_status = 0;
6431 int forever = ((options & TARGET_WNOHANG) == 0
6432 && wait_forever_enabled_p);
6434 if (!rs->waiting_for_stop_reply)
6436 status->kind = TARGET_WAITKIND_NO_RESUMED;
6437 return minus_one_ptid;
6440 if (!target_is_async_p ())
6442 ofunc = signal (SIGINT, sync_remote_interrupt);
6443 /* If the user hit C-c before this packet, or between packets,
6444 pretend that it was hit right here. */
6445 if (check_quit_flag ())
6448 sync_remote_interrupt (SIGINT);
6452 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6453 _never_ wait for ever -> test on target_is_async_p().
6454 However, before we do that we need to ensure that the caller
6455 knows how to take the target into/out of async mode. */
6456 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6457 forever, &is_notif);
6459 if (!target_is_async_p ())
6460 signal (SIGINT, ofunc);
6462 /* GDB gets a notification. Return to core as this event is
6464 if (ret != -1 && is_notif)
6465 return minus_one_ptid;
6467 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6468 return minus_one_ptid;
6473 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6475 /* We got something. */
6476 rs->waiting_for_stop_reply = 0;
6478 /* Assume that the target has acknowledged Ctrl-C unless we receive
6479 an 'F' or 'O' packet. */
6480 if (buf[0] != 'F' && buf[0] != 'O')
6481 rs->ctrlc_pending_p = 0;
6485 case 'E': /* Error of some sort. */
6486 /* We're out of sync with the target now. Did it continue or
6487 not? Not is more likely, so report a stop. */
6488 warning (_("Remote failure reply: %s"), buf);
6489 status->kind = TARGET_WAITKIND_STOPPED;
6490 status->value.sig = GDB_SIGNAL_0;
6492 case 'F': /* File-I/O request. */
6493 remote_fileio_request (buf, rs->ctrlc_pending_p);
6494 rs->ctrlc_pending_p = 0;
6496 case 'T': case 'S': case 'X': case 'W':
6498 struct stop_reply *stop_reply
6499 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6502 event_ptid = process_stop_reply (stop_reply, status);
6505 case 'O': /* Console output. */
6506 remote_console_output (buf + 1);
6508 /* The target didn't really stop; keep waiting. */
6509 rs->waiting_for_stop_reply = 1;
6513 if (rs->last_sent_signal != GDB_SIGNAL_0)
6515 /* Zero length reply means that we tried 'S' or 'C' and the
6516 remote system doesn't support it. */
6517 target_terminal_ours_for_output ();
6519 ("Can't send signals to this remote system. %s not sent.\n",
6520 gdb_signal_to_name (rs->last_sent_signal));
6521 rs->last_sent_signal = GDB_SIGNAL_0;
6522 target_terminal_inferior ();
6524 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6525 putpkt ((char *) buf);
6527 /* We just told the target to resume, so a stop reply is in
6529 rs->waiting_for_stop_reply = 1;
6532 /* else fallthrough */
6534 warning (_("Invalid remote reply: %s"), buf);
6536 rs->waiting_for_stop_reply = 1;
6540 if (status->kind == TARGET_WAITKIND_IGNORE)
6542 /* Nothing interesting happened. If we're doing a non-blocking
6543 poll, we're done. Otherwise, go back to waiting. */
6544 if (options & TARGET_WNOHANG)
6545 return minus_one_ptid;
6549 else if (status->kind != TARGET_WAITKIND_EXITED
6550 && status->kind != TARGET_WAITKIND_SIGNALLED)
6552 if (!ptid_equal (event_ptid, null_ptid))
6553 record_currthread (rs, event_ptid);
6555 event_ptid = inferior_ptid;
6558 /* A process exit. Invalidate our notion of current thread. */
6559 record_currthread (rs, minus_one_ptid);
6564 /* Wait until the remote machine stops, then return, storing status in
6565 STATUS just as `wait' would. */
6568 remote_wait (struct target_ops *ops,
6569 ptid_t ptid, struct target_waitstatus *status, int options)
6574 event_ptid = remote_wait_ns (ptid, status, options);
6576 event_ptid = remote_wait_as (ptid, status, options);
6578 if (target_is_async_p ())
6580 /* If there are are events left in the queue tell the event loop
6582 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6583 mark_async_event_handler (remote_async_inferior_event_token);
6589 /* Fetch a single register using a 'p' packet. */
6592 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6594 struct remote_state *rs = get_remote_state ();
6596 char regp[MAX_REGISTER_SIZE];
6599 if (packet_support (PACKET_p) == PACKET_DISABLE)
6602 if (reg->pnum == -1)
6607 p += hexnumstr (p, reg->pnum);
6610 getpkt (&rs->buf, &rs->buf_size, 0);
6614 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6618 case PACKET_UNKNOWN:
6621 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6622 gdbarch_register_name (get_regcache_arch (regcache),
6627 /* If this register is unfetchable, tell the regcache. */
6630 regcache_raw_supply (regcache, reg->regnum, NULL);
6634 /* Otherwise, parse and supply the value. */
6640 error (_("fetch_register_using_p: early buf termination"));
6642 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6645 regcache_raw_supply (regcache, reg->regnum, regp);
6649 /* Fetch the registers included in the target's 'g' packet. */
6652 send_g_packet (void)
6654 struct remote_state *rs = get_remote_state ();
6657 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6658 remote_send (&rs->buf, &rs->buf_size);
6660 /* We can get out of synch in various cases. If the first character
6661 in the buffer is not a hex character, assume that has happened
6662 and try to fetch another packet to read. */
6663 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6664 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6665 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6666 && rs->buf[0] != 'x') /* New: unavailable register value. */
6669 fprintf_unfiltered (gdb_stdlog,
6670 "Bad register packet; fetching a new packet\n");
6671 getpkt (&rs->buf, &rs->buf_size, 0);
6674 buf_len = strlen (rs->buf);
6676 /* Sanity check the received packet. */
6677 if (buf_len % 2 != 0)
6678 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6684 process_g_packet (struct regcache *regcache)
6686 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6687 struct remote_state *rs = get_remote_state ();
6688 struct remote_arch_state *rsa = get_remote_arch_state ();
6693 buf_len = strlen (rs->buf);
6695 /* Further sanity checks, with knowledge of the architecture. */
6696 if (buf_len > 2 * rsa->sizeof_g_packet)
6697 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6699 /* Save the size of the packet sent to us by the target. It is used
6700 as a heuristic when determining the max size of packets that the
6701 target can safely receive. */
6702 if (rsa->actual_register_packet_size == 0)
6703 rsa->actual_register_packet_size = buf_len;
6705 /* If this is smaller than we guessed the 'g' packet would be,
6706 update our records. A 'g' reply that doesn't include a register's
6707 value implies either that the register is not available, or that
6708 the 'p' packet must be used. */
6709 if (buf_len < 2 * rsa->sizeof_g_packet)
6711 rsa->sizeof_g_packet = buf_len / 2;
6713 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6715 if (rsa->regs[i].pnum == -1)
6718 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6719 rsa->regs[i].in_g_packet = 0;
6721 rsa->regs[i].in_g_packet = 1;
6725 regs = alloca (rsa->sizeof_g_packet);
6727 /* Unimplemented registers read as all bits zero. */
6728 memset (regs, 0, rsa->sizeof_g_packet);
6730 /* Reply describes registers byte by byte, each byte encoded as two
6731 hex characters. Suck them all up, then supply them to the
6732 register cacheing/storage mechanism. */
6735 for (i = 0; i < rsa->sizeof_g_packet; i++)
6737 if (p[0] == 0 || p[1] == 0)
6738 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6739 internal_error (__FILE__, __LINE__,
6740 _("unexpected end of 'g' packet reply"));
6742 if (p[0] == 'x' && p[1] == 'x')
6743 regs[i] = 0; /* 'x' */
6745 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6749 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6751 struct packet_reg *r = &rsa->regs[i];
6755 if (r->offset * 2 >= strlen (rs->buf))
6756 /* This shouldn't happen - we adjusted in_g_packet above. */
6757 internal_error (__FILE__, __LINE__,
6758 _("unexpected end of 'g' packet reply"));
6759 else if (rs->buf[r->offset * 2] == 'x')
6761 gdb_assert (r->offset * 2 < strlen (rs->buf));
6762 /* The register isn't available, mark it as such (at
6763 the same time setting the value to zero). */
6764 regcache_raw_supply (regcache, r->regnum, NULL);
6767 regcache_raw_supply (regcache, r->regnum,
6774 fetch_registers_using_g (struct regcache *regcache)
6777 process_g_packet (regcache);
6780 /* Make the remote selected traceframe match GDB's selected
6784 set_remote_traceframe (void)
6787 struct remote_state *rs = get_remote_state ();
6789 if (rs->remote_traceframe_number == get_traceframe_number ())
6792 /* Avoid recursion, remote_trace_find calls us again. */
6793 rs->remote_traceframe_number = get_traceframe_number ();
6795 newnum = target_trace_find (tfind_number,
6796 get_traceframe_number (), 0, 0, NULL);
6798 /* Should not happen. If it does, all bets are off. */
6799 if (newnum != get_traceframe_number ())
6800 warning (_("could not set remote traceframe"));
6804 remote_fetch_registers (struct target_ops *ops,
6805 struct regcache *regcache, int regnum)
6807 struct remote_arch_state *rsa = get_remote_arch_state ();
6810 set_remote_traceframe ();
6811 set_general_thread (inferior_ptid);
6815 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6817 gdb_assert (reg != NULL);
6819 /* If this register might be in the 'g' packet, try that first -
6820 we are likely to read more than one register. If this is the
6821 first 'g' packet, we might be overly optimistic about its
6822 contents, so fall back to 'p'. */
6823 if (reg->in_g_packet)
6825 fetch_registers_using_g (regcache);
6826 if (reg->in_g_packet)
6830 if (fetch_register_using_p (regcache, reg))
6833 /* This register is not available. */
6834 regcache_raw_supply (regcache, reg->regnum, NULL);
6839 fetch_registers_using_g (regcache);
6841 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6842 if (!rsa->regs[i].in_g_packet)
6843 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6845 /* This register is not available. */
6846 regcache_raw_supply (regcache, i, NULL);
6850 /* Prepare to store registers. Since we may send them all (using a
6851 'G' request), we have to read out the ones we don't want to change
6855 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6857 struct remote_arch_state *rsa = get_remote_arch_state ();
6859 gdb_byte buf[MAX_REGISTER_SIZE];
6861 /* Make sure the entire registers array is valid. */
6862 switch (packet_support (PACKET_P))
6864 case PACKET_DISABLE:
6865 case PACKET_SUPPORT_UNKNOWN:
6866 /* Make sure all the necessary registers are cached. */
6867 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6868 if (rsa->regs[i].in_g_packet)
6869 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6876 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6877 packet was not recognized. */
6880 store_register_using_P (const struct regcache *regcache,
6881 struct packet_reg *reg)
6883 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6884 struct remote_state *rs = get_remote_state ();
6885 /* Try storing a single register. */
6886 char *buf = rs->buf;
6887 gdb_byte regp[MAX_REGISTER_SIZE];
6890 if (packet_support (PACKET_P) == PACKET_DISABLE)
6893 if (reg->pnum == -1)
6896 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6897 p = buf + strlen (buf);
6898 regcache_raw_collect (regcache, reg->regnum, regp);
6899 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6901 getpkt (&rs->buf, &rs->buf_size, 0);
6903 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6908 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6909 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6910 case PACKET_UNKNOWN:
6913 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6917 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6918 contents of the register cache buffer. FIXME: ignores errors. */
6921 store_registers_using_G (const struct regcache *regcache)
6923 struct remote_state *rs = get_remote_state ();
6924 struct remote_arch_state *rsa = get_remote_arch_state ();
6928 /* Extract all the registers in the regcache copying them into a
6933 regs = alloca (rsa->sizeof_g_packet);
6934 memset (regs, 0, rsa->sizeof_g_packet);
6935 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6937 struct packet_reg *r = &rsa->regs[i];
6940 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6944 /* Command describes registers byte by byte,
6945 each byte encoded as two hex characters. */
6948 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6950 bin2hex (regs, p, rsa->sizeof_g_packet);
6952 getpkt (&rs->buf, &rs->buf_size, 0);
6953 if (packet_check_result (rs->buf) == PACKET_ERROR)
6954 error (_("Could not write registers; remote failure reply '%s'"),
6958 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6959 of the register cache buffer. FIXME: ignores errors. */
6962 remote_store_registers (struct target_ops *ops,
6963 struct regcache *regcache, int regnum)
6965 struct remote_arch_state *rsa = get_remote_arch_state ();
6968 set_remote_traceframe ();
6969 set_general_thread (inferior_ptid);
6973 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6975 gdb_assert (reg != NULL);
6977 /* Always prefer to store registers using the 'P' packet if
6978 possible; we often change only a small number of registers.
6979 Sometimes we change a larger number; we'd need help from a
6980 higher layer to know to use 'G'. */
6981 if (store_register_using_P (regcache, reg))
6984 /* For now, don't complain if we have no way to write the
6985 register. GDB loses track of unavailable registers too
6986 easily. Some day, this may be an error. We don't have
6987 any way to read the register, either... */
6988 if (!reg->in_g_packet)
6991 store_registers_using_G (regcache);
6995 store_registers_using_G (regcache);
6997 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6998 if (!rsa->regs[i].in_g_packet)
6999 if (!store_register_using_P (regcache, &rsa->regs[i]))
7000 /* See above for why we do not issue an error here. */
7005 /* Return the number of hex digits in num. */
7008 hexnumlen (ULONGEST num)
7012 for (i = 0; num != 0; i++)
7018 /* Set BUF to the minimum number of hex digits representing NUM. */
7021 hexnumstr (char *buf, ULONGEST num)
7023 int len = hexnumlen (num);
7025 return hexnumnstr (buf, num, len);
7029 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7032 hexnumnstr (char *buf, ULONGEST num, int width)
7038 for (i = width - 1; i >= 0; i--)
7040 buf[i] = "0123456789abcdef"[(num & 0xf)];
7047 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7050 remote_address_masked (CORE_ADDR addr)
7052 unsigned int address_size = remote_address_size;
7054 /* If "remoteaddresssize" was not set, default to target address size. */
7056 address_size = gdbarch_addr_bit (target_gdbarch ());
7058 if (address_size > 0
7059 && address_size < (sizeof (ULONGEST) * 8))
7061 /* Only create a mask when that mask can safely be constructed
7062 in a ULONGEST variable. */
7065 mask = (mask << address_size) - 1;
7071 /* Determine whether the remote target supports binary downloading.
7072 This is accomplished by sending a no-op memory write of zero length
7073 to the target at the specified address. It does not suffice to send
7074 the whole packet, since many stubs strip the eighth bit and
7075 subsequently compute a wrong checksum, which causes real havoc with
7078 NOTE: This can still lose if the serial line is not eight-bit
7079 clean. In cases like this, the user should clear "remote
7083 check_binary_download (CORE_ADDR addr)
7085 struct remote_state *rs = get_remote_state ();
7087 switch (packet_support (PACKET_X))
7089 case PACKET_DISABLE:
7093 case PACKET_SUPPORT_UNKNOWN:
7099 p += hexnumstr (p, (ULONGEST) addr);
7101 p += hexnumstr (p, (ULONGEST) 0);
7105 putpkt_binary (rs->buf, (int) (p - rs->buf));
7106 getpkt (&rs->buf, &rs->buf_size, 0);
7108 if (rs->buf[0] == '\0')
7111 fprintf_unfiltered (gdb_stdlog,
7112 "binary downloading NOT "
7113 "supported by target\n");
7114 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7119 fprintf_unfiltered (gdb_stdlog,
7120 "binary downloading supported by target\n");
7121 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7128 /* Helper function to resize the payload in order to try to get a good
7129 alignment. We try to write an amount of data such that the next write will
7130 start on an address aligned on REMOTE_ALIGN_WRITES. */
7133 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7135 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7138 /* Write memory data directly to the remote machine.
7139 This does not inform the data cache; the data cache uses this.
7140 HEADER is the starting part of the packet.
7141 MEMADDR is the address in the remote memory space.
7142 MYADDR is the address of the buffer in our space.
7143 LEN_UNITS is the number of addressable units to write.
7144 UNIT_SIZE is the length in bytes of an addressable unit.
7145 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7146 should send data as binary ('X'), or hex-encoded ('M').
7148 The function creates packet of the form
7149 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7151 where encoding of <DATA> is terminated by PACKET_FORMAT.
7153 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7156 Return the transferred status, error or OK (an
7157 'enum target_xfer_status' value). Save the number of addressable units
7158 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7160 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7161 exchange between gdb and the stub could look like (?? in place of the
7167 -> $M1000,3:eeeeffffeeee#??
7171 <- eeeeffffeeeedddd */
7173 static enum target_xfer_status
7174 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7175 const gdb_byte *myaddr, ULONGEST len_units,
7176 int unit_size, ULONGEST *xfered_len_units,
7177 char packet_format, int use_length)
7179 struct remote_state *rs = get_remote_state ();
7185 int payload_capacity_bytes;
7186 int payload_length_bytes;
7188 if (packet_format != 'X' && packet_format != 'M')
7189 internal_error (__FILE__, __LINE__,
7190 _("remote_write_bytes_aux: bad packet format"));
7193 return TARGET_XFER_EOF;
7195 payload_capacity_bytes = get_memory_write_packet_size ();
7197 /* The packet buffer will be large enough for the payload;
7198 get_memory_packet_size ensures this. */
7201 /* Compute the size of the actual payload by subtracting out the
7202 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7204 payload_capacity_bytes -= strlen ("$,:#NN");
7206 /* The comma won't be used. */
7207 payload_capacity_bytes += 1;
7208 payload_capacity_bytes -= strlen (header);
7209 payload_capacity_bytes -= hexnumlen (memaddr);
7211 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7213 strcat (rs->buf, header);
7214 p = rs->buf + strlen (header);
7216 /* Compute a best guess of the number of bytes actually transfered. */
7217 if (packet_format == 'X')
7219 /* Best guess at number of bytes that will fit. */
7220 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7222 payload_capacity_bytes -= hexnumlen (todo_units);
7223 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7227 /* Number of bytes that will fit. */
7228 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7230 payload_capacity_bytes -= hexnumlen (todo_units);
7231 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7234 if (todo_units <= 0)
7235 internal_error (__FILE__, __LINE__,
7236 _("minimum packet size too small to write data"));
7238 /* If we already need another packet, then try to align the end
7239 of this packet to a useful boundary. */
7240 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7241 todo_units = align_for_efficient_write (todo_units, memaddr);
7243 /* Append "<memaddr>". */
7244 memaddr = remote_address_masked (memaddr);
7245 p += hexnumstr (p, (ULONGEST) memaddr);
7252 /* Append the length and retain its location and size. It may need to be
7253 adjusted once the packet body has been created. */
7255 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7263 /* Append the packet body. */
7264 if (packet_format == 'X')
7266 /* Binary mode. Send target system values byte by byte, in
7267 increasing byte addresses. Only escape certain critical
7269 payload_length_bytes =
7270 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7271 &units_written, payload_capacity_bytes);
7273 /* If not all TODO units fit, then we'll need another packet. Make
7274 a second try to keep the end of the packet aligned. Don't do
7275 this if the packet is tiny. */
7276 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7280 new_todo_units = align_for_efficient_write (units_written, memaddr);
7282 if (new_todo_units != units_written)
7283 payload_length_bytes =
7284 remote_escape_output (myaddr, new_todo_units, unit_size,
7285 (gdb_byte *) p, &units_written,
7286 payload_capacity_bytes);
7289 p += payload_length_bytes;
7290 if (use_length && units_written < todo_units)
7292 /* Escape chars have filled up the buffer prematurely,
7293 and we have actually sent fewer units than planned.
7294 Fix-up the length field of the packet. Use the same
7295 number of characters as before. */
7296 plen += hexnumnstr (plen, (ULONGEST) units_written,
7298 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7303 /* Normal mode: Send target system values byte by byte, in
7304 increasing byte addresses. Each byte is encoded as a two hex
7306 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7307 units_written = todo_units;
7310 putpkt_binary (rs->buf, (int) (p - rs->buf));
7311 getpkt (&rs->buf, &rs->buf_size, 0);
7313 if (rs->buf[0] == 'E')
7314 return TARGET_XFER_E_IO;
7316 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7317 send fewer units than we'd planned. */
7318 *xfered_len_units = (ULONGEST) units_written;
7319 return TARGET_XFER_OK;
7322 /* Write memory data directly to the remote machine.
7323 This does not inform the data cache; the data cache uses this.
7324 MEMADDR is the address in the remote memory space.
7325 MYADDR is the address of the buffer in our space.
7326 LEN is the number of bytes.
7328 Return the transferred status, error or OK (an
7329 'enum target_xfer_status' value). Save the number of bytes
7330 transferred in *XFERED_LEN. Only transfer a single packet. */
7332 static enum target_xfer_status
7333 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7334 int unit_size, ULONGEST *xfered_len)
7336 char *packet_format = 0;
7338 /* Check whether the target supports binary download. */
7339 check_binary_download (memaddr);
7341 switch (packet_support (PACKET_X))
7344 packet_format = "X";
7346 case PACKET_DISABLE:
7347 packet_format = "M";
7349 case PACKET_SUPPORT_UNKNOWN:
7350 internal_error (__FILE__, __LINE__,
7351 _("remote_write_bytes: bad internal state"));
7353 internal_error (__FILE__, __LINE__, _("bad switch"));
7356 return remote_write_bytes_aux (packet_format,
7357 memaddr, myaddr, len, unit_size, xfered_len,
7358 packet_format[0], 1);
7361 /* Read memory data directly from the remote machine.
7362 This does not use the data cache; the data cache uses this.
7363 MEMADDR is the address in the remote memory space.
7364 MYADDR is the address of the buffer in our space.
7365 LEN_UNITS is the number of addressable memory units to read..
7366 UNIT_SIZE is the length in bytes of an addressable unit.
7368 Return the transferred status, error or OK (an
7369 'enum target_xfer_status' value). Save the number of bytes
7370 transferred in *XFERED_LEN_UNITS.
7372 See the comment of remote_write_bytes_aux for an example of
7373 memory read/write exchange between gdb and the stub. */
7375 static enum target_xfer_status
7376 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7377 int unit_size, ULONGEST *xfered_len_units)
7379 struct remote_state *rs = get_remote_state ();
7380 int buf_size_bytes; /* Max size of packet output buffer. */
7385 buf_size_bytes = get_memory_read_packet_size ();
7386 /* The packet buffer will be large enough for the payload;
7387 get_memory_packet_size ensures this. */
7389 /* Number of units that will fit. */
7390 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7392 /* Construct "m"<memaddr>","<len>". */
7393 memaddr = remote_address_masked (memaddr);
7396 p += hexnumstr (p, (ULONGEST) memaddr);
7398 p += hexnumstr (p, (ULONGEST) todo_units);
7401 getpkt (&rs->buf, &rs->buf_size, 0);
7402 if (rs->buf[0] == 'E'
7403 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7404 && rs->buf[3] == '\0')
7405 return TARGET_XFER_E_IO;
7406 /* Reply describes memory byte by byte, each byte encoded as two hex
7409 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7410 /* Return what we have. Let higher layers handle partial reads. */
7411 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7412 return TARGET_XFER_OK;
7415 /* Using the set of read-only target sections of remote, read live
7418 For interface/parameters/return description see target.h,
7421 static enum target_xfer_status
7422 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7423 ULONGEST memaddr, ULONGEST len,
7424 int unit_size, ULONGEST *xfered_len)
7426 struct target_section *secp;
7427 struct target_section_table *table;
7429 secp = target_section_by_addr (ops, memaddr);
7431 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7432 secp->the_bfd_section)
7435 struct target_section *p;
7436 ULONGEST memend = memaddr + len;
7438 table = target_get_section_table (ops);
7440 for (p = table->sections; p < table->sections_end; p++)
7442 if (memaddr >= p->addr)
7444 if (memend <= p->endaddr)
7446 /* Entire transfer is within this section. */
7447 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7450 else if (memaddr >= p->endaddr)
7452 /* This section ends before the transfer starts. */
7457 /* This section overlaps the transfer. Just do half. */
7458 len = p->endaddr - memaddr;
7459 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7466 return TARGET_XFER_EOF;
7469 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7470 first if the requested memory is unavailable in traceframe.
7471 Otherwise, fall back to remote_read_bytes_1. */
7473 static enum target_xfer_status
7474 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7475 gdb_byte *myaddr, ULONGEST len, int unit_size,
7476 ULONGEST *xfered_len)
7479 return TARGET_XFER_EOF;
7481 if (get_traceframe_number () != -1)
7483 VEC(mem_range_s) *available;
7485 /* If we fail to get the set of available memory, then the
7486 target does not support querying traceframe info, and so we
7487 attempt reading from the traceframe anyway (assuming the
7488 target implements the old QTro packet then). */
7489 if (traceframe_available_memory (&available, memaddr, len))
7491 struct cleanup *old_chain;
7493 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7495 if (VEC_empty (mem_range_s, available)
7496 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7498 enum target_xfer_status res;
7500 /* Don't read into the traceframe's available
7502 if (!VEC_empty (mem_range_s, available))
7504 LONGEST oldlen = len;
7506 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7507 gdb_assert (len <= oldlen);
7510 do_cleanups (old_chain);
7512 /* This goes through the topmost target again. */
7513 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7514 len, unit_size, xfered_len);
7515 if (res == TARGET_XFER_OK)
7516 return TARGET_XFER_OK;
7519 /* No use trying further, we know some memory starting
7520 at MEMADDR isn't available. */
7522 return TARGET_XFER_UNAVAILABLE;
7526 /* Don't try to read more than how much is available, in
7527 case the target implements the deprecated QTro packet to
7528 cater for older GDBs (the target's knowledge of read-only
7529 sections may be outdated by now). */
7530 len = VEC_index (mem_range_s, available, 0)->length;
7532 do_cleanups (old_chain);
7536 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7541 /* Sends a packet with content determined by the printf format string
7542 FORMAT and the remaining arguments, then gets the reply. Returns
7543 whether the packet was a success, a failure, or unknown. */
7545 static enum packet_result remote_send_printf (const char *format, ...)
7546 ATTRIBUTE_PRINTF (1, 2);
7548 static enum packet_result
7549 remote_send_printf (const char *format, ...)
7551 struct remote_state *rs = get_remote_state ();
7552 int max_size = get_remote_packet_size ();
7555 va_start (ap, format);
7558 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7559 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7561 if (putpkt (rs->buf) < 0)
7562 error (_("Communication problem with target."));
7565 getpkt (&rs->buf, &rs->buf_size, 0);
7567 return packet_check_result (rs->buf);
7571 restore_remote_timeout (void *p)
7573 int value = *(int *)p;
7575 remote_timeout = value;
7578 /* Flash writing can take quite some time. We'll set
7579 effectively infinite timeout for flash operations.
7580 In future, we'll need to decide on a better approach. */
7581 static const int remote_flash_timeout = 1000;
7584 remote_flash_erase (struct target_ops *ops,
7585 ULONGEST address, LONGEST length)
7587 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7588 int saved_remote_timeout = remote_timeout;
7589 enum packet_result ret;
7590 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7591 &saved_remote_timeout);
7593 remote_timeout = remote_flash_timeout;
7595 ret = remote_send_printf ("vFlashErase:%s,%s",
7596 phex (address, addr_size),
7600 case PACKET_UNKNOWN:
7601 error (_("Remote target does not support flash erase"));
7603 error (_("Error erasing flash with vFlashErase packet"));
7608 do_cleanups (back_to);
7611 static enum target_xfer_status
7612 remote_flash_write (struct target_ops *ops, ULONGEST address,
7613 ULONGEST length, ULONGEST *xfered_len,
7614 const gdb_byte *data)
7616 int saved_remote_timeout = remote_timeout;
7617 enum target_xfer_status ret;
7618 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7619 &saved_remote_timeout);
7621 remote_timeout = remote_flash_timeout;
7622 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7624 do_cleanups (back_to);
7630 remote_flash_done (struct target_ops *ops)
7632 int saved_remote_timeout = remote_timeout;
7634 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7635 &saved_remote_timeout);
7637 remote_timeout = remote_flash_timeout;
7638 ret = remote_send_printf ("vFlashDone");
7639 do_cleanups (back_to);
7643 case PACKET_UNKNOWN:
7644 error (_("Remote target does not support vFlashDone"));
7646 error (_("Error finishing flash operation"));
7653 remote_files_info (struct target_ops *ignore)
7655 puts_filtered ("Debugging a target over a serial line.\n");
7658 /* Stuff for dealing with the packets which are part of this protocol.
7659 See comment at top of file for details. */
7661 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7662 error to higher layers. Called when a serial error is detected.
7663 The exception message is STRING, followed by a colon and a blank,
7664 the system error message for errno at function entry and final dot
7665 for output compatibility with throw_perror_with_name. */
7668 unpush_and_perror (const char *string)
7670 int saved_errno = errno;
7672 remote_unpush_target ();
7673 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7674 safe_strerror (saved_errno));
7677 /* Read a single character from the remote end. */
7680 readchar (int timeout)
7683 struct remote_state *rs = get_remote_state ();
7685 ch = serial_readchar (rs->remote_desc, timeout);
7690 switch ((enum serial_rc) ch)
7693 remote_unpush_target ();
7694 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7697 unpush_and_perror (_("Remote communication error. "
7698 "Target disconnected."));
7700 case SERIAL_TIMEOUT:
7706 /* Wrapper for serial_write that closes the target and throws if
7710 remote_serial_write (const char *str, int len)
7712 struct remote_state *rs = get_remote_state ();
7714 if (serial_write (rs->remote_desc, str, len))
7716 unpush_and_perror (_("Remote communication error. "
7717 "Target disconnected."));
7721 /* Send the command in *BUF to the remote machine, and read the reply
7722 into *BUF. Report an error if we get an error reply. Resize
7723 *BUF using xrealloc if necessary to hold the result, and update
7727 remote_send (char **buf,
7731 getpkt (buf, sizeof_buf, 0);
7733 if ((*buf)[0] == 'E')
7734 error (_("Remote failure reply: %s"), *buf);
7737 /* Return a pointer to an xmalloc'ed string representing an escaped
7738 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7739 etc. The caller is responsible for releasing the returned
7743 escape_buffer (const char *buf, int n)
7745 struct cleanup *old_chain;
7746 struct ui_file *stb;
7749 stb = mem_fileopen ();
7750 old_chain = make_cleanup_ui_file_delete (stb);
7752 fputstrn_unfiltered (buf, n, '\\', stb);
7753 str = ui_file_xstrdup (stb, NULL);
7754 do_cleanups (old_chain);
7758 /* Display a null-terminated packet on stdout, for debugging, using C
7762 print_packet (const char *buf)
7764 puts_filtered ("\"");
7765 fputstr_filtered (buf, '"', gdb_stdout);
7766 puts_filtered ("\"");
7770 putpkt (const char *buf)
7772 return putpkt_binary (buf, strlen (buf));
7775 /* Send a packet to the remote machine, with error checking. The data
7776 of the packet is in BUF. The string in BUF can be at most
7777 get_remote_packet_size () - 5 to account for the $, # and checksum,
7778 and for a possible /0 if we are debugging (remote_debug) and want
7779 to print the sent packet as a string. */
7782 putpkt_binary (const char *buf, int cnt)
7784 struct remote_state *rs = get_remote_state ();
7786 unsigned char csum = 0;
7787 char *buf2 = alloca (cnt + 6);
7794 /* Catch cases like trying to read memory or listing threads while
7795 we're waiting for a stop reply. The remote server wouldn't be
7796 ready to handle this request, so we'd hang and timeout. We don't
7797 have to worry about this in synchronous mode, because in that
7798 case it's not possible to issue a command while the target is
7799 running. This is not a problem in non-stop mode, because in that
7800 case, the stub is always ready to process serial input. */
7801 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7803 error (_("Cannot execute this command while the target is running.\n"
7804 "Use the \"interrupt\" command to stop the target\n"
7805 "and then try again."));
7808 /* We're sending out a new packet. Make sure we don't look at a
7809 stale cached response. */
7810 rs->cached_wait_status = 0;
7812 /* Copy the packet into buffer BUF2, encapsulating it
7813 and giving it a checksum. */
7818 for (i = 0; i < cnt; i++)
7824 *p++ = tohex ((csum >> 4) & 0xf);
7825 *p++ = tohex (csum & 0xf);
7827 /* Send it over and over until we get a positive ack. */
7831 int started_error_output = 0;
7835 struct cleanup *old_chain;
7839 str = escape_buffer (buf2, p - buf2);
7840 old_chain = make_cleanup (xfree, str);
7841 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7842 gdb_flush (gdb_stdlog);
7843 do_cleanups (old_chain);
7845 remote_serial_write (buf2, p - buf2);
7847 /* If this is a no acks version of the remote protocol, send the
7848 packet and move on. */
7852 /* Read until either a timeout occurs (-2) or '+' is read.
7853 Handle any notification that arrives in the mean time. */
7856 ch = readchar (remote_timeout);
7864 case SERIAL_TIMEOUT:
7867 if (started_error_output)
7869 putchar_unfiltered ('\n');
7870 started_error_output = 0;
7879 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7883 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7885 case SERIAL_TIMEOUT:
7889 break; /* Retransmit buffer. */
7893 fprintf_unfiltered (gdb_stdlog,
7894 "Packet instead of Ack, ignoring it\n");
7895 /* It's probably an old response sent because an ACK
7896 was lost. Gobble up the packet and ack it so it
7897 doesn't get retransmitted when we resend this
7900 remote_serial_write ("+", 1);
7901 continue; /* Now, go look for +. */
7908 /* If we got a notification, handle it, and go back to looking
7910 /* We've found the start of a notification. Now
7911 collect the data. */
7912 val = read_frame (&rs->buf, &rs->buf_size);
7917 struct cleanup *old_chain;
7920 str = escape_buffer (rs->buf, val);
7921 old_chain = make_cleanup (xfree, str);
7922 fprintf_unfiltered (gdb_stdlog,
7923 " Notification received: %s\n",
7925 do_cleanups (old_chain);
7927 handle_notification (rs->notif_state, rs->buf);
7928 /* We're in sync now, rewait for the ack. */
7935 if (!started_error_output)
7937 started_error_output = 1;
7938 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7940 fputc_unfiltered (ch & 0177, gdb_stdlog);
7941 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7950 if (!started_error_output)
7952 started_error_output = 1;
7953 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7955 fputc_unfiltered (ch & 0177, gdb_stdlog);
7959 break; /* Here to retransmit. */
7963 /* This is wrong. If doing a long backtrace, the user should be
7964 able to get out next time we call QUIT, without anything as
7965 violent as interrupt_query. If we want to provide a way out of
7966 here without getting to the next QUIT, it should be based on
7967 hitting ^C twice as in remote_wait. */
7978 /* Come here after finding the start of a frame when we expected an
7979 ack. Do our best to discard the rest of this packet. */
7988 c = readchar (remote_timeout);
7991 case SERIAL_TIMEOUT:
7992 /* Nothing we can do. */
7995 /* Discard the two bytes of checksum and stop. */
7996 c = readchar (remote_timeout);
7998 c = readchar (remote_timeout);
8001 case '*': /* Run length encoding. */
8002 /* Discard the repeat count. */
8003 c = readchar (remote_timeout);
8008 /* A regular character. */
8014 /* Come here after finding the start of the frame. Collect the rest
8015 into *BUF, verifying the checksum, length, and handling run-length
8016 compression. NUL terminate the buffer. If there is not enough room,
8017 expand *BUF using xrealloc.
8019 Returns -1 on error, number of characters in buffer (ignoring the
8020 trailing NULL) on success. (could be extended to return one of the
8021 SERIAL status indications). */
8024 read_frame (char **buf_p,
8031 struct remote_state *rs = get_remote_state ();
8038 c = readchar (remote_timeout);
8041 case SERIAL_TIMEOUT:
8043 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8047 fputs_filtered ("Saw new packet start in middle of old one\n",
8049 return -1; /* Start a new packet, count retries. */
8052 unsigned char pktcsum;
8058 check_0 = readchar (remote_timeout);
8060 check_1 = readchar (remote_timeout);
8062 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8065 fputs_filtered ("Timeout in checksum, retrying\n",
8069 else if (check_0 < 0 || check_1 < 0)
8072 fputs_filtered ("Communication error in checksum\n",
8077 /* Don't recompute the checksum; with no ack packets we
8078 don't have any way to indicate a packet retransmission
8083 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8084 if (csum == pktcsum)
8089 struct cleanup *old_chain;
8092 str = escape_buffer (buf, bc);
8093 old_chain = make_cleanup (xfree, str);
8094 fprintf_unfiltered (gdb_stdlog,
8095 "Bad checksum, sentsum=0x%x, "
8096 "csum=0x%x, buf=%s\n",
8097 pktcsum, csum, str);
8098 do_cleanups (old_chain);
8100 /* Number of characters in buffer ignoring trailing
8104 case '*': /* Run length encoding. */
8109 c = readchar (remote_timeout);
8111 repeat = c - ' ' + 3; /* Compute repeat count. */
8113 /* The character before ``*'' is repeated. */
8115 if (repeat > 0 && repeat <= 255 && bc > 0)
8117 if (bc + repeat - 1 >= *sizeof_buf - 1)
8119 /* Make some more room in the buffer. */
8120 *sizeof_buf += repeat;
8121 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8125 memset (&buf[bc], buf[bc - 1], repeat);
8131 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8135 if (bc >= *sizeof_buf - 1)
8137 /* Make some more room in the buffer. */
8139 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8150 /* Read a packet from the remote machine, with error checking, and
8151 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8152 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8153 rather than timing out; this is used (in synchronous mode) to wait
8154 for a target that is is executing user code to stop. */
8155 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8156 don't have to change all the calls to getpkt to deal with the
8157 return value, because at the moment I don't know what the right
8158 thing to do it for those. */
8166 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8170 /* Read a packet from the remote machine, with error checking, and
8171 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8172 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8173 rather than timing out; this is used (in synchronous mode) to wait
8174 for a target that is is executing user code to stop. If FOREVER ==
8175 0, this function is allowed to time out gracefully and return an
8176 indication of this to the caller. Otherwise return the number of
8177 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8178 enough reason to return to the caller. *IS_NOTIF is an output
8179 boolean that indicates whether *BUF holds a notification or not
8180 (a regular packet). */
8183 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8184 int expecting_notif, int *is_notif)
8186 struct remote_state *rs = get_remote_state ();
8192 /* We're reading a new response. Make sure we don't look at a
8193 previously cached response. */
8194 rs->cached_wait_status = 0;
8196 strcpy (*buf, "timeout");
8199 timeout = watchdog > 0 ? watchdog : -1;
8200 else if (expecting_notif)
8201 timeout = 0; /* There should already be a char in the buffer. If
8204 timeout = remote_timeout;
8208 /* Process any number of notifications, and then return when
8212 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8214 for (tries = 1; tries <= MAX_TRIES; tries++)
8216 /* This can loop forever if the remote side sends us
8217 characters continuously, but if it pauses, we'll get
8218 SERIAL_TIMEOUT from readchar because of timeout. Then
8219 we'll count that as a retry.
8221 Note that even when forever is set, we will only wait
8222 forever prior to the start of a packet. After that, we
8223 expect characters to arrive at a brisk pace. They should
8224 show up within remote_timeout intervals. */
8226 c = readchar (timeout);
8227 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8229 if (c == SERIAL_TIMEOUT)
8231 if (expecting_notif)
8232 return -1; /* Don't complain, it's normal to not get
8233 anything in this case. */
8235 if (forever) /* Watchdog went off? Kill the target. */
8238 remote_unpush_target ();
8239 throw_error (TARGET_CLOSE_ERROR,
8240 _("Watchdog timeout has expired. "
8241 "Target detached."));
8244 fputs_filtered ("Timed out.\n", gdb_stdlog);
8248 /* We've found the start of a packet or notification.
8249 Now collect the data. */
8250 val = read_frame (buf, sizeof_buf);
8255 remote_serial_write ("-", 1);
8258 if (tries > MAX_TRIES)
8260 /* We have tried hard enough, and just can't receive the
8261 packet/notification. Give up. */
8262 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8264 /* Skip the ack char if we're in no-ack mode. */
8265 if (!rs->noack_mode)
8266 remote_serial_write ("+", 1);
8270 /* If we got an ordinary packet, return that to our caller. */
8275 struct cleanup *old_chain;
8278 str = escape_buffer (*buf, val);
8279 old_chain = make_cleanup (xfree, str);
8280 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8281 do_cleanups (old_chain);
8284 /* Skip the ack char if we're in no-ack mode. */
8285 if (!rs->noack_mode)
8286 remote_serial_write ("+", 1);
8287 if (is_notif != NULL)
8292 /* If we got a notification, handle it, and go back to looking
8296 gdb_assert (c == '%');
8300 struct cleanup *old_chain;
8303 str = escape_buffer (*buf, val);
8304 old_chain = make_cleanup (xfree, str);
8305 fprintf_unfiltered (gdb_stdlog,
8306 " Notification received: %s\n",
8308 do_cleanups (old_chain);
8310 if (is_notif != NULL)
8313 handle_notification (rs->notif_state, *buf);
8315 /* Notifications require no acknowledgement. */
8317 if (expecting_notif)
8324 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8326 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8330 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8333 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8337 /* Check whether EVENT is a fork event for the process specified
8338 by the pid passed in DATA, and if it is, kill the fork child. */
8341 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8342 QUEUE_ITER (stop_reply_p) *iter,
8346 struct queue_iter_param *param = data;
8347 int parent_pid = *(int *) param->input;
8349 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8351 struct remote_state *rs = get_remote_state ();
8352 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8355 res = remote_vkill (child_pid, rs);
8357 error (_("Can't kill fork child process %d"), child_pid);
8363 /* Kill any new fork children of process PID that haven't been
8364 processed by follow_fork. */
8367 kill_new_fork_children (int pid, struct remote_state *rs)
8369 struct thread_info *thread;
8370 struct notif_client *notif = ¬if_client_stop;
8371 struct queue_iter_param param;
8373 /* Kill the fork child threads of any threads in process PID
8374 that are stopped at a fork event. */
8375 ALL_NON_EXITED_THREADS (thread)
8377 struct target_waitstatus *ws = &thread->pending_follow;
8379 if (is_pending_fork_parent (ws, pid, thread->ptid))
8381 struct remote_state *rs = get_remote_state ();
8382 int child_pid = ptid_get_pid (ws->value.related_pid);
8385 res = remote_vkill (child_pid, rs);
8387 error (_("Can't kill fork child process %d"), child_pid);
8391 /* Check for any pending fork events (not reported or processed yet)
8392 in process PID and kill those fork child threads as well. */
8393 remote_notif_get_pending_events (notif);
8395 param.output = NULL;
8396 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8397 kill_child_of_pending_fork, ¶m);
8402 remote_kill (struct target_ops *ops)
8405 /* Catch errors so the user can quit from gdb even when we
8406 aren't on speaking terms with the remote system. */
8411 CATCH (ex, RETURN_MASK_ERROR)
8413 if (ex.error == TARGET_CLOSE_ERROR)
8415 /* If we got an (EOF) error that caused the target
8416 to go away, then we're done, that's what we wanted.
8417 "k" is susceptible to cause a premature EOF, given
8418 that the remote server isn't actually required to
8419 reply to "k", and it can happen that it doesn't
8420 even get to reply ACK to the "k". */
8424 /* Otherwise, something went wrong. We didn't actually kill
8425 the target. Just propagate the exception, and let the
8426 user or higher layers decide what to do. */
8427 throw_exception (ex);
8431 /* We've killed the remote end, we get to mourn it. Since this is
8432 target remote, single-process, mourning the inferior also
8433 unpushes remote_ops. */
8434 target_mourn_inferior ();
8438 remote_vkill (int pid, struct remote_state *rs)
8440 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8443 /* Tell the remote target to detach. */
8444 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8446 getpkt (&rs->buf, &rs->buf_size, 0);
8448 switch (packet_ok (rs->buf,
8449 &remote_protocol_packets[PACKET_vKill]))
8455 case PACKET_UNKNOWN:
8458 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8463 extended_remote_kill (struct target_ops *ops)
8466 int pid = ptid_get_pid (inferior_ptid);
8467 struct remote_state *rs = get_remote_state ();
8469 /* If we're stopped while forking and we haven't followed yet, kill the
8470 child task. We need to do this before killing the parent task
8471 because if this is a vfork then the parent will be sleeping. */
8472 kill_new_fork_children (pid, rs);
8474 res = remote_vkill (pid, rs);
8475 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8477 /* Don't try 'k' on a multi-process aware stub -- it has no way
8478 to specify the pid. */
8482 getpkt (&rs->buf, &rs->buf_size, 0);
8483 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8486 /* Don't wait for it to die. I'm not really sure it matters whether
8487 we do or not. For the existing stubs, kill is a noop. */
8493 error (_("Can't kill process"));
8495 target_mourn_inferior ();
8499 remote_mourn (struct target_ops *target)
8501 unpush_target (target);
8503 /* remote_close takes care of doing most of the clean up. */
8504 generic_mourn_inferior ();
8508 extended_remote_mourn (struct target_ops *target)
8510 struct remote_state *rs = get_remote_state ();
8512 /* In case we got here due to an error, but we're going to stay
8514 rs->waiting_for_stop_reply = 0;
8516 /* If the current general thread belonged to the process we just
8517 detached from or has exited, the remote side current general
8518 thread becomes undefined. Considering a case like this:
8520 - We just got here due to a detach.
8521 - The process that we're detaching from happens to immediately
8522 report a global breakpoint being hit in non-stop mode, in the
8523 same thread we had selected before.
8524 - GDB attaches to this process again.
8525 - This event happens to be the next event we handle.
8527 GDB would consider that the current general thread didn't need to
8528 be set on the stub side (with Hg), since for all it knew,
8529 GENERAL_THREAD hadn't changed.
8531 Notice that although in all-stop mode, the remote server always
8532 sets the current thread to the thread reporting the stop event,
8533 that doesn't happen in non-stop mode; in non-stop, the stub *must
8534 not* change the current thread when reporting a breakpoint hit,
8535 due to the decoupling of event reporting and event handling.
8537 To keep things simple, we always invalidate our notion of the
8539 record_currthread (rs, minus_one_ptid);
8541 /* Unlike "target remote", we do not want to unpush the target; then
8542 the next time the user says "run", we won't be connected. */
8544 /* Call common code to mark the inferior as not running. */
8545 generic_mourn_inferior ();
8547 if (!have_inferiors ())
8549 if (!remote_multi_process_p (rs))
8551 /* Check whether the target is running now - some remote stubs
8552 automatically restart after kill. */
8554 getpkt (&rs->buf, &rs->buf_size, 0);
8556 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8558 /* Assume that the target has been restarted. Set
8559 inferior_ptid so that bits of core GDB realizes
8560 there's something here, e.g., so that the user can
8561 say "kill" again. */
8562 inferior_ptid = magic_null_ptid;
8569 extended_remote_supports_disable_randomization (struct target_ops *self)
8571 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8575 extended_remote_disable_randomization (int val)
8577 struct remote_state *rs = get_remote_state ();
8580 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8583 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8585 error (_("Target does not support QDisableRandomization."));
8586 if (strcmp (reply, "OK") != 0)
8587 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8591 extended_remote_run (char *args)
8593 struct remote_state *rs = get_remote_state ();
8596 /* If the user has disabled vRun support, or we have detected that
8597 support is not available, do not try it. */
8598 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8601 strcpy (rs->buf, "vRun;");
8602 len = strlen (rs->buf);
8604 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8605 error (_("Remote file name too long for run packet"));
8606 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8607 strlen (remote_exec_file));
8609 gdb_assert (args != NULL);
8612 struct cleanup *back_to;
8616 argv = gdb_buildargv (args);
8617 back_to = make_cleanup_freeargv (argv);
8618 for (i = 0; argv[i] != NULL; i++)
8620 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8621 error (_("Argument list too long for run packet"));
8622 rs->buf[len++] = ';';
8623 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8626 do_cleanups (back_to);
8629 rs->buf[len++] = '\0';
8632 getpkt (&rs->buf, &rs->buf_size, 0);
8634 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8637 /* We have a wait response. All is well. */
8639 case PACKET_UNKNOWN:
8642 if (remote_exec_file[0] == '\0')
8643 error (_("Running the default executable on the remote target failed; "
8644 "try \"set remote exec-file\"?"));
8646 error (_("Running \"%s\" on the remote target failed"),
8649 gdb_assert_not_reached (_("bad switch"));
8653 /* In the extended protocol we want to be able to do things like
8654 "run" and have them basically work as expected. So we need
8655 a special create_inferior function. We support changing the
8656 executable file and the command line arguments, but not the
8660 extended_remote_create_inferior (struct target_ops *ops,
8661 char *exec_file, char *args,
8662 char **env, int from_tty)
8666 struct remote_state *rs = get_remote_state ();
8668 /* If running asynchronously, register the target file descriptor
8669 with the event loop. */
8670 if (target_can_async_p ())
8673 /* Disable address space randomization if requested (and supported). */
8674 if (extended_remote_supports_disable_randomization (ops))
8675 extended_remote_disable_randomization (disable_randomization);
8677 /* Now restart the remote server. */
8678 run_worked = extended_remote_run (args) != -1;
8681 /* vRun was not supported. Fail if we need it to do what the
8683 if (remote_exec_file[0])
8684 error (_("Remote target does not support \"set remote exec-file\""));
8686 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8688 /* Fall back to "R". */
8689 extended_remote_restart ();
8692 if (!have_inferiors ())
8694 /* Clean up from the last time we ran, before we mark the target
8695 running again. This will mark breakpoints uninserted, and
8696 get_offsets may insert breakpoints. */
8697 init_thread_list ();
8698 init_wait_for_inferior ();
8701 /* vRun's success return is a stop reply. */
8702 stop_reply = run_worked ? rs->buf : NULL;
8703 add_current_inferior_and_thread (stop_reply);
8705 /* Get updated offsets, if the stub uses qOffsets. */
8710 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8711 the list of conditions (in agent expression bytecode format), if any, the
8712 target needs to evaluate. The output is placed into the packet buffer
8713 started from BUF and ended at BUF_END. */
8716 remote_add_target_side_condition (struct gdbarch *gdbarch,
8717 struct bp_target_info *bp_tgt, char *buf,
8720 struct agent_expr *aexpr = NULL;
8723 char *buf_start = buf;
8725 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8728 buf += strlen (buf);
8729 xsnprintf (buf, buf_end - buf, "%s", ";");
8732 /* Send conditions to the target and free the vector. */
8734 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8737 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8738 buf += strlen (buf);
8739 for (i = 0; i < aexpr->len; ++i)
8740 buf = pack_hex_byte (buf, aexpr->buf[i]);
8747 remote_add_target_side_commands (struct gdbarch *gdbarch,
8748 struct bp_target_info *bp_tgt, char *buf)
8750 struct agent_expr *aexpr = NULL;
8753 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8756 buf += strlen (buf);
8758 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8759 buf += strlen (buf);
8761 /* Concatenate all the agent expressions that are commands into the
8764 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8767 sprintf (buf, "X%x,", aexpr->len);
8768 buf += strlen (buf);
8769 for (i = 0; i < aexpr->len; ++i)
8770 buf = pack_hex_byte (buf, aexpr->buf[i]);
8775 /* Insert a breakpoint. On targets that have software breakpoint
8776 support, we ask the remote target to do the work; on targets
8777 which don't, we insert a traditional memory breakpoint. */
8780 remote_insert_breakpoint (struct target_ops *ops,
8781 struct gdbarch *gdbarch,
8782 struct bp_target_info *bp_tgt)
8784 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8785 If it succeeds, then set the support to PACKET_ENABLE. If it
8786 fails, and the user has explicitly requested the Z support then
8787 report an error, otherwise, mark it disabled and go on. */
8789 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8791 CORE_ADDR addr = bp_tgt->reqstd_address;
8792 struct remote_state *rs;
8795 struct condition_list *cond = NULL;
8797 /* Make sure the remote is pointing at the right process, if
8799 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8800 set_general_process ();
8802 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8804 rs = get_remote_state ();
8806 endbuf = rs->buf + get_remote_packet_size ();
8811 addr = (ULONGEST) remote_address_masked (addr);
8812 p += hexnumstr (p, addr);
8813 xsnprintf (p, endbuf - p, ",%d", bpsize);
8815 if (remote_supports_cond_breakpoints (ops))
8816 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8818 if (remote_can_run_breakpoint_commands (ops))
8819 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8822 getpkt (&rs->buf, &rs->buf_size, 0);
8824 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8829 bp_tgt->placed_address = addr;
8830 bp_tgt->placed_size = bpsize;
8832 case PACKET_UNKNOWN:
8837 /* If this breakpoint has target-side commands but this stub doesn't
8838 support Z0 packets, throw error. */
8839 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8840 throw_error (NOT_SUPPORTED_ERROR, _("\
8841 Target doesn't support breakpoints that have target side commands."));
8843 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8847 remote_remove_breakpoint (struct target_ops *ops,
8848 struct gdbarch *gdbarch,
8849 struct bp_target_info *bp_tgt)
8851 CORE_ADDR addr = bp_tgt->placed_address;
8852 struct remote_state *rs = get_remote_state ();
8854 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8857 char *endbuf = rs->buf + get_remote_packet_size ();
8859 /* Make sure the remote is pointing at the right process, if
8861 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8862 set_general_process ();
8868 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8869 p += hexnumstr (p, addr);
8870 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8873 getpkt (&rs->buf, &rs->buf_size, 0);
8875 return (rs->buf[0] == 'E');
8878 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8881 static enum Z_packet_type
8882 watchpoint_to_Z_packet (int type)
8887 return Z_PACKET_WRITE_WP;
8890 return Z_PACKET_READ_WP;
8893 return Z_PACKET_ACCESS_WP;
8896 internal_error (__FILE__, __LINE__,
8897 _("hw_bp_to_z: bad watchpoint type %d"), type);
8902 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8903 enum target_hw_bp_type type, struct expression *cond)
8905 struct remote_state *rs = get_remote_state ();
8906 char *endbuf = rs->buf + get_remote_packet_size ();
8908 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8910 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8913 /* Make sure the remote is pointing at the right process, if
8915 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8916 set_general_process ();
8918 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8919 p = strchr (rs->buf, '\0');
8920 addr = remote_address_masked (addr);
8921 p += hexnumstr (p, (ULONGEST) addr);
8922 xsnprintf (p, endbuf - p, ",%x", len);
8925 getpkt (&rs->buf, &rs->buf_size, 0);
8927 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8931 case PACKET_UNKNOWN:
8936 internal_error (__FILE__, __LINE__,
8937 _("remote_insert_watchpoint: reached end of function"));
8941 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8942 CORE_ADDR start, int length)
8944 CORE_ADDR diff = remote_address_masked (addr - start);
8946 return diff < length;
8951 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8952 enum target_hw_bp_type type, struct expression *cond)
8954 struct remote_state *rs = get_remote_state ();
8955 char *endbuf = rs->buf + get_remote_packet_size ();
8957 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8959 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8962 /* Make sure the remote is pointing at the right process, if
8964 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8965 set_general_process ();
8967 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8968 p = strchr (rs->buf, '\0');
8969 addr = remote_address_masked (addr);
8970 p += hexnumstr (p, (ULONGEST) addr);
8971 xsnprintf (p, endbuf - p, ",%x", len);
8973 getpkt (&rs->buf, &rs->buf_size, 0);
8975 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8978 case PACKET_UNKNOWN:
8983 internal_error (__FILE__, __LINE__,
8984 _("remote_remove_watchpoint: reached end of function"));
8988 int remote_hw_watchpoint_limit = -1;
8989 int remote_hw_watchpoint_length_limit = -1;
8990 int remote_hw_breakpoint_limit = -1;
8993 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8994 CORE_ADDR addr, int len)
8996 if (remote_hw_watchpoint_length_limit == 0)
8998 else if (remote_hw_watchpoint_length_limit < 0)
9000 else if (len <= remote_hw_watchpoint_length_limit)
9007 remote_check_watch_resources (struct target_ops *self,
9008 enum bptype type, int cnt, int ot)
9010 if (type == bp_hardware_breakpoint)
9012 if (remote_hw_breakpoint_limit == 0)
9014 else if (remote_hw_breakpoint_limit < 0)
9016 else if (cnt <= remote_hw_breakpoint_limit)
9021 if (remote_hw_watchpoint_limit == 0)
9023 else if (remote_hw_watchpoint_limit < 0)
9027 else if (cnt <= remote_hw_watchpoint_limit)
9033 /* The to_stopped_by_sw_breakpoint method of target remote. */
9036 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9038 struct remote_state *rs = get_remote_state ();
9040 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9043 /* The to_supports_stopped_by_sw_breakpoint method of target
9047 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9049 struct remote_state *rs = get_remote_state ();
9051 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9054 /* The to_stopped_by_hw_breakpoint method of target remote. */
9057 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9059 struct remote_state *rs = get_remote_state ();
9061 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9064 /* The to_supports_stopped_by_hw_breakpoint method of target
9068 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9070 struct remote_state *rs = get_remote_state ();
9072 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9076 remote_stopped_by_watchpoint (struct target_ops *ops)
9078 struct remote_state *rs = get_remote_state ();
9080 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
9084 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9086 struct remote_state *rs = get_remote_state ();
9089 if (remote_stopped_by_watchpoint (target))
9091 *addr_p = rs->remote_watch_data_address;
9100 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9101 struct bp_target_info *bp_tgt)
9103 CORE_ADDR addr = bp_tgt->reqstd_address;
9104 struct remote_state *rs;
9109 /* The length field should be set to the size of a breakpoint
9110 instruction, even though we aren't inserting one ourselves. */
9112 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9114 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9117 /* Make sure the remote is pointing at the right process, if
9119 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9120 set_general_process ();
9122 rs = get_remote_state ();
9124 endbuf = rs->buf + get_remote_packet_size ();
9130 addr = remote_address_masked (addr);
9131 p += hexnumstr (p, (ULONGEST) addr);
9132 xsnprintf (p, endbuf - p, ",%x", bpsize);
9134 if (remote_supports_cond_breakpoints (self))
9135 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9137 if (remote_can_run_breakpoint_commands (self))
9138 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9141 getpkt (&rs->buf, &rs->buf_size, 0);
9143 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9146 if (rs->buf[1] == '.')
9148 message = strchr (rs->buf + 2, '.');
9150 error (_("Remote failure reply: %s"), message + 1);
9153 case PACKET_UNKNOWN:
9156 bp_tgt->placed_address = addr;
9157 bp_tgt->placed_size = bpsize;
9160 internal_error (__FILE__, __LINE__,
9161 _("remote_insert_hw_breakpoint: reached end of function"));
9166 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9167 struct bp_target_info *bp_tgt)
9170 struct remote_state *rs = get_remote_state ();
9172 char *endbuf = rs->buf + get_remote_packet_size ();
9174 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9177 /* Make sure the remote is pointing at the right process, if
9179 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9180 set_general_process ();
9186 addr = remote_address_masked (bp_tgt->placed_address);
9187 p += hexnumstr (p, (ULONGEST) addr);
9188 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9191 getpkt (&rs->buf, &rs->buf_size, 0);
9193 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9196 case PACKET_UNKNOWN:
9201 internal_error (__FILE__, __LINE__,
9202 _("remote_remove_hw_breakpoint: reached end of function"));
9205 /* Verify memory using the "qCRC:" request. */
9208 remote_verify_memory (struct target_ops *ops,
9209 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9211 struct remote_state *rs = get_remote_state ();
9212 unsigned long host_crc, target_crc;
9215 /* It doesn't make sense to use qCRC if the remote target is
9216 connected but not running. */
9217 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9219 enum packet_result result;
9221 /* Make sure the remote is pointing at the right process. */
9222 set_general_process ();
9224 /* FIXME: assumes lma can fit into long. */
9225 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9226 (long) lma, (long) size);
9229 /* Be clever; compute the host_crc before waiting for target
9231 host_crc = xcrc32 (data, size, 0xffffffff);
9233 getpkt (&rs->buf, &rs->buf_size, 0);
9235 result = packet_ok (rs->buf,
9236 &remote_protocol_packets[PACKET_qCRC]);
9237 if (result == PACKET_ERROR)
9239 else if (result == PACKET_OK)
9241 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9242 target_crc = target_crc * 16 + fromhex (*tmp);
9244 return (host_crc == target_crc);
9248 return simple_verify_memory (ops, data, lma, size);
9251 /* compare-sections command
9253 With no arguments, compares each loadable section in the exec bfd
9254 with the same memory range on the target, and reports mismatches.
9255 Useful for verifying the image on the target against the exec file. */
9258 compare_sections_command (char *args, int from_tty)
9261 struct cleanup *old_chain;
9263 const char *sectname;
9272 error (_("command cannot be used without an exec file"));
9274 /* Make sure the remote is pointing at the right process. */
9275 set_general_process ();
9277 if (args != NULL && strcmp (args, "-r") == 0)
9283 for (s = exec_bfd->sections; s; s = s->next)
9285 if (!(s->flags & SEC_LOAD))
9286 continue; /* Skip non-loadable section. */
9288 if (read_only && (s->flags & SEC_READONLY) == 0)
9289 continue; /* Skip writeable sections */
9291 size = bfd_get_section_size (s);
9293 continue; /* Skip zero-length section. */
9295 sectname = bfd_get_section_name (exec_bfd, s);
9296 if (args && strcmp (args, sectname) != 0)
9297 continue; /* Not the section selected by user. */
9299 matched = 1; /* Do this section. */
9302 sectdata = xmalloc (size);
9303 old_chain = make_cleanup (xfree, sectdata);
9304 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9306 res = target_verify_memory (sectdata, lma, size);
9309 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9310 paddress (target_gdbarch (), lma),
9311 paddress (target_gdbarch (), lma + size));
9313 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9314 paddress (target_gdbarch (), lma),
9315 paddress (target_gdbarch (), lma + size));
9317 printf_filtered ("matched.\n");
9320 printf_filtered ("MIS-MATCHED!\n");
9324 do_cleanups (old_chain);
9327 warning (_("One or more sections of the target image does not match\n\
9328 the loaded file\n"));
9329 if (args && !matched)
9330 printf_filtered (_("No loaded section named '%s'.\n"), args);
9333 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9334 into remote target. The number of bytes written to the remote
9335 target is returned, or -1 for error. */
9337 static enum target_xfer_status
9338 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9339 const char *annex, const gdb_byte *writebuf,
9340 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9341 struct packet_config *packet)
9345 struct remote_state *rs = get_remote_state ();
9346 int max_size = get_memory_write_packet_size ();
9348 if (packet->support == PACKET_DISABLE)
9349 return TARGET_XFER_E_IO;
9351 /* Insert header. */
9352 i = snprintf (rs->buf, max_size,
9353 "qXfer:%s:write:%s:%s:",
9354 object_name, annex ? annex : "",
9355 phex_nz (offset, sizeof offset));
9356 max_size -= (i + 1);
9358 /* Escape as much data as fits into rs->buf. */
9359 buf_len = remote_escape_output
9360 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9362 if (putpkt_binary (rs->buf, i + buf_len) < 0
9363 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9364 || packet_ok (rs->buf, packet) != PACKET_OK)
9365 return TARGET_XFER_E_IO;
9367 unpack_varlen_hex (rs->buf, &n);
9370 return TARGET_XFER_OK;
9373 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9374 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9375 number of bytes read is returned, or 0 for EOF, or -1 for error.
9376 The number of bytes read may be less than LEN without indicating an
9377 EOF. PACKET is checked and updated to indicate whether the remote
9378 target supports this object. */
9380 static enum target_xfer_status
9381 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9383 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9384 ULONGEST *xfered_len,
9385 struct packet_config *packet)
9387 struct remote_state *rs = get_remote_state ();
9388 LONGEST i, n, packet_len;
9390 if (packet->support == PACKET_DISABLE)
9391 return TARGET_XFER_E_IO;
9393 /* Check whether we've cached an end-of-object packet that matches
9395 if (rs->finished_object)
9397 if (strcmp (object_name, rs->finished_object) == 0
9398 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9399 && offset == rs->finished_offset)
9400 return TARGET_XFER_EOF;
9403 /* Otherwise, we're now reading something different. Discard
9405 xfree (rs->finished_object);
9406 xfree (rs->finished_annex);
9407 rs->finished_object = NULL;
9408 rs->finished_annex = NULL;
9411 /* Request only enough to fit in a single packet. The actual data
9412 may not, since we don't know how much of it will need to be escaped;
9413 the target is free to respond with slightly less data. We subtract
9414 five to account for the response type and the protocol frame. */
9415 n = min (get_remote_packet_size () - 5, len);
9416 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9417 object_name, annex ? annex : "",
9418 phex_nz (offset, sizeof offset),
9419 phex_nz (n, sizeof n));
9420 i = putpkt (rs->buf);
9422 return TARGET_XFER_E_IO;
9425 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9426 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9427 return TARGET_XFER_E_IO;
9429 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9430 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9432 /* 'm' means there is (or at least might be) more data after this
9433 batch. That does not make sense unless there's at least one byte
9434 of data in this reply. */
9435 if (rs->buf[0] == 'm' && packet_len == 1)
9436 error (_("Remote qXfer reply contained no data."));
9438 /* Got some data. */
9439 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9440 packet_len - 1, readbuf, n);
9442 /* 'l' is an EOF marker, possibly including a final block of data,
9443 or possibly empty. If we have the final block of a non-empty
9444 object, record this fact to bypass a subsequent partial read. */
9445 if (rs->buf[0] == 'l' && offset + i > 0)
9447 rs->finished_object = xstrdup (object_name);
9448 rs->finished_annex = xstrdup (annex ? annex : "");
9449 rs->finished_offset = offset + i;
9453 return TARGET_XFER_EOF;
9457 return TARGET_XFER_OK;
9461 static enum target_xfer_status
9462 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9463 const char *annex, gdb_byte *readbuf,
9464 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9465 ULONGEST *xfered_len)
9467 struct remote_state *rs;
9471 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9473 set_remote_traceframe ();
9474 set_general_thread (inferior_ptid);
9476 rs = get_remote_state ();
9478 /* Handle memory using the standard memory routines. */
9479 if (object == TARGET_OBJECT_MEMORY)
9481 /* If the remote target is connected but not running, we should
9482 pass this request down to a lower stratum (e.g. the executable
9484 if (!target_has_execution)
9485 return TARGET_XFER_EOF;
9487 if (writebuf != NULL)
9488 return remote_write_bytes (offset, writebuf, len, unit_size,
9491 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9495 /* Handle SPU memory using qxfer packets. */
9496 if (object == TARGET_OBJECT_SPU)
9499 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9500 xfered_len, &remote_protocol_packets
9501 [PACKET_qXfer_spu_read]);
9503 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9504 xfered_len, &remote_protocol_packets
9505 [PACKET_qXfer_spu_write]);
9508 /* Handle extra signal info using qxfer packets. */
9509 if (object == TARGET_OBJECT_SIGNAL_INFO)
9512 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9513 xfered_len, &remote_protocol_packets
9514 [PACKET_qXfer_siginfo_read]);
9516 return remote_write_qxfer (ops, "siginfo", annex,
9517 writebuf, offset, len, xfered_len,
9518 &remote_protocol_packets
9519 [PACKET_qXfer_siginfo_write]);
9522 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9525 return remote_read_qxfer (ops, "statictrace", annex,
9526 readbuf, offset, len, xfered_len,
9527 &remote_protocol_packets
9528 [PACKET_qXfer_statictrace_read]);
9530 return TARGET_XFER_E_IO;
9533 /* Only handle flash writes. */
9534 if (writebuf != NULL)
9540 case TARGET_OBJECT_FLASH:
9541 return remote_flash_write (ops, offset, len, xfered_len,
9545 return TARGET_XFER_E_IO;
9549 /* Map pre-existing objects onto letters. DO NOT do this for new
9550 objects!!! Instead specify new query packets. */
9553 case TARGET_OBJECT_AVR:
9557 case TARGET_OBJECT_AUXV:
9558 gdb_assert (annex == NULL);
9559 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9561 &remote_protocol_packets[PACKET_qXfer_auxv]);
9563 case TARGET_OBJECT_AVAILABLE_FEATURES:
9564 return remote_read_qxfer
9565 (ops, "features", annex, readbuf, offset, len, xfered_len,
9566 &remote_protocol_packets[PACKET_qXfer_features]);
9568 case TARGET_OBJECT_LIBRARIES:
9569 return remote_read_qxfer
9570 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9571 &remote_protocol_packets[PACKET_qXfer_libraries]);
9573 case TARGET_OBJECT_LIBRARIES_SVR4:
9574 return remote_read_qxfer
9575 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9576 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9578 case TARGET_OBJECT_MEMORY_MAP:
9579 gdb_assert (annex == NULL);
9580 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9582 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9584 case TARGET_OBJECT_OSDATA:
9585 /* Should only get here if we're connected. */
9586 gdb_assert (rs->remote_desc);
9587 return remote_read_qxfer
9588 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9589 &remote_protocol_packets[PACKET_qXfer_osdata]);
9591 case TARGET_OBJECT_THREADS:
9592 gdb_assert (annex == NULL);
9593 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9595 &remote_protocol_packets[PACKET_qXfer_threads]);
9597 case TARGET_OBJECT_TRACEFRAME_INFO:
9598 gdb_assert (annex == NULL);
9599 return remote_read_qxfer
9600 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9601 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9603 case TARGET_OBJECT_FDPIC:
9604 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9606 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9608 case TARGET_OBJECT_OPENVMS_UIB:
9609 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9611 &remote_protocol_packets[PACKET_qXfer_uib]);
9613 case TARGET_OBJECT_BTRACE:
9614 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9616 &remote_protocol_packets[PACKET_qXfer_btrace]);
9618 case TARGET_OBJECT_BTRACE_CONF:
9619 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9621 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9623 case TARGET_OBJECT_EXEC_FILE:
9624 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9626 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9629 return TARGET_XFER_E_IO;
9632 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9633 large enough let the caller deal with it. */
9634 if (len < get_remote_packet_size ())
9635 return TARGET_XFER_E_IO;
9636 len = get_remote_packet_size ();
9638 /* Except for querying the minimum buffer size, target must be open. */
9639 if (!rs->remote_desc)
9640 error (_("remote query is only available after target open"));
9642 gdb_assert (annex != NULL);
9643 gdb_assert (readbuf != NULL);
9649 /* We used one buffer char for the remote protocol q command and
9650 another for the query type. As the remote protocol encapsulation
9651 uses 4 chars plus one extra in case we are debugging
9652 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9655 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9657 /* Bad caller may have sent forbidden characters. */
9658 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9663 gdb_assert (annex[i] == '\0');
9665 i = putpkt (rs->buf);
9667 return TARGET_XFER_E_IO;
9669 getpkt (&rs->buf, &rs->buf_size, 0);
9670 strcpy ((char *) readbuf, rs->buf);
9672 *xfered_len = strlen ((char *) readbuf);
9673 return TARGET_XFER_OK;
9677 remote_search_memory (struct target_ops* ops,
9678 CORE_ADDR start_addr, ULONGEST search_space_len,
9679 const gdb_byte *pattern, ULONGEST pattern_len,
9680 CORE_ADDR *found_addrp)
9682 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9683 struct remote_state *rs = get_remote_state ();
9684 int max_size = get_memory_write_packet_size ();
9685 struct packet_config *packet =
9686 &remote_protocol_packets[PACKET_qSearch_memory];
9687 /* Number of packet bytes used to encode the pattern;
9688 this could be more than PATTERN_LEN due to escape characters. */
9689 int escaped_pattern_len;
9690 /* Amount of pattern that was encodable in the packet. */
9691 int used_pattern_len;
9694 ULONGEST found_addr;
9696 /* Don't go to the target if we don't have to.
9697 This is done before checking packet->support to avoid the possibility that
9698 a success for this edge case means the facility works in general. */
9699 if (pattern_len > search_space_len)
9701 if (pattern_len == 0)
9703 *found_addrp = start_addr;
9707 /* If we already know the packet isn't supported, fall back to the simple
9708 way of searching memory. */
9710 if (packet_config_support (packet) == PACKET_DISABLE)
9712 /* Target doesn't provided special support, fall back and use the
9713 standard support (copy memory and do the search here). */
9714 return simple_search_memory (ops, start_addr, search_space_len,
9715 pattern, pattern_len, found_addrp);
9718 /* Make sure the remote is pointing at the right process. */
9719 set_general_process ();
9721 /* Insert header. */
9722 i = snprintf (rs->buf, max_size,
9723 "qSearch:memory:%s;%s;",
9724 phex_nz (start_addr, addr_size),
9725 phex_nz (search_space_len, sizeof (search_space_len)));
9726 max_size -= (i + 1);
9728 /* Escape as much data as fits into rs->buf. */
9729 escaped_pattern_len =
9730 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
9731 &used_pattern_len, max_size);
9733 /* Bail if the pattern is too large. */
9734 if (used_pattern_len != pattern_len)
9735 error (_("Pattern is too large to transmit to remote target."));
9737 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9738 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9739 || packet_ok (rs->buf, packet) != PACKET_OK)
9741 /* The request may not have worked because the command is not
9742 supported. If so, fall back to the simple way. */
9743 if (packet->support == PACKET_DISABLE)
9745 return simple_search_memory (ops, start_addr, search_space_len,
9746 pattern, pattern_len, found_addrp);
9751 if (rs->buf[0] == '0')
9753 else if (rs->buf[0] == '1')
9756 if (rs->buf[1] != ',')
9757 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9758 unpack_varlen_hex (rs->buf + 2, &found_addr);
9759 *found_addrp = found_addr;
9762 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9768 remote_rcmd (struct target_ops *self, const char *command,
9769 struct ui_file *outbuf)
9771 struct remote_state *rs = get_remote_state ();
9774 if (!rs->remote_desc)
9775 error (_("remote rcmd is only available after target open"));
9777 /* Send a NULL command across as an empty command. */
9778 if (command == NULL)
9781 /* The query prefix. */
9782 strcpy (rs->buf, "qRcmd,");
9783 p = strchr (rs->buf, '\0');
9785 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9786 > get_remote_packet_size ())
9787 error (_("\"monitor\" command ``%s'' is too long."), command);
9789 /* Encode the actual command. */
9790 bin2hex ((const gdb_byte *) command, p, strlen (command));
9792 if (putpkt (rs->buf) < 0)
9793 error (_("Communication problem with target."));
9795 /* get/display the response */
9800 /* XXX - see also remote_get_noisy_reply(). */
9801 QUIT; /* Allow user to bail out with ^C. */
9803 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9805 /* Timeout. Continue to (try to) read responses.
9806 This is better than stopping with an error, assuming the stub
9807 is still executing the (long) monitor command.
9808 If needed, the user can interrupt gdb using C-c, obtaining
9809 an effect similar to stop on timeout. */
9814 error (_("Target does not support this command."));
9815 if (buf[0] == 'O' && buf[1] != 'K')
9817 remote_console_output (buf + 1); /* 'O' message from stub. */
9820 if (strcmp (buf, "OK") == 0)
9822 if (strlen (buf) == 3 && buf[0] == 'E'
9823 && isdigit (buf[1]) && isdigit (buf[2]))
9825 error (_("Protocol error with Rcmd"));
9827 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9829 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9831 fputc_unfiltered (c, outbuf);
9837 static VEC(mem_region_s) *
9838 remote_memory_map (struct target_ops *ops)
9840 VEC(mem_region_s) *result = NULL;
9841 char *text = target_read_stralloc (¤t_target,
9842 TARGET_OBJECT_MEMORY_MAP, NULL);
9846 struct cleanup *back_to = make_cleanup (xfree, text);
9848 result = parse_memory_map (text);
9849 do_cleanups (back_to);
9856 packet_command (char *args, int from_tty)
9858 struct remote_state *rs = get_remote_state ();
9860 if (!rs->remote_desc)
9861 error (_("command can only be used with remote target"));
9864 error (_("remote-packet command requires packet text as argument"));
9866 puts_filtered ("sending: ");
9867 print_packet (args);
9868 puts_filtered ("\n");
9871 getpkt (&rs->buf, &rs->buf_size, 0);
9872 puts_filtered ("received: ");
9873 print_packet (rs->buf);
9874 puts_filtered ("\n");
9878 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9880 static void display_thread_info (struct gdb_ext_thread_info *info);
9882 static void threadset_test_cmd (char *cmd, int tty);
9884 static void threadalive_test (char *cmd, int tty);
9886 static void threadlist_test_cmd (char *cmd, int tty);
9888 int get_and_display_threadinfo (threadref *ref);
9890 static void threadinfo_test_cmd (char *cmd, int tty);
9892 static int thread_display_step (threadref *ref, void *context);
9894 static void threadlist_update_test_cmd (char *cmd, int tty);
9896 static void init_remote_threadtests (void);
9898 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9901 threadset_test_cmd (char *cmd, int tty)
9903 int sample_thread = SAMPLE_THREAD;
9905 printf_filtered (_("Remote threadset test\n"));
9906 set_general_thread (sample_thread);
9911 threadalive_test (char *cmd, int tty)
9913 int sample_thread = SAMPLE_THREAD;
9914 int pid = ptid_get_pid (inferior_ptid);
9915 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9917 if (remote_thread_alive (ptid))
9918 printf_filtered ("PASS: Thread alive test\n");
9920 printf_filtered ("FAIL: Thread alive test\n");
9923 void output_threadid (char *title, threadref *ref);
9926 output_threadid (char *title, threadref *ref)
9930 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9932 printf_filtered ("%s %s\n", title, (&hexid[0]));
9936 threadlist_test_cmd (char *cmd, int tty)
9939 threadref nextthread;
9940 int done, result_count;
9941 threadref threadlist[3];
9943 printf_filtered ("Remote Threadlist test\n");
9944 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9945 &result_count, &threadlist[0]))
9946 printf_filtered ("FAIL: threadlist test\n");
9949 threadref *scan = threadlist;
9950 threadref *limit = scan + result_count;
9952 while (scan < limit)
9953 output_threadid (" thread ", scan++);
9958 display_thread_info (struct gdb_ext_thread_info *info)
9960 output_threadid ("Threadid: ", &info->threadid);
9961 printf_filtered ("Name: %s\n ", info->shortname);
9962 printf_filtered ("State: %s\n", info->display);
9963 printf_filtered ("other: %s\n\n", info->more_display);
9967 get_and_display_threadinfo (threadref *ref)
9971 struct gdb_ext_thread_info threadinfo;
9973 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9974 | TAG_MOREDISPLAY | TAG_DISPLAY;
9975 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9976 display_thread_info (&threadinfo);
9981 threadinfo_test_cmd (char *cmd, int tty)
9983 int athread = SAMPLE_THREAD;
9987 int_to_threadref (&thread, athread);
9988 printf_filtered ("Remote Threadinfo test\n");
9989 if (!get_and_display_threadinfo (&thread))
9990 printf_filtered ("FAIL cannot get thread info\n");
9994 thread_display_step (threadref *ref, void *context)
9996 /* output_threadid(" threadstep ",ref); *//* simple test */
9997 return get_and_display_threadinfo (ref);
10001 threadlist_update_test_cmd (char *cmd, int tty)
10003 printf_filtered ("Remote Threadlist update test\n");
10004 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10008 init_remote_threadtests (void)
10010 add_com ("tlist", class_obscure, threadlist_test_cmd,
10011 _("Fetch and print the remote list of "
10012 "thread identifiers, one pkt only"));
10013 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10014 _("Fetch and display info about one thread"));
10015 add_com ("tset", class_obscure, threadset_test_cmd,
10016 _("Test setting to a different thread"));
10017 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10018 _("Iterate through updating all remote thread info"));
10019 add_com ("talive", class_obscure, threadalive_test,
10020 _(" Remote thread alive test "));
10025 /* Convert a thread ID to a string. Returns the string in a static
10029 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10031 static char buf[64];
10032 struct remote_state *rs = get_remote_state ();
10034 if (ptid_equal (ptid, null_ptid))
10035 return normal_pid_to_str (ptid);
10036 else if (ptid_is_pid (ptid))
10038 /* Printing an inferior target id. */
10040 /* When multi-process extensions are off, there's no way in the
10041 remote protocol to know the remote process id, if there's any
10042 at all. There's one exception --- when we're connected with
10043 target extended-remote, and we manually attached to a process
10044 with "attach PID". We don't record anywhere a flag that
10045 allows us to distinguish that case from the case of
10046 connecting with extended-remote and the stub already being
10047 attached to a process, and reporting yes to qAttached, hence
10048 no smart special casing here. */
10049 if (!remote_multi_process_p (rs))
10051 xsnprintf (buf, sizeof buf, "Remote target");
10055 return normal_pid_to_str (ptid);
10059 if (ptid_equal (magic_null_ptid, ptid))
10060 xsnprintf (buf, sizeof buf, "Thread <main>");
10061 else if (rs->extended && remote_multi_process_p (rs))
10062 if (ptid_get_lwp (ptid) == 0)
10063 return normal_pid_to_str (ptid);
10065 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10066 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10068 xsnprintf (buf, sizeof buf, "Thread %ld",
10069 ptid_get_lwp (ptid));
10074 /* Get the address of the thread local variable in OBJFILE which is
10075 stored at OFFSET within the thread local storage for thread PTID. */
10078 remote_get_thread_local_address (struct target_ops *ops,
10079 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10081 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10083 struct remote_state *rs = get_remote_state ();
10085 char *endp = rs->buf + get_remote_packet_size ();
10086 enum packet_result result;
10088 strcpy (p, "qGetTLSAddr:");
10090 p = write_ptid (p, endp, ptid);
10092 p += hexnumstr (p, offset);
10094 p += hexnumstr (p, lm);
10098 getpkt (&rs->buf, &rs->buf_size, 0);
10099 result = packet_ok (rs->buf,
10100 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10101 if (result == PACKET_OK)
10105 unpack_varlen_hex (rs->buf, &result);
10108 else if (result == PACKET_UNKNOWN)
10109 throw_error (TLS_GENERIC_ERROR,
10110 _("Remote target doesn't support qGetTLSAddr packet"));
10112 throw_error (TLS_GENERIC_ERROR,
10113 _("Remote target failed to process qGetTLSAddr request"));
10116 throw_error (TLS_GENERIC_ERROR,
10117 _("TLS not supported or disabled on this target"));
10122 /* Provide thread local base, i.e. Thread Information Block address.
10123 Returns 1 if ptid is found and thread_local_base is non zero. */
10126 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10128 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10130 struct remote_state *rs = get_remote_state ();
10132 char *endp = rs->buf + get_remote_packet_size ();
10133 enum packet_result result;
10135 strcpy (p, "qGetTIBAddr:");
10137 p = write_ptid (p, endp, ptid);
10141 getpkt (&rs->buf, &rs->buf_size, 0);
10142 result = packet_ok (rs->buf,
10143 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10144 if (result == PACKET_OK)
10148 unpack_varlen_hex (rs->buf, &result);
10150 *addr = (CORE_ADDR) result;
10153 else if (result == PACKET_UNKNOWN)
10154 error (_("Remote target doesn't support qGetTIBAddr packet"));
10156 error (_("Remote target failed to process qGetTIBAddr request"));
10159 error (_("qGetTIBAddr not supported or disabled on this target"));
10164 /* Support for inferring a target description based on the current
10165 architecture and the size of a 'g' packet. While the 'g' packet
10166 can have any size (since optional registers can be left off the
10167 end), some sizes are easily recognizable given knowledge of the
10168 approximate architecture. */
10170 struct remote_g_packet_guess
10173 const struct target_desc *tdesc;
10175 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10176 DEF_VEC_O(remote_g_packet_guess_s);
10178 struct remote_g_packet_data
10180 VEC(remote_g_packet_guess_s) *guesses;
10183 static struct gdbarch_data *remote_g_packet_data_handle;
10186 remote_g_packet_data_init (struct obstack *obstack)
10188 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10192 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10193 const struct target_desc *tdesc)
10195 struct remote_g_packet_data *data
10196 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10197 struct remote_g_packet_guess new_guess, *guess;
10200 gdb_assert (tdesc != NULL);
10203 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10205 if (guess->bytes == bytes)
10206 internal_error (__FILE__, __LINE__,
10207 _("Duplicate g packet description added for size %d"),
10210 new_guess.bytes = bytes;
10211 new_guess.tdesc = tdesc;
10212 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10215 /* Return 1 if remote_read_description would do anything on this target
10216 and architecture, 0 otherwise. */
10219 remote_read_description_p (struct target_ops *target)
10221 struct remote_g_packet_data *data
10222 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10224 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10230 static const struct target_desc *
10231 remote_read_description (struct target_ops *target)
10233 struct remote_g_packet_data *data
10234 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
10236 /* Do not try this during initial connection, when we do not know
10237 whether there is a running but stopped thread. */
10238 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10239 return target->beneath->to_read_description (target->beneath);
10241 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10243 struct remote_g_packet_guess *guess;
10245 int bytes = send_g_packet ();
10248 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10250 if (guess->bytes == bytes)
10251 return guess->tdesc;
10253 /* We discard the g packet. A minor optimization would be to
10254 hold on to it, and fill the register cache once we have selected
10255 an architecture, but it's too tricky to do safely. */
10258 return target->beneath->to_read_description (target->beneath);
10261 /* Remote file transfer support. This is host-initiated I/O, not
10262 target-initiated; for target-initiated, see remote-fileio.c. */
10264 /* If *LEFT is at least the length of STRING, copy STRING to
10265 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10266 decrease *LEFT. Otherwise raise an error. */
10269 remote_buffer_add_string (char **buffer, int *left, char *string)
10271 int len = strlen (string);
10274 error (_("Packet too long for target."));
10276 memcpy (*buffer, string, len);
10280 /* NUL-terminate the buffer as a convenience, if there is
10286 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10287 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10288 decrease *LEFT. Otherwise raise an error. */
10291 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10294 if (2 * len > *left)
10295 error (_("Packet too long for target."));
10297 bin2hex (bytes, *buffer, len);
10298 *buffer += 2 * len;
10301 /* NUL-terminate the buffer as a convenience, if there is
10307 /* If *LEFT is large enough, convert VALUE to hex and add it to
10308 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10309 decrease *LEFT. Otherwise raise an error. */
10312 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10314 int len = hexnumlen (value);
10317 error (_("Packet too long for target."));
10319 hexnumstr (*buffer, value);
10323 /* NUL-terminate the buffer as a convenience, if there is
10329 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10330 value, *REMOTE_ERRNO to the remote error number or zero if none
10331 was included, and *ATTACHMENT to point to the start of the annex
10332 if any. The length of the packet isn't needed here; there may
10333 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10335 Return 0 if the packet could be parsed, -1 if it could not. If
10336 -1 is returned, the other variables may not be initialized. */
10339 remote_hostio_parse_result (char *buffer, int *retcode,
10340 int *remote_errno, char **attachment)
10345 *attachment = NULL;
10347 if (buffer[0] != 'F')
10351 *retcode = strtol (&buffer[1], &p, 16);
10352 if (errno != 0 || p == &buffer[1])
10355 /* Check for ",errno". */
10359 *remote_errno = strtol (p + 1, &p2, 16);
10360 if (errno != 0 || p + 1 == p2)
10365 /* Check for ";attachment". If there is no attachment, the
10366 packet should end here. */
10369 *attachment = p + 1;
10372 else if (*p == '\0')
10378 /* Send a prepared I/O packet to the target and read its response.
10379 The prepared packet is in the global RS->BUF before this function
10380 is called, and the answer is there when we return.
10382 COMMAND_BYTES is the length of the request to send, which may include
10383 binary data. WHICH_PACKET is the packet configuration to check
10384 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10385 is set to the error number and -1 is returned. Otherwise the value
10386 returned by the function is returned.
10388 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10389 attachment is expected; an error will be reported if there's a
10390 mismatch. If one is found, *ATTACHMENT will be set to point into
10391 the packet buffer and *ATTACHMENT_LEN will be set to the
10392 attachment's length. */
10395 remote_hostio_send_command (int command_bytes, int which_packet,
10396 int *remote_errno, char **attachment,
10397 int *attachment_len)
10399 struct remote_state *rs = get_remote_state ();
10400 int ret, bytes_read;
10401 char *attachment_tmp;
10403 if (!rs->remote_desc
10404 || packet_support (which_packet) == PACKET_DISABLE)
10406 *remote_errno = FILEIO_ENOSYS;
10410 putpkt_binary (rs->buf, command_bytes);
10411 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10413 /* If it timed out, something is wrong. Don't try to parse the
10415 if (bytes_read < 0)
10417 *remote_errno = FILEIO_EINVAL;
10421 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10424 *remote_errno = FILEIO_EINVAL;
10426 case PACKET_UNKNOWN:
10427 *remote_errno = FILEIO_ENOSYS;
10433 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10436 *remote_errno = FILEIO_EINVAL;
10440 /* Make sure we saw an attachment if and only if we expected one. */
10441 if ((attachment_tmp == NULL && attachment != NULL)
10442 || (attachment_tmp != NULL && attachment == NULL))
10444 *remote_errno = FILEIO_EINVAL;
10448 /* If an attachment was found, it must point into the packet buffer;
10449 work out how many bytes there were. */
10450 if (attachment_tmp != NULL)
10452 *attachment = attachment_tmp;
10453 *attachment_len = bytes_read - (*attachment - rs->buf);
10459 /* Invalidate the readahead cache. */
10462 readahead_cache_invalidate (void)
10464 struct remote_state *rs = get_remote_state ();
10466 rs->readahead_cache.fd = -1;
10469 /* Invalidate the readahead cache if it is holding data for FD. */
10472 readahead_cache_invalidate_fd (int fd)
10474 struct remote_state *rs = get_remote_state ();
10476 if (rs->readahead_cache.fd == fd)
10477 rs->readahead_cache.fd = -1;
10480 /* Set the filesystem remote_hostio functions that take FILENAME
10481 arguments will use. Return 0 on success, or -1 if an error
10482 occurs (and set *REMOTE_ERRNO). */
10485 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10487 struct remote_state *rs = get_remote_state ();
10488 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10490 int left = get_remote_packet_size () - 1;
10494 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10497 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10500 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10502 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10503 remote_buffer_add_string (&p, &left, arg);
10505 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10506 remote_errno, NULL, NULL);
10508 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10512 rs->fs_pid = required_pid;
10517 /* Implementation of to_fileio_open. */
10520 remote_hostio_open (struct target_ops *self,
10521 struct inferior *inf, const char *filename,
10522 int flags, int mode, int warn_if_slow,
10525 struct remote_state *rs = get_remote_state ();
10527 int left = get_remote_packet_size () - 1;
10531 static int warning_issued = 0;
10533 printf_unfiltered (_("Reading %s from remote target...\n"),
10536 if (!warning_issued)
10538 warning (_("File transfers from remote targets can be slow."
10539 " Use \"set sysroot\" to access files locally"
10541 warning_issued = 1;
10545 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10548 remote_buffer_add_string (&p, &left, "vFile:open:");
10550 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10551 strlen (filename));
10552 remote_buffer_add_string (&p, &left, ",");
10554 remote_buffer_add_int (&p, &left, flags);
10555 remote_buffer_add_string (&p, &left, ",");
10557 remote_buffer_add_int (&p, &left, mode);
10559 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10560 remote_errno, NULL, NULL);
10563 /* Implementation of to_fileio_pwrite. */
10566 remote_hostio_pwrite (struct target_ops *self,
10567 int fd, const gdb_byte *write_buf, int len,
10568 ULONGEST offset, int *remote_errno)
10570 struct remote_state *rs = get_remote_state ();
10572 int left = get_remote_packet_size ();
10575 readahead_cache_invalidate_fd (fd);
10577 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10579 remote_buffer_add_int (&p, &left, fd);
10580 remote_buffer_add_string (&p, &left, ",");
10582 remote_buffer_add_int (&p, &left, offset);
10583 remote_buffer_add_string (&p, &left, ",");
10585 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10586 get_remote_packet_size () - (p - rs->buf));
10588 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10589 remote_errno, NULL, NULL);
10592 /* Helper for the implementation of to_fileio_pread. Read the file
10593 from the remote side with vFile:pread. */
10596 remote_hostio_pread_vFile (struct target_ops *self,
10597 int fd, gdb_byte *read_buf, int len,
10598 ULONGEST offset, int *remote_errno)
10600 struct remote_state *rs = get_remote_state ();
10603 int left = get_remote_packet_size ();
10604 int ret, attachment_len;
10607 remote_buffer_add_string (&p, &left, "vFile:pread:");
10609 remote_buffer_add_int (&p, &left, fd);
10610 remote_buffer_add_string (&p, &left, ",");
10612 remote_buffer_add_int (&p, &left, len);
10613 remote_buffer_add_string (&p, &left, ",");
10615 remote_buffer_add_int (&p, &left, offset);
10617 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10618 remote_errno, &attachment,
10624 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10626 if (read_len != ret)
10627 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10632 /* Serve pread from the readahead cache. Returns number of bytes
10633 read, or 0 if the request can't be served from the cache. */
10636 remote_hostio_pread_from_cache (struct remote_state *rs,
10637 int fd, gdb_byte *read_buf, size_t len,
10640 struct readahead_cache *cache = &rs->readahead_cache;
10642 if (cache->fd == fd
10643 && cache->offset <= offset
10644 && offset < cache->offset + cache->bufsize)
10646 ULONGEST max = cache->offset + cache->bufsize;
10648 if (offset + len > max)
10649 len = max - offset;
10651 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10658 /* Implementation of to_fileio_pread. */
10661 remote_hostio_pread (struct target_ops *self,
10662 int fd, gdb_byte *read_buf, int len,
10663 ULONGEST offset, int *remote_errno)
10666 struct remote_state *rs = get_remote_state ();
10667 struct readahead_cache *cache = &rs->readahead_cache;
10669 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10672 cache->hit_count++;
10675 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10676 pulongest (cache->hit_count));
10680 cache->miss_count++;
10682 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10683 pulongest (cache->miss_count));
10686 cache->offset = offset;
10687 cache->bufsize = get_remote_packet_size ();
10688 cache->buf = xrealloc (cache->buf, cache->bufsize);
10690 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10691 cache->offset, remote_errno);
10694 readahead_cache_invalidate_fd (fd);
10698 cache->bufsize = ret;
10699 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10702 /* Implementation of to_fileio_close. */
10705 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
10707 struct remote_state *rs = get_remote_state ();
10709 int left = get_remote_packet_size () - 1;
10711 readahead_cache_invalidate_fd (fd);
10713 remote_buffer_add_string (&p, &left, "vFile:close:");
10715 remote_buffer_add_int (&p, &left, fd);
10717 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10718 remote_errno, NULL, NULL);
10721 /* Implementation of to_fileio_unlink. */
10724 remote_hostio_unlink (struct target_ops *self,
10725 struct inferior *inf, const char *filename,
10728 struct remote_state *rs = get_remote_state ();
10730 int left = get_remote_packet_size () - 1;
10732 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10735 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10737 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10738 strlen (filename));
10740 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10741 remote_errno, NULL, NULL);
10744 /* Implementation of to_fileio_readlink. */
10747 remote_hostio_readlink (struct target_ops *self,
10748 struct inferior *inf, const char *filename,
10751 struct remote_state *rs = get_remote_state ();
10754 int left = get_remote_packet_size ();
10755 int len, attachment_len;
10759 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10762 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10764 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10765 strlen (filename));
10767 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10768 remote_errno, &attachment,
10774 ret = xmalloc (len + 1);
10776 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10777 (gdb_byte *) ret, len);
10778 if (read_len != len)
10779 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10785 /* Implementation of to_fileio_fstat. */
10788 remote_hostio_fstat (struct target_ops *self,
10789 int fd, struct stat *st,
10792 struct remote_state *rs = get_remote_state ();
10794 int left = get_remote_packet_size ();
10795 int attachment_len, ret;
10797 struct fio_stat fst;
10800 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10802 remote_buffer_add_int (&p, &left, fd);
10804 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10805 remote_errno, &attachment,
10809 if (*remote_errno != FILEIO_ENOSYS)
10812 /* Strictly we should return -1, ENOSYS here, but when
10813 "set sysroot remote:" was implemented in August 2008
10814 BFD's need for a stat function was sidestepped with
10815 this hack. This was not remedied until March 2015
10816 so we retain the previous behavior to avoid breaking
10819 Note that the memset is a March 2015 addition; older
10820 GDBs set st_size *and nothing else* so the structure
10821 would have garbage in all other fields. This might
10822 break something but retaining the previous behavior
10823 here would be just too wrong. */
10825 memset (st, 0, sizeof (struct stat));
10826 st->st_size = INT_MAX;
10830 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10831 (gdb_byte *) &fst, sizeof (fst));
10833 if (read_len != ret)
10834 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10836 if (read_len != sizeof (fst))
10837 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10838 read_len, (int) sizeof (fst));
10840 remote_fileio_to_host_stat (&fst, st);
10845 /* Implementation of to_filesystem_is_local. */
10848 remote_filesystem_is_local (struct target_ops *self)
10850 /* Valgrind GDB presents itself as a remote target but works
10851 on the local filesystem: it does not implement remote get
10852 and users are not expected to set a sysroot. To handle
10853 this case we treat the remote filesystem as local if the
10854 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10855 does not support vFile:open. */
10856 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
10858 enum packet_support ps = packet_support (PACKET_vFile_open);
10860 if (ps == PACKET_SUPPORT_UNKNOWN)
10862 int fd, remote_errno;
10864 /* Try opening a file to probe support. The supplied
10865 filename is irrelevant, we only care about whether
10866 the stub recognizes the packet or not. */
10867 fd = remote_hostio_open (self, NULL, "just probing",
10868 FILEIO_O_RDONLY, 0700, 0,
10872 remote_hostio_close (self, fd, &remote_errno);
10874 ps = packet_support (PACKET_vFile_open);
10877 if (ps == PACKET_DISABLE)
10879 static int warning_issued = 0;
10881 if (!warning_issued)
10883 warning (_("remote target does not support file"
10884 " transfer, attempting to access files"
10885 " from local filesystem."));
10886 warning_issued = 1;
10897 remote_fileio_errno_to_host (int errnum)
10903 case FILEIO_ENOENT:
10911 case FILEIO_EACCES:
10913 case FILEIO_EFAULT:
10917 case FILEIO_EEXIST:
10919 case FILEIO_ENODEV:
10921 case FILEIO_ENOTDIR:
10923 case FILEIO_EISDIR:
10925 case FILEIO_EINVAL:
10927 case FILEIO_ENFILE:
10929 case FILEIO_EMFILE:
10933 case FILEIO_ENOSPC:
10935 case FILEIO_ESPIPE:
10939 case FILEIO_ENOSYS:
10941 case FILEIO_ENAMETOOLONG:
10942 return ENAMETOOLONG;
10948 remote_hostio_error (int errnum)
10950 int host_error = remote_fileio_errno_to_host (errnum);
10952 if (host_error == -1)
10953 error (_("Unknown remote I/O error %d"), errnum);
10955 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10959 remote_hostio_close_cleanup (void *opaque)
10961 int fd = *(int *) opaque;
10964 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10968 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10970 struct cleanup *back_to, *close_cleanup;
10971 int retcode, fd, remote_errno, bytes, io_size;
10974 int bytes_in_buffer;
10977 struct remote_state *rs = get_remote_state ();
10979 if (!rs->remote_desc)
10980 error (_("command can only be used with remote target"));
10982 file = gdb_fopen_cloexec (local_file, "rb");
10984 perror_with_name (local_file);
10985 back_to = make_cleanup_fclose (file);
10987 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
10988 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10990 0700, 0, &remote_errno);
10992 remote_hostio_error (remote_errno);
10994 /* Send up to this many bytes at once. They won't all fit in the
10995 remote packet limit, so we'll transfer slightly fewer. */
10996 io_size = get_remote_packet_size ();
10997 buffer = xmalloc (io_size);
10998 make_cleanup (xfree, buffer);
11000 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11002 bytes_in_buffer = 0;
11005 while (bytes_in_buffer || !saw_eof)
11009 bytes = fread (buffer + bytes_in_buffer, 1,
11010 io_size - bytes_in_buffer,
11015 error (_("Error reading %s."), local_file);
11018 /* EOF. Unless there is something still in the
11019 buffer from the last iteration, we are done. */
11021 if (bytes_in_buffer == 0)
11029 bytes += bytes_in_buffer;
11030 bytes_in_buffer = 0;
11032 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11034 offset, &remote_errno);
11037 remote_hostio_error (remote_errno);
11038 else if (retcode == 0)
11039 error (_("Remote write of %d bytes returned 0!"), bytes);
11040 else if (retcode < bytes)
11042 /* Short write. Save the rest of the read data for the next
11044 bytes_in_buffer = bytes - retcode;
11045 memmove (buffer, buffer + retcode, bytes_in_buffer);
11051 discard_cleanups (close_cleanup);
11052 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11053 remote_hostio_error (remote_errno);
11056 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11057 do_cleanups (back_to);
11061 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11063 struct cleanup *back_to, *close_cleanup;
11064 int fd, remote_errno, bytes, io_size;
11068 struct remote_state *rs = get_remote_state ();
11070 if (!rs->remote_desc)
11071 error (_("command can only be used with remote target"));
11073 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11074 remote_file, FILEIO_O_RDONLY, 0, 0,
11077 remote_hostio_error (remote_errno);
11079 file = gdb_fopen_cloexec (local_file, "wb");
11081 perror_with_name (local_file);
11082 back_to = make_cleanup_fclose (file);
11084 /* Send up to this many bytes at once. They won't all fit in the
11085 remote packet limit, so we'll transfer slightly fewer. */
11086 io_size = get_remote_packet_size ();
11087 buffer = xmalloc (io_size);
11088 make_cleanup (xfree, buffer);
11090 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11095 bytes = remote_hostio_pread (find_target_at (process_stratum),
11096 fd, buffer, io_size, offset, &remote_errno);
11098 /* Success, but no bytes, means end-of-file. */
11101 remote_hostio_error (remote_errno);
11105 bytes = fwrite (buffer, 1, bytes, file);
11107 perror_with_name (local_file);
11110 discard_cleanups (close_cleanup);
11111 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11112 remote_hostio_error (remote_errno);
11115 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11116 do_cleanups (back_to);
11120 remote_file_delete (const char *remote_file, int from_tty)
11122 int retcode, remote_errno;
11123 struct remote_state *rs = get_remote_state ();
11125 if (!rs->remote_desc)
11126 error (_("command can only be used with remote target"));
11128 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11129 NULL, remote_file, &remote_errno);
11131 remote_hostio_error (remote_errno);
11134 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11138 remote_put_command (char *args, int from_tty)
11140 struct cleanup *back_to;
11144 error_no_arg (_("file to put"));
11146 argv = gdb_buildargv (args);
11147 back_to = make_cleanup_freeargv (argv);
11148 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11149 error (_("Invalid parameters to remote put"));
11151 remote_file_put (argv[0], argv[1], from_tty);
11153 do_cleanups (back_to);
11157 remote_get_command (char *args, int from_tty)
11159 struct cleanup *back_to;
11163 error_no_arg (_("file to get"));
11165 argv = gdb_buildargv (args);
11166 back_to = make_cleanup_freeargv (argv);
11167 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11168 error (_("Invalid parameters to remote get"));
11170 remote_file_get (argv[0], argv[1], from_tty);
11172 do_cleanups (back_to);
11176 remote_delete_command (char *args, int from_tty)
11178 struct cleanup *back_to;
11182 error_no_arg (_("file to delete"));
11184 argv = gdb_buildargv (args);
11185 back_to = make_cleanup_freeargv (argv);
11186 if (argv[0] == NULL || argv[1] != NULL)
11187 error (_("Invalid parameters to remote delete"));
11189 remote_file_delete (argv[0], from_tty);
11191 do_cleanups (back_to);
11195 remote_command (char *args, int from_tty)
11197 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11201 remote_can_execute_reverse (struct target_ops *self)
11203 if (packet_support (PACKET_bs) == PACKET_ENABLE
11204 || packet_support (PACKET_bc) == PACKET_ENABLE)
11211 remote_supports_non_stop (struct target_ops *self)
11217 remote_supports_disable_randomization (struct target_ops *self)
11219 /* Only supported in extended mode. */
11224 remote_supports_multi_process (struct target_ops *self)
11226 struct remote_state *rs = get_remote_state ();
11228 /* Only extended-remote handles being attached to multiple
11229 processes, even though plain remote can use the multi-process
11230 thread id extensions, so that GDB knows the target process's
11232 return rs->extended && remote_multi_process_p (rs);
11236 remote_supports_cond_tracepoints (void)
11238 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11242 remote_supports_cond_breakpoints (struct target_ops *self)
11244 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11248 remote_supports_fast_tracepoints (void)
11250 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11254 remote_supports_static_tracepoints (void)
11256 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11260 remote_supports_install_in_trace (void)
11262 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11266 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11268 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11273 remote_supports_string_tracing (struct target_ops *self)
11275 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11279 remote_can_run_breakpoint_commands (struct target_ops *self)
11281 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11285 remote_trace_init (struct target_ops *self)
11288 remote_get_noisy_reply (&target_buf, &target_buf_size);
11289 if (strcmp (target_buf, "OK") != 0)
11290 error (_("Target does not support this command."));
11293 static void free_actions_list (char **actions_list);
11294 static void free_actions_list_cleanup_wrapper (void *);
11296 free_actions_list_cleanup_wrapper (void *al)
11298 free_actions_list (al);
11302 free_actions_list (char **actions_list)
11306 if (actions_list == 0)
11309 for (ndx = 0; actions_list[ndx]; ndx++)
11310 xfree (actions_list[ndx]);
11312 xfree (actions_list);
11315 /* Recursive routine to walk through command list including loops, and
11316 download packets for each command. */
11319 remote_download_command_source (int num, ULONGEST addr,
11320 struct command_line *cmds)
11322 struct remote_state *rs = get_remote_state ();
11323 struct command_line *cmd;
11325 for (cmd = cmds; cmd; cmd = cmd->next)
11327 QUIT; /* Allow user to bail out with ^C. */
11328 strcpy (rs->buf, "QTDPsrc:");
11329 encode_source_string (num, addr, "cmd", cmd->line,
11330 rs->buf + strlen (rs->buf),
11331 rs->buf_size - strlen (rs->buf));
11333 remote_get_noisy_reply (&target_buf, &target_buf_size);
11334 if (strcmp (target_buf, "OK"))
11335 warning (_("Target does not support source download."));
11337 if (cmd->control_type == while_control
11338 || cmd->control_type == while_stepping_control)
11340 remote_download_command_source (num, addr, *cmd->body_list);
11342 QUIT; /* Allow user to bail out with ^C. */
11343 strcpy (rs->buf, "QTDPsrc:");
11344 encode_source_string (num, addr, "cmd", "end",
11345 rs->buf + strlen (rs->buf),
11346 rs->buf_size - strlen (rs->buf));
11348 remote_get_noisy_reply (&target_buf, &target_buf_size);
11349 if (strcmp (target_buf, "OK"))
11350 warning (_("Target does not support source download."));
11356 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11358 #define BUF_SIZE 2048
11362 char buf[BUF_SIZE];
11363 char **tdp_actions;
11364 char **stepping_actions;
11366 struct cleanup *old_chain = NULL;
11367 struct agent_expr *aexpr;
11368 struct cleanup *aexpr_chain = NULL;
11370 struct breakpoint *b = loc->owner;
11371 struct tracepoint *t = (struct tracepoint *) b;
11373 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11374 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11376 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11379 tpaddr = loc->address;
11380 sprintf_vma (addrbuf, tpaddr);
11381 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11382 addrbuf, /* address */
11383 (b->enable_state == bp_enabled ? 'E' : 'D'),
11384 t->step_count, t->pass_count);
11385 /* Fast tracepoints are mostly handled by the target, but we can
11386 tell the target how big of an instruction block should be moved
11388 if (b->type == bp_fast_tracepoint)
11390 /* Only test for support at download time; we may not know
11391 target capabilities at definition time. */
11392 if (remote_supports_fast_tracepoints ())
11394 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11396 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11397 gdb_insn_length (loc->gdbarch, tpaddr));
11399 /* If it passed validation at definition but fails now,
11400 something is very wrong. */
11401 internal_error (__FILE__, __LINE__,
11402 _("Fast tracepoint not "
11403 "valid during download"));
11406 /* Fast tracepoints are functionally identical to regular
11407 tracepoints, so don't take lack of support as a reason to
11408 give up on the trace run. */
11409 warning (_("Target does not support fast tracepoints, "
11410 "downloading %d as regular tracepoint"), b->number);
11412 else if (b->type == bp_static_tracepoint)
11414 /* Only test for support at download time; we may not know
11415 target capabilities at definition time. */
11416 if (remote_supports_static_tracepoints ())
11418 struct static_tracepoint_marker marker;
11420 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11421 strcat (buf, ":S");
11423 error (_("Static tracepoint not valid during download"));
11426 /* Fast tracepoints are functionally identical to regular
11427 tracepoints, so don't take lack of support as a reason
11428 to give up on the trace run. */
11429 error (_("Target does not support static tracepoints"));
11431 /* If the tracepoint has a conditional, make it into an agent
11432 expression and append to the definition. */
11435 /* Only test support at download time, we may not know target
11436 capabilities at definition time. */
11437 if (remote_supports_cond_tracepoints ())
11439 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11440 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11441 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11443 pkt = buf + strlen (buf);
11444 for (ndx = 0; ndx < aexpr->len; ++ndx)
11445 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11447 do_cleanups (aexpr_chain);
11450 warning (_("Target does not support conditional tracepoints, "
11451 "ignoring tp %d cond"), b->number);
11454 if (b->commands || *default_collect)
11457 remote_get_noisy_reply (&target_buf, &target_buf_size);
11458 if (strcmp (target_buf, "OK"))
11459 error (_("Target does not support tracepoints."));
11461 /* do_single_steps (t); */
11464 for (ndx = 0; tdp_actions[ndx]; ndx++)
11466 QUIT; /* Allow user to bail out with ^C. */
11467 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11468 b->number, addrbuf, /* address */
11470 ((tdp_actions[ndx + 1] || stepping_actions)
11473 remote_get_noisy_reply (&target_buf,
11475 if (strcmp (target_buf, "OK"))
11476 error (_("Error on target while setting tracepoints."));
11479 if (stepping_actions)
11481 for (ndx = 0; stepping_actions[ndx]; ndx++)
11483 QUIT; /* Allow user to bail out with ^C. */
11484 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11485 b->number, addrbuf, /* address */
11486 ((ndx == 0) ? "S" : ""),
11487 stepping_actions[ndx],
11488 (stepping_actions[ndx + 1] ? "-" : ""));
11490 remote_get_noisy_reply (&target_buf,
11492 if (strcmp (target_buf, "OK"))
11493 error (_("Error on target while setting tracepoints."));
11497 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11499 if (b->location != NULL)
11501 strcpy (buf, "QTDPsrc:");
11502 encode_source_string (b->number, loc->address, "at",
11503 event_location_to_string (b->location),
11504 buf + strlen (buf), 2048 - strlen (buf));
11506 remote_get_noisy_reply (&target_buf, &target_buf_size);
11507 if (strcmp (target_buf, "OK"))
11508 warning (_("Target does not support source download."));
11510 if (b->cond_string)
11512 strcpy (buf, "QTDPsrc:");
11513 encode_source_string (b->number, loc->address,
11514 "cond", b->cond_string, buf + strlen (buf),
11515 2048 - strlen (buf));
11517 remote_get_noisy_reply (&target_buf, &target_buf_size);
11518 if (strcmp (target_buf, "OK"))
11519 warning (_("Target does not support source download."));
11521 remote_download_command_source (b->number, loc->address,
11522 breakpoint_commands (b));
11525 do_cleanups (old_chain);
11529 remote_can_download_tracepoint (struct target_ops *self)
11531 struct remote_state *rs = get_remote_state ();
11532 struct trace_status *ts;
11535 /* Don't try to install tracepoints until we've relocated our
11536 symbols, and fetched and merged the target's tracepoint list with
11538 if (rs->starting_up)
11541 ts = current_trace_status ();
11542 status = remote_get_trace_status (self, ts);
11544 if (status == -1 || !ts->running_known || !ts->running)
11547 /* If we are in a tracing experiment, but remote stub doesn't support
11548 installing tracepoint in trace, we have to return. */
11549 if (!remote_supports_install_in_trace ())
11557 remote_download_trace_state_variable (struct target_ops *self,
11558 struct trace_state_variable *tsv)
11560 struct remote_state *rs = get_remote_state ();
11563 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11564 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11566 p = rs->buf + strlen (rs->buf);
11567 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11568 error (_("Trace state variable name too long for tsv definition packet"));
11569 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11572 remote_get_noisy_reply (&target_buf, &target_buf_size);
11573 if (*target_buf == '\0')
11574 error (_("Target does not support this command."));
11575 if (strcmp (target_buf, "OK") != 0)
11576 error (_("Error on target while downloading trace state variable."));
11580 remote_enable_tracepoint (struct target_ops *self,
11581 struct bp_location *location)
11583 struct remote_state *rs = get_remote_state ();
11586 sprintf_vma (addr_buf, location->address);
11587 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11588 location->owner->number, addr_buf);
11590 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11591 if (*rs->buf == '\0')
11592 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11593 if (strcmp (rs->buf, "OK") != 0)
11594 error (_("Error on target while enabling tracepoint."));
11598 remote_disable_tracepoint (struct target_ops *self,
11599 struct bp_location *location)
11601 struct remote_state *rs = get_remote_state ();
11604 sprintf_vma (addr_buf, location->address);
11605 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11606 location->owner->number, addr_buf);
11608 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11609 if (*rs->buf == '\0')
11610 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11611 if (strcmp (rs->buf, "OK") != 0)
11612 error (_("Error on target while disabling tracepoint."));
11616 remote_trace_set_readonly_regions (struct target_ops *self)
11620 bfd_size_type size;
11626 return; /* No information to give. */
11628 strcpy (target_buf, "QTro");
11629 offset = strlen (target_buf);
11630 for (s = exec_bfd->sections; s; s = s->next)
11632 char tmp1[40], tmp2[40];
11635 if ((s->flags & SEC_LOAD) == 0 ||
11636 /* (s->flags & SEC_CODE) == 0 || */
11637 (s->flags & SEC_READONLY) == 0)
11641 vma = bfd_get_section_vma (abfd, s);
11642 size = bfd_get_section_size (s);
11643 sprintf_vma (tmp1, vma);
11644 sprintf_vma (tmp2, vma + size);
11645 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11646 if (offset + sec_length + 1 > target_buf_size)
11648 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
11650 Too many sections for read-only sections definition packet."));
11653 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11655 offset += sec_length;
11659 putpkt (target_buf);
11660 getpkt (&target_buf, &target_buf_size, 0);
11665 remote_trace_start (struct target_ops *self)
11667 putpkt ("QTStart");
11668 remote_get_noisy_reply (&target_buf, &target_buf_size);
11669 if (*target_buf == '\0')
11670 error (_("Target does not support this command."));
11671 if (strcmp (target_buf, "OK") != 0)
11672 error (_("Bogus reply from target: %s"), target_buf);
11676 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11678 /* Initialize it just to avoid a GCC false warning. */
11680 /* FIXME we need to get register block size some other way. */
11681 extern int trace_regblock_size;
11682 enum packet_result result;
11684 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11687 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11689 putpkt ("qTStatus");
11693 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11695 CATCH (ex, RETURN_MASK_ERROR)
11697 if (ex.error != TARGET_CLOSE_ERROR)
11699 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11702 throw_exception (ex);
11706 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11708 /* If the remote target doesn't do tracing, flag it. */
11709 if (result == PACKET_UNKNOWN)
11712 /* We're working with a live target. */
11713 ts->filename = NULL;
11716 error (_("Bogus trace status reply from target: %s"), target_buf);
11718 /* Function 'parse_trace_status' sets default value of each field of
11719 'ts' at first, so we don't have to do it here. */
11720 parse_trace_status (p, ts);
11722 return ts->running;
11726 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
11727 struct uploaded_tp *utp)
11729 struct remote_state *rs = get_remote_state ();
11731 struct bp_location *loc;
11732 struct tracepoint *tp = (struct tracepoint *) bp;
11733 size_t size = get_remote_packet_size ();
11737 tp->base.hit_count = 0;
11738 tp->traceframe_usage = 0;
11739 for (loc = tp->base.loc; loc; loc = loc->next)
11741 /* If the tracepoint was never downloaded, don't go asking for
11743 if (tp->number_on_target == 0)
11745 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11746 phex_nz (loc->address, 0));
11748 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11749 if (reply && *reply)
11752 parse_tracepoint_status (reply + 1, bp, utp);
11758 utp->hit_count = 0;
11759 utp->traceframe_usage = 0;
11760 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11761 phex_nz (utp->addr, 0));
11763 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11764 if (reply && *reply)
11767 parse_tracepoint_status (reply + 1, bp, utp);
11773 remote_trace_stop (struct target_ops *self)
11776 remote_get_noisy_reply (&target_buf, &target_buf_size);
11777 if (*target_buf == '\0')
11778 error (_("Target does not support this command."));
11779 if (strcmp (target_buf, "OK") != 0)
11780 error (_("Bogus reply from target: %s"), target_buf);
11784 remote_trace_find (struct target_ops *self,
11785 enum trace_find_type type, int num,
11786 CORE_ADDR addr1, CORE_ADDR addr2,
11789 struct remote_state *rs = get_remote_state ();
11790 char *endbuf = rs->buf + get_remote_packet_size ();
11792 int target_frameno = -1, target_tracept = -1;
11794 /* Lookups other than by absolute frame number depend on the current
11795 trace selected, so make sure it is correct on the remote end
11797 if (type != tfind_number)
11798 set_remote_traceframe ();
11801 strcpy (p, "QTFrame:");
11802 p = strchr (p, '\0');
11806 xsnprintf (p, endbuf - p, "%x", num);
11809 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11812 xsnprintf (p, endbuf - p, "tdp:%x", num);
11815 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11816 phex_nz (addr2, 0));
11818 case tfind_outside:
11819 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11820 phex_nz (addr2, 0));
11823 error (_("Unknown trace find type %d"), type);
11827 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11828 if (*reply == '\0')
11829 error (_("Target does not support this command."));
11831 while (reply && *reply)
11836 target_frameno = (int) strtol (p, &reply, 16);
11838 error (_("Unable to parse trace frame number"));
11839 /* Don't update our remote traceframe number cache on failure
11840 to select a remote traceframe. */
11841 if (target_frameno == -1)
11846 target_tracept = (int) strtol (p, &reply, 16);
11848 error (_("Unable to parse tracepoint number"));
11850 case 'O': /* "OK"? */
11851 if (reply[1] == 'K' && reply[2] == '\0')
11854 error (_("Bogus reply from target: %s"), reply);
11857 error (_("Bogus reply from target: %s"), reply);
11860 *tpp = target_tracept;
11862 rs->remote_traceframe_number = target_frameno;
11863 return target_frameno;
11867 remote_get_trace_state_variable_value (struct target_ops *self,
11868 int tsvnum, LONGEST *val)
11870 struct remote_state *rs = get_remote_state ();
11874 set_remote_traceframe ();
11876 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11878 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11879 if (reply && *reply)
11883 unpack_varlen_hex (reply + 1, &uval);
11884 *val = (LONGEST) uval;
11892 remote_save_trace_data (struct target_ops *self, const char *filename)
11894 struct remote_state *rs = get_remote_state ();
11898 strcpy (p, "QTSave:");
11900 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11901 error (_("Remote file name too long for trace save packet"));
11902 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11905 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11906 if (*reply == '\0')
11907 error (_("Target does not support this command."));
11908 if (strcmp (reply, "OK") != 0)
11909 error (_("Bogus reply from target: %s"), reply);
11913 /* This is basically a memory transfer, but needs to be its own packet
11914 because we don't know how the target actually organizes its trace
11915 memory, plus we want to be able to ask for as much as possible, but
11916 not be unhappy if we don't get as much as we ask for. */
11919 remote_get_raw_trace_data (struct target_ops *self,
11920 gdb_byte *buf, ULONGEST offset, LONGEST len)
11922 struct remote_state *rs = get_remote_state ();
11928 strcpy (p, "qTBuffer:");
11930 p += hexnumstr (p, offset);
11932 p += hexnumstr (p, len);
11936 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11937 if (reply && *reply)
11939 /* 'l' by itself means we're at the end of the buffer and
11940 there is nothing more to get. */
11944 /* Convert the reply into binary. Limit the number of bytes to
11945 convert according to our passed-in buffer size, rather than
11946 what was returned in the packet; if the target is
11947 unexpectedly generous and gives us a bigger reply than we
11948 asked for, we don't want to crash. */
11949 rslt = hex2bin (target_buf, buf, len);
11953 /* Something went wrong, flag as an error. */
11958 remote_set_disconnected_tracing (struct target_ops *self, int val)
11960 struct remote_state *rs = get_remote_state ();
11962 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11966 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11968 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11969 if (*reply == '\0')
11970 error (_("Target does not support this command."));
11971 if (strcmp (reply, "OK") != 0)
11972 error (_("Bogus reply from target: %s"), reply);
11975 warning (_("Target does not support disconnected tracing."));
11979 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11981 struct thread_info *info = find_thread_ptid (ptid);
11983 if (info && info->priv)
11984 return info->priv->core;
11989 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11991 struct remote_state *rs = get_remote_state ();
11994 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11996 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11997 if (*reply == '\0')
11998 error (_("Target does not support this command."));
11999 if (strcmp (reply, "OK") != 0)
12000 error (_("Bogus reply from target: %s"), reply);
12003 static struct traceframe_info *
12004 remote_traceframe_info (struct target_ops *self)
12008 text = target_read_stralloc (¤t_target,
12009 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12012 struct traceframe_info *info;
12013 struct cleanup *back_to = make_cleanup (xfree, text);
12015 info = parse_traceframe_info (text);
12016 do_cleanups (back_to);
12023 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12024 instruction on which a fast tracepoint may be placed. Returns -1
12025 if the packet is not supported, and 0 if the minimum instruction
12026 length is unknown. */
12029 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12031 struct remote_state *rs = get_remote_state ();
12034 /* If we're not debugging a process yet, the IPA can't be
12036 if (!target_has_execution)
12039 /* Make sure the remote is pointing at the right process. */
12040 set_general_process ();
12042 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12044 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12045 if (*reply == '\0')
12049 ULONGEST min_insn_len;
12051 unpack_varlen_hex (reply, &min_insn_len);
12053 return (int) min_insn_len;
12058 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12060 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12062 struct remote_state *rs = get_remote_state ();
12063 char *buf = rs->buf;
12064 char *endbuf = rs->buf + get_remote_packet_size ();
12065 enum packet_result result;
12067 gdb_assert (val >= 0 || val == -1);
12068 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12069 /* Send -1 as literal "-1" to avoid host size dependency. */
12073 buf += hexnumstr (buf, (ULONGEST) -val);
12076 buf += hexnumstr (buf, (ULONGEST) val);
12079 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12080 result = packet_ok (rs->buf,
12081 &remote_protocol_packets[PACKET_QTBuffer_size]);
12083 if (result != PACKET_OK)
12084 warning (_("Bogus reply from target: %s"), rs->buf);
12089 remote_set_trace_notes (struct target_ops *self,
12090 const char *user, const char *notes,
12091 const char *stop_notes)
12093 struct remote_state *rs = get_remote_state ();
12095 char *buf = rs->buf;
12096 char *endbuf = rs->buf + get_remote_packet_size ();
12099 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12102 buf += xsnprintf (buf, endbuf - buf, "user:");
12103 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12109 buf += xsnprintf (buf, endbuf - buf, "notes:");
12110 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12116 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12117 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12121 /* Ensure the buffer is terminated. */
12125 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12126 if (*reply == '\0')
12129 if (strcmp (reply, "OK") != 0)
12130 error (_("Bogus reply from target: %s"), reply);
12136 remote_use_agent (struct target_ops *self, int use)
12138 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12140 struct remote_state *rs = get_remote_state ();
12142 /* If the stub supports QAgent. */
12143 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12145 getpkt (&rs->buf, &rs->buf_size, 0);
12147 if (strcmp (rs->buf, "OK") == 0)
12158 remote_can_use_agent (struct target_ops *self)
12160 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12163 struct btrace_target_info
12165 /* The ptid of the traced thread. */
12168 /* The obtained branch trace configuration. */
12169 struct btrace_config conf;
12172 /* Reset our idea of our target's btrace configuration. */
12175 remote_btrace_reset (void)
12177 struct remote_state *rs = get_remote_state ();
12179 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12182 /* Check whether the target supports branch tracing. */
12185 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12187 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12189 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12194 case BTRACE_FORMAT_NONE:
12197 case BTRACE_FORMAT_BTS:
12198 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12200 case BTRACE_FORMAT_PT:
12201 /* The trace is decoded on the host. Even if our target supports it,
12202 we still need to have libipt to decode the trace. */
12203 #if defined (HAVE_LIBIPT)
12204 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12205 #else /* !defined (HAVE_LIBIPT) */
12207 #endif /* !defined (HAVE_LIBIPT) */
12210 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12213 /* Synchronize the configuration with the target. */
12216 btrace_sync_conf (const struct btrace_config *conf)
12218 struct packet_config *packet;
12219 struct remote_state *rs;
12220 char *buf, *pos, *endbuf;
12222 rs = get_remote_state ();
12224 endbuf = buf + get_remote_packet_size ();
12226 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12227 if (packet_config_support (packet) == PACKET_ENABLE
12228 && conf->bts.size != rs->btrace_config.bts.size)
12231 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12235 getpkt (&buf, &rs->buf_size, 0);
12237 if (packet_ok (buf, packet) == PACKET_ERROR)
12239 if (buf[0] == 'E' && buf[1] == '.')
12240 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12242 error (_("Failed to configure the BTS buffer size."));
12245 rs->btrace_config.bts.size = conf->bts.size;
12248 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12249 if (packet_config_support (packet) == PACKET_ENABLE
12250 && conf->pt.size != rs->btrace_config.pt.size)
12253 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12257 getpkt (&buf, &rs->buf_size, 0);
12259 if (packet_ok (buf, packet) == PACKET_ERROR)
12261 if (buf[0] == 'E' && buf[1] == '.')
12262 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12264 error (_("Failed to configure the trace buffer size."));
12267 rs->btrace_config.pt.size = conf->pt.size;
12271 /* Read the current thread's btrace configuration from the target and
12272 store it into CONF. */
12275 btrace_read_config (struct btrace_config *conf)
12279 xml = target_read_stralloc (¤t_target,
12280 TARGET_OBJECT_BTRACE_CONF, "");
12283 struct cleanup *cleanup;
12285 cleanup = make_cleanup (xfree, xml);
12286 parse_xml_btrace_conf (conf, xml);
12287 do_cleanups (cleanup);
12291 /* Enable branch tracing. */
12293 static struct btrace_target_info *
12294 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12295 const struct btrace_config *conf)
12297 struct btrace_target_info *tinfo = NULL;
12298 struct packet_config *packet = NULL;
12299 struct remote_state *rs = get_remote_state ();
12300 char *buf = rs->buf;
12301 char *endbuf = rs->buf + get_remote_packet_size ();
12303 switch (conf->format)
12305 case BTRACE_FORMAT_BTS:
12306 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12309 case BTRACE_FORMAT_PT:
12310 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12314 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12315 error (_("Target does not support branch tracing."));
12317 btrace_sync_conf (conf);
12319 set_general_thread (ptid);
12321 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12323 getpkt (&rs->buf, &rs->buf_size, 0);
12325 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12327 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12328 error (_("Could not enable branch tracing for %s: %s"),
12329 target_pid_to_str (ptid), rs->buf + 2);
12331 error (_("Could not enable branch tracing for %s."),
12332 target_pid_to_str (ptid));
12335 tinfo = XCNEW (struct btrace_target_info);
12336 tinfo->ptid = ptid;
12338 /* If we fail to read the configuration, we lose some information, but the
12339 tracing itself is not impacted. */
12342 btrace_read_config (&tinfo->conf);
12344 CATCH (err, RETURN_MASK_ERROR)
12346 if (err.message != NULL)
12347 warning ("%s", err.message);
12354 /* Disable branch tracing. */
12357 remote_disable_btrace (struct target_ops *self,
12358 struct btrace_target_info *tinfo)
12360 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12361 struct remote_state *rs = get_remote_state ();
12362 char *buf = rs->buf;
12363 char *endbuf = rs->buf + get_remote_packet_size ();
12365 if (packet_config_support (packet) != PACKET_ENABLE)
12366 error (_("Target does not support branch tracing."));
12368 set_general_thread (tinfo->ptid);
12370 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12372 getpkt (&rs->buf, &rs->buf_size, 0);
12374 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12376 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12377 error (_("Could not disable branch tracing for %s: %s"),
12378 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12380 error (_("Could not disable branch tracing for %s."),
12381 target_pid_to_str (tinfo->ptid));
12387 /* Teardown branch tracing. */
12390 remote_teardown_btrace (struct target_ops *self,
12391 struct btrace_target_info *tinfo)
12393 /* We must not talk to the target during teardown. */
12397 /* Read the branch trace. */
12399 static enum btrace_error
12400 remote_read_btrace (struct target_ops *self,
12401 struct btrace_data *btrace,
12402 struct btrace_target_info *tinfo,
12403 enum btrace_read_type type)
12405 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12406 struct remote_state *rs = get_remote_state ();
12407 struct cleanup *cleanup;
12411 if (packet_config_support (packet) != PACKET_ENABLE)
12412 error (_("Target does not support branch tracing."));
12414 #if !defined(HAVE_LIBEXPAT)
12415 error (_("Cannot process branch tracing result. XML parsing not supported."));
12420 case BTRACE_READ_ALL:
12423 case BTRACE_READ_NEW:
12426 case BTRACE_READ_DELTA:
12430 internal_error (__FILE__, __LINE__,
12431 _("Bad branch tracing read type: %u."),
12432 (unsigned int) type);
12435 xml = target_read_stralloc (¤t_target,
12436 TARGET_OBJECT_BTRACE, annex);
12438 return BTRACE_ERR_UNKNOWN;
12440 cleanup = make_cleanup (xfree, xml);
12441 parse_xml_btrace (btrace, xml);
12442 do_cleanups (cleanup);
12444 return BTRACE_ERR_NONE;
12447 static const struct btrace_config *
12448 remote_btrace_conf (struct target_ops *self,
12449 const struct btrace_target_info *tinfo)
12451 return &tinfo->conf;
12455 remote_augmented_libraries_svr4_read (struct target_ops *self)
12457 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12461 /* Implementation of to_load. */
12464 remote_load (struct target_ops *self, const char *name, int from_tty)
12466 generic_load (name, from_tty);
12469 /* Accepts an integer PID; returns a string representing a file that
12470 can be opened on the remote side to get the symbols for the child
12471 process. Returns NULL if the operation is not supported. */
12474 remote_pid_to_exec_file (struct target_ops *self, int pid)
12476 static char *filename = NULL;
12477 struct inferior *inf;
12478 char *annex = NULL;
12480 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12483 if (filename != NULL)
12486 inf = find_inferior_pid (pid);
12488 internal_error (__FILE__, __LINE__,
12489 _("not currently attached to process %d"), pid);
12491 if (!inf->fake_pid_p)
12493 const int annex_size = 9;
12495 annex = alloca (annex_size);
12496 xsnprintf (annex, annex_size, "%x", pid);
12499 filename = target_read_stralloc (¤t_target,
12500 TARGET_OBJECT_EXEC_FILE, annex);
12506 init_remote_ops (void)
12508 remote_ops.to_shortname = "remote";
12509 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12510 remote_ops.to_doc =
12511 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12512 Specify the serial device it is connected to\n\
12513 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12514 remote_ops.to_open = remote_open;
12515 remote_ops.to_close = remote_close;
12516 remote_ops.to_detach = remote_detach;
12517 remote_ops.to_disconnect = remote_disconnect;
12518 remote_ops.to_resume = remote_resume;
12519 remote_ops.to_wait = remote_wait;
12520 remote_ops.to_fetch_registers = remote_fetch_registers;
12521 remote_ops.to_store_registers = remote_store_registers;
12522 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12523 remote_ops.to_files_info = remote_files_info;
12524 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12525 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12526 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12527 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12528 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12529 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12530 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12531 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12532 remote_ops.to_watchpoint_addr_within_range =
12533 remote_watchpoint_addr_within_range;
12534 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12535 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12536 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12537 remote_ops.to_region_ok_for_hw_watchpoint
12538 = remote_region_ok_for_hw_watchpoint;
12539 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12540 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12541 remote_ops.to_kill = remote_kill;
12542 remote_ops.to_load = remote_load;
12543 remote_ops.to_mourn_inferior = remote_mourn;
12544 remote_ops.to_pass_signals = remote_pass_signals;
12545 remote_ops.to_program_signals = remote_program_signals;
12546 remote_ops.to_thread_alive = remote_thread_alive;
12547 remote_ops.to_update_thread_list = remote_update_thread_list;
12548 remote_ops.to_pid_to_str = remote_pid_to_str;
12549 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12550 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12551 remote_ops.to_stop = remote_stop;
12552 remote_ops.to_interrupt = remote_interrupt;
12553 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12554 remote_ops.to_xfer_partial = remote_xfer_partial;
12555 remote_ops.to_rcmd = remote_rcmd;
12556 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12557 remote_ops.to_log_command = serial_log_command;
12558 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12559 remote_ops.to_stratum = process_stratum;
12560 remote_ops.to_has_all_memory = default_child_has_all_memory;
12561 remote_ops.to_has_memory = default_child_has_memory;
12562 remote_ops.to_has_stack = default_child_has_stack;
12563 remote_ops.to_has_registers = default_child_has_registers;
12564 remote_ops.to_has_execution = default_child_has_execution;
12565 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12566 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12567 remote_ops.to_magic = OPS_MAGIC;
12568 remote_ops.to_memory_map = remote_memory_map;
12569 remote_ops.to_flash_erase = remote_flash_erase;
12570 remote_ops.to_flash_done = remote_flash_done;
12571 remote_ops.to_read_description = remote_read_description;
12572 remote_ops.to_search_memory = remote_search_memory;
12573 remote_ops.to_can_async_p = remote_can_async_p;
12574 remote_ops.to_is_async_p = remote_is_async_p;
12575 remote_ops.to_async = remote_async;
12576 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12577 remote_ops.to_terminal_ours = remote_terminal_ours;
12578 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12579 remote_ops.to_supports_multi_process = remote_supports_multi_process;
12580 remote_ops.to_supports_disable_randomization
12581 = remote_supports_disable_randomization;
12582 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12583 remote_ops.to_fileio_open = remote_hostio_open;
12584 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12585 remote_ops.to_fileio_pread = remote_hostio_pread;
12586 remote_ops.to_fileio_fstat = remote_hostio_fstat;
12587 remote_ops.to_fileio_close = remote_hostio_close;
12588 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12589 remote_ops.to_fileio_readlink = remote_hostio_readlink;
12590 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12591 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12592 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12593 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12594 remote_ops.to_trace_init = remote_trace_init;
12595 remote_ops.to_download_tracepoint = remote_download_tracepoint;
12596 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12597 remote_ops.to_download_trace_state_variable
12598 = remote_download_trace_state_variable;
12599 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12600 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12601 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12602 remote_ops.to_trace_start = remote_trace_start;
12603 remote_ops.to_get_trace_status = remote_get_trace_status;
12604 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12605 remote_ops.to_trace_stop = remote_trace_stop;
12606 remote_ops.to_trace_find = remote_trace_find;
12607 remote_ops.to_get_trace_state_variable_value
12608 = remote_get_trace_state_variable_value;
12609 remote_ops.to_save_trace_data = remote_save_trace_data;
12610 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
12611 remote_ops.to_upload_trace_state_variables
12612 = remote_upload_trace_state_variables;
12613 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
12614 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
12615 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12616 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
12617 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
12618 remote_ops.to_set_trace_notes = remote_set_trace_notes;
12619 remote_ops.to_core_of_thread = remote_core_of_thread;
12620 remote_ops.to_verify_memory = remote_verify_memory;
12621 remote_ops.to_get_tib_address = remote_get_tib_address;
12622 remote_ops.to_set_permissions = remote_set_permissions;
12623 remote_ops.to_static_tracepoint_marker_at
12624 = remote_static_tracepoint_marker_at;
12625 remote_ops.to_static_tracepoint_markers_by_strid
12626 = remote_static_tracepoint_markers_by_strid;
12627 remote_ops.to_traceframe_info = remote_traceframe_info;
12628 remote_ops.to_use_agent = remote_use_agent;
12629 remote_ops.to_can_use_agent = remote_can_use_agent;
12630 remote_ops.to_supports_btrace = remote_supports_btrace;
12631 remote_ops.to_enable_btrace = remote_enable_btrace;
12632 remote_ops.to_disable_btrace = remote_disable_btrace;
12633 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12634 remote_ops.to_read_btrace = remote_read_btrace;
12635 remote_ops.to_btrace_conf = remote_btrace_conf;
12636 remote_ops.to_augmented_libraries_svr4_read =
12637 remote_augmented_libraries_svr4_read;
12640 /* Set up the extended remote vector by making a copy of the standard
12641 remote vector and adding to it. */
12644 init_extended_remote_ops (void)
12646 extended_remote_ops = remote_ops;
12648 extended_remote_ops.to_shortname = "extended-remote";
12649 extended_remote_ops.to_longname =
12650 "Extended remote serial target in gdb-specific protocol";
12651 extended_remote_ops.to_doc =
12652 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12653 Specify the serial device it is connected to (e.g. /dev/ttya).";
12654 extended_remote_ops.to_open = extended_remote_open;
12655 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12656 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
12657 extended_remote_ops.to_detach = extended_remote_detach;
12658 extended_remote_ops.to_attach = extended_remote_attach;
12659 extended_remote_ops.to_post_attach = extended_remote_post_attach;
12660 extended_remote_ops.to_kill = extended_remote_kill;
12661 extended_remote_ops.to_supports_disable_randomization
12662 = extended_remote_supports_disable_randomization;
12663 extended_remote_ops.to_follow_fork = remote_follow_fork;
12664 extended_remote_ops.to_insert_fork_catchpoint
12665 = remote_insert_fork_catchpoint;
12666 extended_remote_ops.to_remove_fork_catchpoint
12667 = remote_remove_fork_catchpoint;
12668 extended_remote_ops.to_insert_vfork_catchpoint
12669 = remote_insert_vfork_catchpoint;
12670 extended_remote_ops.to_remove_vfork_catchpoint
12671 = remote_remove_vfork_catchpoint;
12675 remote_can_async_p (struct target_ops *ops)
12677 struct remote_state *rs = get_remote_state ();
12679 if (!target_async_permitted)
12680 /* We only enable async when the user specifically asks for it. */
12683 /* We're async whenever the serial device is. */
12684 return serial_can_async_p (rs->remote_desc);
12688 remote_is_async_p (struct target_ops *ops)
12690 struct remote_state *rs = get_remote_state ();
12692 if (!target_async_permitted)
12693 /* We only enable async when the user specifically asks for it. */
12696 /* We're async whenever the serial device is. */
12697 return serial_is_async_p (rs->remote_desc);
12700 /* Pass the SERIAL event on and up to the client. One day this code
12701 will be able to delay notifying the client of an event until the
12702 point where an entire packet has been received. */
12704 static serial_event_ftype remote_async_serial_handler;
12707 remote_async_serial_handler (struct serial *scb, void *context)
12709 struct remote_state *rs = context;
12711 /* Don't propogate error information up to the client. Instead let
12712 the client find out about the error by querying the target. */
12713 inferior_event_handler (INF_REG_EVENT, NULL);
12717 remote_async_inferior_event_handler (gdb_client_data data)
12719 inferior_event_handler (INF_REG_EVENT, NULL);
12723 remote_async (struct target_ops *ops, int enable)
12725 struct remote_state *rs = get_remote_state ();
12729 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
12731 /* If there are pending events in the stop reply queue tell the
12732 event loop to process them. */
12733 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12734 mark_async_event_handler (remote_async_inferior_event_token);
12738 serial_async (rs->remote_desc, NULL, NULL);
12739 clear_async_event_handler (remote_async_inferior_event_token);
12744 set_remote_cmd (char *args, int from_tty)
12746 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
12750 show_remote_cmd (char *args, int from_tty)
12752 /* We can't just use cmd_show_list here, because we want to skip
12753 the redundant "show remote Z-packet" and the legacy aliases. */
12754 struct cleanup *showlist_chain;
12755 struct cmd_list_element *list = remote_show_cmdlist;
12756 struct ui_out *uiout = current_uiout;
12758 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12759 for (; list != NULL; list = list->next)
12760 if (strcmp (list->name, "Z-packet") == 0)
12762 else if (list->type == not_set_cmd)
12763 /* Alias commands are exactly like the original, except they
12764 don't have the normal type. */
12768 struct cleanup *option_chain
12769 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
12771 ui_out_field_string (uiout, "name", list->name);
12772 ui_out_text (uiout, ": ");
12773 if (list->type == show_cmd)
12774 do_show_command ((char *) NULL, from_tty, list);
12776 cmd_func (list, NULL, from_tty);
12777 /* Close the tuple. */
12778 do_cleanups (option_chain);
12781 /* Close the tuple. */
12782 do_cleanups (showlist_chain);
12786 /* Function to be called whenever a new objfile (shlib) is detected. */
12788 remote_new_objfile (struct objfile *objfile)
12790 struct remote_state *rs = get_remote_state ();
12792 if (rs->remote_desc != 0) /* Have a remote connection. */
12793 remote_check_symbols ();
12796 /* Pull all the tracepoints defined on the target and create local
12797 data structures representing them. We don't want to create real
12798 tracepoints yet, we don't want to mess up the user's existing
12802 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
12804 struct remote_state *rs = get_remote_state ();
12807 /* Ask for a first packet of tracepoint definition. */
12809 getpkt (&rs->buf, &rs->buf_size, 0);
12811 while (*p && *p != 'l')
12813 parse_tracepoint_definition (p, utpp);
12814 /* Ask for another packet of tracepoint definition. */
12816 getpkt (&rs->buf, &rs->buf_size, 0);
12823 remote_upload_trace_state_variables (struct target_ops *self,
12824 struct uploaded_tsv **utsvp)
12826 struct remote_state *rs = get_remote_state ();
12829 /* Ask for a first packet of variable definition. */
12831 getpkt (&rs->buf, &rs->buf_size, 0);
12833 while (*p && *p != 'l')
12835 parse_tsv_definition (p, utsvp);
12836 /* Ask for another packet of variable definition. */
12838 getpkt (&rs->buf, &rs->buf_size, 0);
12844 /* The "set/show range-stepping" show hook. */
12847 show_range_stepping (struct ui_file *file, int from_tty,
12848 struct cmd_list_element *c,
12851 fprintf_filtered (file,
12852 _("Debugger's willingness to use range stepping "
12853 "is %s.\n"), value);
12856 /* The "set/show range-stepping" set hook. */
12859 set_range_stepping (char *ignore_args, int from_tty,
12860 struct cmd_list_element *c)
12862 struct remote_state *rs = get_remote_state ();
12864 /* Whene enabling, check whether range stepping is actually
12865 supported by the target, and warn if not. */
12866 if (use_range_stepping)
12868 if (rs->remote_desc != NULL)
12870 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12871 remote_vcont_probe (rs);
12873 if (packet_support (PACKET_vCont) == PACKET_ENABLE
12874 && rs->supports_vCont.r)
12878 warning (_("Range stepping is not supported by the current target"));
12883 _initialize_remote (void)
12885 struct remote_state *rs;
12886 struct cmd_list_element *cmd;
12887 const char *cmd_name;
12889 /* architecture specific data */
12890 remote_gdbarch_data_handle =
12891 gdbarch_data_register_post_init (init_remote_state);
12892 remote_g_packet_data_handle =
12893 gdbarch_data_register_pre_init (remote_g_packet_data_init);
12895 /* Initialize the per-target state. At the moment there is only one
12896 of these, not one per target. Only one target is active at a
12898 remote_state = new_remote_state ();
12900 init_remote_ops ();
12901 add_target (&remote_ops);
12903 init_extended_remote_ops ();
12904 add_target (&extended_remote_ops);
12906 /* Hook into new objfile notification. */
12907 observer_attach_new_objfile (remote_new_objfile);
12908 /* We're no longer interested in notification events of an inferior
12910 observer_attach_inferior_exit (discard_pending_stop_replies);
12912 /* Set up signal handlers. */
12913 async_sigint_remote_token =
12914 create_async_signal_handler (async_remote_interrupt, NULL);
12915 async_sigint_remote_twice_token =
12916 create_async_signal_handler (async_remote_interrupt_twice, NULL);
12919 init_remote_threadtests ();
12922 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
12923 /* set/show remote ... */
12925 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12926 Remote protocol specific variables\n\
12927 Configure various remote-protocol specific variables such as\n\
12928 the packets being used"),
12929 &remote_set_cmdlist, "set remote ",
12930 0 /* allow-unknown */, &setlist);
12931 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12932 Remote protocol specific variables\n\
12933 Configure various remote-protocol specific variables such as\n\
12934 the packets being used"),
12935 &remote_show_cmdlist, "show remote ",
12936 0 /* allow-unknown */, &showlist);
12938 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12939 Compare section data on target to the exec file.\n\
12940 Argument is a single section name (default: all loaded sections).\n\
12941 To compare only read-only loaded sections, specify the -r option."),
12944 add_cmd ("packet", class_maintenance, packet_command, _("\
12945 Send an arbitrary packet to a remote target.\n\
12946 maintenance packet TEXT\n\
12947 If GDB is talking to an inferior via the GDB serial protocol, then\n\
12948 this command sends the string TEXT to the inferior, and displays the\n\
12949 response packet. GDB supplies the initial `$' character, and the\n\
12950 terminating `#' character and checksum."),
12953 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12954 Set whether to send break if interrupted."), _("\
12955 Show whether to send break if interrupted."), _("\
12956 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12957 set_remotebreak, show_remotebreak,
12958 &setlist, &showlist);
12959 cmd_name = "remotebreak";
12960 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12961 deprecate_cmd (cmd, "set remote interrupt-sequence");
12962 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12963 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12964 deprecate_cmd (cmd, "show remote interrupt-sequence");
12966 add_setshow_enum_cmd ("interrupt-sequence", class_support,
12967 interrupt_sequence_modes, &interrupt_sequence_mode,
12969 Set interrupt sequence to remote target."), _("\
12970 Show interrupt sequence to remote target."), _("\
12971 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12972 NULL, show_interrupt_sequence,
12973 &remote_set_cmdlist,
12974 &remote_show_cmdlist);
12976 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12977 &interrupt_on_connect, _("\
12978 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12979 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12980 If set, interrupt sequence is sent to remote target."),
12982 &remote_set_cmdlist, &remote_show_cmdlist);
12984 /* Install commands for configuring memory read/write packets. */
12986 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12987 Set the maximum number of bytes per memory write packet (deprecated)."),
12989 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12990 Show the maximum number of bytes per memory write packet (deprecated)."),
12992 add_cmd ("memory-write-packet-size", no_class,
12993 set_memory_write_packet_size, _("\
12994 Set the maximum number of bytes per memory-write packet.\n\
12995 Specify the number of bytes in a packet or 0 (zero) for the\n\
12996 default packet size. The actual limit is further reduced\n\
12997 dependent on the target. Specify ``fixed'' to disable the\n\
12998 further restriction and ``limit'' to enable that restriction."),
12999 &remote_set_cmdlist);
13000 add_cmd ("memory-read-packet-size", no_class,
13001 set_memory_read_packet_size, _("\
13002 Set the maximum number of bytes per memory-read packet.\n\
13003 Specify the number of bytes in a packet or 0 (zero) for the\n\
13004 default packet size. The actual limit is further reduced\n\
13005 dependent on the target. Specify ``fixed'' to disable the\n\
13006 further restriction and ``limit'' to enable that restriction."),
13007 &remote_set_cmdlist);
13008 add_cmd ("memory-write-packet-size", no_class,
13009 show_memory_write_packet_size,
13010 _("Show the maximum number of bytes per memory-write packet."),
13011 &remote_show_cmdlist);
13012 add_cmd ("memory-read-packet-size", no_class,
13013 show_memory_read_packet_size,
13014 _("Show the maximum number of bytes per memory-read packet."),
13015 &remote_show_cmdlist);
13017 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13018 &remote_hw_watchpoint_limit, _("\
13019 Set the maximum number of target hardware watchpoints."), _("\
13020 Show the maximum number of target hardware watchpoints."), _("\
13021 Specify a negative limit for unlimited."),
13022 NULL, NULL, /* FIXME: i18n: The maximum
13023 number of target hardware
13024 watchpoints is %s. */
13025 &remote_set_cmdlist, &remote_show_cmdlist);
13026 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13027 &remote_hw_watchpoint_length_limit, _("\
13028 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13029 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13030 Specify a negative limit for unlimited."),
13031 NULL, NULL, /* FIXME: i18n: The maximum
13032 length (in bytes) of a target
13033 hardware watchpoint is %s. */
13034 &remote_set_cmdlist, &remote_show_cmdlist);
13035 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13036 &remote_hw_breakpoint_limit, _("\
13037 Set the maximum number of target hardware breakpoints."), _("\
13038 Show the maximum number of target hardware breakpoints."), _("\
13039 Specify a negative limit for unlimited."),
13040 NULL, NULL, /* FIXME: i18n: The maximum
13041 number of target hardware
13042 breakpoints is %s. */
13043 &remote_set_cmdlist, &remote_show_cmdlist);
13045 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13046 &remote_address_size, _("\
13047 Set the maximum size of the address (in bits) in a memory packet."), _("\
13048 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13050 NULL, /* FIXME: i18n: */
13051 &setlist, &showlist);
13053 init_all_packet_configs ();
13055 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13056 "X", "binary-download", 1);
13058 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13059 "vCont", "verbose-resume", 0);
13061 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13062 "QPassSignals", "pass-signals", 0);
13064 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13065 "QProgramSignals", "program-signals", 0);
13067 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13068 "qSymbol", "symbol-lookup", 0);
13070 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13071 "P", "set-register", 1);
13073 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13074 "p", "fetch-register", 1);
13076 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13077 "Z0", "software-breakpoint", 0);
13079 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13080 "Z1", "hardware-breakpoint", 0);
13082 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13083 "Z2", "write-watchpoint", 0);
13085 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13086 "Z3", "read-watchpoint", 0);
13088 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13089 "Z4", "access-watchpoint", 0);
13091 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13092 "qXfer:auxv:read", "read-aux-vector", 0);
13094 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13095 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13097 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13098 "qXfer:features:read", "target-features", 0);
13100 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13101 "qXfer:libraries:read", "library-info", 0);
13103 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13104 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13106 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13107 "qXfer:memory-map:read", "memory-map", 0);
13109 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13110 "qXfer:spu:read", "read-spu-object", 0);
13112 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13113 "qXfer:spu:write", "write-spu-object", 0);
13115 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13116 "qXfer:osdata:read", "osdata", 0);
13118 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13119 "qXfer:threads:read", "threads", 0);
13121 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13122 "qXfer:siginfo:read", "read-siginfo-object", 0);
13124 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13125 "qXfer:siginfo:write", "write-siginfo-object", 0);
13127 add_packet_config_cmd
13128 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13129 "qXfer:traceframe-info:read", "traceframe-info", 0);
13131 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13132 "qXfer:uib:read", "unwind-info-block", 0);
13134 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13135 "qGetTLSAddr", "get-thread-local-storage-address",
13138 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13139 "qGetTIBAddr", "get-thread-information-block-address",
13142 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13143 "bc", "reverse-continue", 0);
13145 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13146 "bs", "reverse-step", 0);
13148 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13149 "qSupported", "supported-packets", 0);
13151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13152 "qSearch:memory", "search-memory", 0);
13154 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13155 "qTStatus", "trace-status", 0);
13157 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13158 "vFile:setfs", "hostio-setfs", 0);
13160 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13161 "vFile:open", "hostio-open", 0);
13163 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13164 "vFile:pread", "hostio-pread", 0);
13166 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13167 "vFile:pwrite", "hostio-pwrite", 0);
13169 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13170 "vFile:close", "hostio-close", 0);
13172 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13173 "vFile:unlink", "hostio-unlink", 0);
13175 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13176 "vFile:readlink", "hostio-readlink", 0);
13178 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13179 "vFile:fstat", "hostio-fstat", 0);
13181 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13182 "vAttach", "attach", 0);
13184 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13187 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13188 "QStartNoAckMode", "noack", 0);
13190 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13191 "vKill", "kill", 0);
13193 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13194 "qAttached", "query-attached", 0);
13196 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13197 "ConditionalTracepoints",
13198 "conditional-tracepoints", 0);
13200 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13201 "ConditionalBreakpoints",
13202 "conditional-breakpoints", 0);
13204 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13205 "BreakpointCommands",
13206 "breakpoint-commands", 0);
13208 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13209 "FastTracepoints", "fast-tracepoints", 0);
13211 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13212 "TracepointSource", "TracepointSource", 0);
13214 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13215 "QAllow", "allow", 0);
13217 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13218 "StaticTracepoints", "static-tracepoints", 0);
13220 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13221 "InstallInTrace", "install-in-trace", 0);
13223 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13224 "qXfer:statictrace:read", "read-sdata-object", 0);
13226 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13227 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13229 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13230 "QDisableRandomization", "disable-randomization", 0);
13232 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13233 "QAgent", "agent", 0);
13235 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13236 "QTBuffer:size", "trace-buffer-size", 0);
13238 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13239 "Qbtrace:off", "disable-btrace", 0);
13241 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13242 "Qbtrace:bts", "enable-btrace-bts", 0);
13244 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13245 "Qbtrace:pt", "enable-btrace-pt", 0);
13247 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13248 "qXfer:btrace", "read-btrace", 0);
13250 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13251 "qXfer:btrace-conf", "read-btrace-conf", 0);
13253 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13254 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13256 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13257 "multiprocess-feature", "multiprocess-feature", 0);
13259 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13260 "swbreak-feature", "swbreak-feature", 0);
13262 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13263 "hwbreak-feature", "hwbreak-feature", 0);
13265 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13266 "fork-event-feature", "fork-event-feature", 0);
13268 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13269 "vfork-event-feature", "vfork-event-feature", 0);
13271 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13272 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13274 /* Assert that we've registered "set remote foo-packet" commands
13275 for all packet configs. */
13279 for (i = 0; i < PACKET_MAX; i++)
13281 /* Ideally all configs would have a command associated. Some
13282 still don't though. */
13287 case PACKET_QNonStop:
13288 case PACKET_EnableDisableTracepoints_feature:
13289 case PACKET_tracenz_feature:
13290 case PACKET_DisconnectedTracing_feature:
13291 case PACKET_augmented_libraries_svr4_read_feature:
13293 /* Additions to this list need to be well justified:
13294 pre-existing packets are OK; new packets are not. */
13302 /* This catches both forgetting to add a config command, and
13303 forgetting to remove a packet from the exception list. */
13304 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13308 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13309 Z sub-packet has its own set and show commands, but users may
13310 have sets to this variable in their .gdbinit files (or in their
13312 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13313 &remote_Z_packet_detect, _("\
13314 Set use of remote protocol `Z' packets"), _("\
13315 Show use of remote protocol `Z' packets "), _("\
13316 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13318 set_remote_protocol_Z_packet_cmd,
13319 show_remote_protocol_Z_packet_cmd,
13320 /* FIXME: i18n: Use of remote protocol
13321 `Z' packets is %s. */
13322 &remote_set_cmdlist, &remote_show_cmdlist);
13324 add_prefix_cmd ("remote", class_files, remote_command, _("\
13325 Manipulate files on the remote system\n\
13326 Transfer files to and from the remote target system."),
13327 &remote_cmdlist, "remote ",
13328 0 /* allow-unknown */, &cmdlist);
13330 add_cmd ("put", class_files, remote_put_command,
13331 _("Copy a local file to the remote system."),
13334 add_cmd ("get", class_files, remote_get_command,
13335 _("Copy a remote file to the local system."),
13338 add_cmd ("delete", class_files, remote_delete_command,
13339 _("Delete a remote file."),
13342 remote_exec_file = xstrdup ("");
13343 add_setshow_string_noescape_cmd ("exec-file", class_files,
13344 &remote_exec_file, _("\
13345 Set the remote pathname for \"run\""), _("\
13346 Show the remote pathname for \"run\""), NULL, NULL, NULL,
13347 &remote_set_cmdlist, &remote_show_cmdlist);
13349 add_setshow_boolean_cmd ("range-stepping", class_run,
13350 &use_range_stepping, _("\
13351 Enable or disable range stepping."), _("\
13352 Show whether target-assisted range stepping is enabled."), _("\
13353 If on, and the target supports it, when stepping a source line, GDB\n\
13354 tells the target to step the corresponding range of addresses itself instead\n\
13355 of issuing multiple single-steps. This speeds up source level\n\
13356 stepping. If off, GDB always issues single-steps, even if range\n\
13357 stepping is supported by the target. The default is on."),
13358 set_range_stepping,
13359 show_range_stepping,
13363 /* Eventually initialize fileio. See fileio.c */
13364 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13366 /* Take advantage of the fact that the TID field is not used, to tag
13367 special ptids with it set to != 0. */
13368 magic_null_ptid = ptid_build (42000, -1, 1);
13369 not_sent_ptid = ptid_build (42000, -2, 1);
13370 any_thread_ptid = ptid_build (42000, 0, 1);
13372 target_buf_size = 2048;
13373 target_buf = xmalloc (target_buf_size);