1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2013 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
23 #include "gdb_string.h"
29 #include "exceptions.h"
31 /*#include "terminal.h" */
34 #include "gdb-stabs.h"
35 #include "gdbthread.h"
37 #include "remote-notif.h"
40 #include "gdb_assert.h"
43 #include "cli/cli-decode.h"
44 #include "cli/cli-setshow.h"
45 #include "target-descriptions.h"
47 #include "filestuff.h"
52 #include "event-loop.h"
53 #include "event-top.h"
59 #include "gdbcore.h" /* for exec_bfd */
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
74 /* Temp hacks for tracepoint encoding migration. */
75 static char *target_buf;
76 static long target_buf_size;
78 /* The size to align memory write packets, when practical. The protocol
79 does not guarantee any alignment, and gdb will generate short
80 writes and unaligned writes, but even as a best-effort attempt this
81 can improve bulk transfers. For instance, if a write is misaligned
82 relative to the target's data bus, the stub may need to make an extra
83 round trip fetching data from the target. This doesn't make a
84 huge difference, but it's easy to do, so we try to be helpful.
86 The alignment chosen is arbitrary; usually data bus width is
87 important here, not the possibly larger cache line size. */
88 enum { REMOTE_ALIGN_WRITES = 16 };
90 /* Prototypes for local functions. */
91 static void async_cleanup_sigint_signal_handler (void *dummy);
92 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
93 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
94 int forever, int *is_notif);
96 static void async_handle_remote_sigint (int);
97 static void async_handle_remote_sigint_twice (int);
99 static void remote_files_info (struct target_ops *ignore);
101 static void remote_prepare_to_store (struct regcache *regcache);
103 static void remote_open (char *name, int from_tty);
105 static void extended_remote_open (char *name, int from_tty);
107 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
109 static void remote_close (void);
111 static void remote_mourn (struct target_ops *ops);
113 static void extended_remote_restart (void);
115 static void extended_remote_mourn (struct target_ops *);
117 static void remote_mourn_1 (struct target_ops *);
119 static void remote_send (char **buf, long *sizeof_buf_p);
121 static int readchar (int timeout);
123 static void remote_serial_write (const char *str, int len);
125 static void remote_kill (struct target_ops *ops);
127 static int tohex (int nib);
129 static int remote_can_async_p (void);
131 static int remote_is_async_p (void);
133 static void remote_async (void (*callback) (enum inferior_event_type event_type,
134 void *context), void *context);
136 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
138 static void sync_remote_interrupt_twice (int signo);
140 static void interrupt_query (void);
142 static void set_general_thread (struct ptid ptid);
143 static void set_continue_thread (struct ptid ptid);
145 static void get_offsets (void);
147 static void skip_frame (void);
149 static long read_frame (char **buf_p, long *sizeof_buf);
151 static int hexnumlen (ULONGEST num);
153 static void init_remote_ops (void);
155 static void init_extended_remote_ops (void);
157 static void remote_stop (ptid_t);
159 static int ishex (int ch, int *val);
161 static int stubhex (int ch);
163 static int hexnumstr (char *, ULONGEST);
165 static int hexnumnstr (char *, ULONGEST, int);
167 static CORE_ADDR remote_address_masked (CORE_ADDR);
169 static void print_packet (char *);
171 static void compare_sections_command (char *, int);
173 static void packet_command (char *, int);
175 static int stub_unpack_int (char *buff, int fieldlength);
177 static ptid_t remote_current_thread (ptid_t oldptid);
179 static void remote_find_new_threads (void);
181 static int fromhex (int a);
183 static int putpkt_binary (char *buf, int cnt);
185 static void check_binary_download (CORE_ADDR addr);
187 struct packet_config;
189 static void show_packet_config_cmd (struct packet_config *config);
191 static void update_packet_config (struct packet_config *config);
193 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
194 struct cmd_list_element *c);
196 static void show_remote_protocol_packet_cmd (struct ui_file *file,
198 struct cmd_list_element *c,
201 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
202 static ptid_t read_ptid (char *buf, char **obuf);
204 static void remote_set_permissions (void);
207 static int remote_get_trace_status (struct trace_status *ts);
209 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
211 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
213 static void remote_query_supported (void);
215 static void remote_check_symbols (void);
217 void _initialize_remote (void);
220 static void stop_reply_xfree (struct stop_reply *);
221 static void remote_parse_stop_reply (char *, struct stop_reply *);
222 static void push_stop_reply (struct stop_reply *);
223 static void discard_pending_stop_replies_in_queue (struct remote_state *);
224 static int peek_stop_reply (ptid_t ptid);
226 static void remote_async_inferior_event_handler (gdb_client_data);
228 static void remote_terminal_ours (void);
230 static int remote_read_description_p (struct target_ops *target);
232 static void remote_console_output (char *msg);
234 static int remote_supports_cond_breakpoints (void);
236 static int remote_can_run_breakpoint_commands (void);
240 static struct cmd_list_element *remote_cmdlist;
242 /* For "set remote" and "show remote". */
244 static struct cmd_list_element *remote_set_cmdlist;
245 static struct cmd_list_element *remote_show_cmdlist;
247 /* Stub vCont actions support.
249 Each field is a boolean flag indicating whether the stub reports
250 support for the corresponding action. */
252 struct vCont_action_support
261 /* Controls whether GDB is willing to use range stepping. */
263 static int use_range_stepping = 1;
265 #define OPAQUETHREADBYTES 8
267 /* a 64 bit opaque identifier */
268 typedef unsigned char threadref[OPAQUETHREADBYTES];
270 /* About this many threadisds fit in a packet. */
272 #define MAXTHREADLISTRESULTS 32
274 /* Description of the remote protocol state for the currently
275 connected target. This is per-target state, and independent of the
276 selected architecture. */
280 /* A buffer to use for incoming packets, and its current size. The
281 buffer is grown dynamically for larger incoming packets.
282 Outgoing packets may also be constructed in this buffer.
283 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
284 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
289 /* True if we're going through initial connection setup (finding out
290 about the remote side's threads, relocating symbols, etc.). */
293 /* If we negotiated packet size explicitly (and thus can bypass
294 heuristics for the largest packet size that will not overflow
295 a buffer in the stub), this will be set to that packet size.
296 Otherwise zero, meaning to use the guessed size. */
297 long explicit_packet_size;
299 /* remote_wait is normally called when the target is running and
300 waits for a stop reply packet. But sometimes we need to call it
301 when the target is already stopped. We can send a "?" packet
302 and have remote_wait read the response. Or, if we already have
303 the response, we can stash it in BUF and tell remote_wait to
304 skip calling getpkt. This flag is set when BUF contains a
305 stop reply packet and the target is not waiting. */
306 int cached_wait_status;
308 /* True, if in no ack mode. That is, neither GDB nor the stub will
309 expect acks from each other. The connection is assumed to be
313 /* True if we're connected in extended remote mode. */
316 /* True if the stub reported support for multi-process
318 int multi_process_aware;
320 /* True if we resumed the target and we're waiting for the target to
321 stop. In the mean time, we can't start another command/query.
322 The remote server wouldn't be ready to process it, so we'd
323 timeout waiting for a reply that would never come and eventually
324 we'd close the connection. This can happen in asynchronous mode
325 because we allow GDB commands while the target is running. */
326 int waiting_for_stop_reply;
328 /* True if the stub reports support for non-stop mode. */
331 /* The status of the stub support for the various vCont actions. */
332 struct vCont_action_support supports_vCont;
334 /* True if the stub reports support for conditional tracepoints. */
335 int cond_tracepoints;
337 /* True if the stub reports support for target-side breakpoint
339 int cond_breakpoints;
341 /* True if the stub reports support for target-side breakpoint
343 int breakpoint_commands;
345 /* True if the stub reports support for fast tracepoints. */
346 int fast_tracepoints;
348 /* True if the stub reports support for static tracepoints. */
349 int static_tracepoints;
351 /* True if the stub reports support for installing tracepoint while
353 int install_in_trace;
355 /* True if the stub can continue running a trace while GDB is
357 int disconnected_tracing;
359 /* True if the stub reports support for enabling and disabling
360 tracepoints while a trace experiment is running. */
361 int enable_disable_tracepoints;
363 /* True if the stub can collect strings using tracenz bytecode. */
366 /* True if the stub supports qXfer:libraries-svr4:read with a
368 int augmented_libraries_svr4_read;
370 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
371 responded to that. */
374 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
375 remote_open knows that we don't have a file open when the program
377 struct serial *remote_desc;
379 /* These are the threads which we last sent to the remote system. The
380 TID member will be -1 for all or -2 for not sent yet. */
381 ptid_t general_thread;
382 ptid_t continue_thread;
384 /* This is the traceframe which we last selected on the remote system.
385 It will be -1 if no traceframe is selected. */
386 int remote_traceframe_number;
388 char *last_pass_packet;
390 /* The last QProgramSignals packet sent to the target. We bypass
391 sending a new program signals list down to the target if the new
392 packet is exactly the same as the last we sent. IOW, we only let
393 the target know about program signals list changes. */
394 char *last_program_signals_packet;
396 enum gdb_signal last_sent_signal;
400 char *finished_object;
401 char *finished_annex;
402 ULONGEST finished_offset;
404 /* Should we try the 'ThreadInfo' query packet?
406 This variable (NOT available to the user: auto-detect only!)
407 determines whether GDB will use the new, simpler "ThreadInfo"
408 query or the older, more complex syntax for thread queries.
409 This is an auto-detect variable (set to true at each connect,
410 and set to false when the target fails to recognize it). */
411 int use_threadinfo_query;
412 int use_threadextra_query;
414 void (*async_client_callback) (enum inferior_event_type event_type,
416 void *async_client_context;
418 /* This is set to the data address of the access causing the target
419 to stop for a watchpoint. */
420 CORE_ADDR remote_watch_data_address;
422 /* This is non-zero if target stopped for a watchpoint. */
423 int remote_stopped_by_watchpoint_p;
425 threadref echo_nextthread;
426 threadref nextthread;
427 threadref resultthreadlist[MAXTHREADLISTRESULTS];
429 /* The state of remote notification. */
430 struct remote_notif_state *notif_state;
433 /* Private data that we'll store in (struct thread_info)->private. */
434 struct private_thread_info
441 free_private_thread_info (struct private_thread_info *info)
447 /* Returns true if the multi-process extensions are in effect. */
449 remote_multi_process_p (struct remote_state *rs)
451 return rs->multi_process_aware;
454 /* This data could be associated with a target, but we do not always
455 have access to the current target when we need it, so for now it is
456 static. This will be fine for as long as only one target is in use
458 static struct remote_state *remote_state;
460 static struct remote_state *
461 get_remote_state_raw (void)
466 /* Allocate a new struct remote_state with xmalloc, initialize it, and
469 static struct remote_state *
470 new_remote_state (void)
472 struct remote_state *result = XCNEW (struct remote_state);
474 /* The default buffer size is unimportant; it will be expanded
475 whenever a larger buffer is needed. */
476 result->buf_size = 400;
477 result->buf = xmalloc (result->buf_size);
478 result->remote_traceframe_number = -1;
479 result->last_sent_signal = GDB_SIGNAL_0;
484 /* Description of the remote protocol for a given architecture. */
488 long offset; /* Offset into G packet. */
489 long regnum; /* GDB's internal register number. */
490 LONGEST pnum; /* Remote protocol register number. */
491 int in_g_packet; /* Always part of G packet. */
492 /* long size in bytes; == register_size (target_gdbarch (), regnum);
494 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
498 struct remote_arch_state
500 /* Description of the remote protocol registers. */
501 long sizeof_g_packet;
503 /* Description of the remote protocol registers indexed by REGNUM
504 (making an array gdbarch_num_regs in size). */
505 struct packet_reg *regs;
507 /* This is the size (in chars) of the first response to the ``g''
508 packet. It is used as a heuristic when determining the maximum
509 size of memory-read and memory-write packets. A target will
510 typically only reserve a buffer large enough to hold the ``g''
511 packet. The size does not include packet overhead (headers and
513 long actual_register_packet_size;
515 /* This is the maximum size (in chars) of a non read/write packet.
516 It is also used as a cap on the size of read/write packets. */
517 long remote_packet_size;
520 /* Utility: generate error from an incoming stub packet. */
522 trace_error (char *buf)
525 return; /* not an error msg */
528 case '1': /* malformed packet error */
529 if (*++buf == '0') /* general case: */
530 error (_("remote.c: error in outgoing packet."));
532 error (_("remote.c: error in outgoing packet at field #%ld."),
533 strtol (buf, NULL, 16));
535 error (_("Target returns error code '%s'."), buf);
539 /* Utility: wait for reply from stub, while accepting "O" packets. */
541 remote_get_noisy_reply (char **buf_p,
544 do /* Loop on reply from remote stub. */
548 QUIT; /* Allow user to bail out with ^C. */
549 getpkt (buf_p, sizeof_buf, 0);
553 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
556 CORE_ADDR from, to, org_to;
558 int adjusted_size = 0;
559 volatile struct gdb_exception ex;
561 p = buf + strlen ("qRelocInsn:");
562 pp = unpack_varlen_hex (p, &ul);
564 error (_("invalid qRelocInsn packet: %s"), buf);
568 unpack_varlen_hex (p, &ul);
573 TRY_CATCH (ex, RETURN_MASK_ALL)
575 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
579 adjusted_size = to - org_to;
581 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
584 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
586 /* Propagate memory errors silently back to the target.
587 The stub may have limited the range of addresses we
588 can write to, for example. */
593 /* Something unexpectedly bad happened. Be verbose so
594 we can tell what, and propagate the error back to the
595 stub, so it doesn't get stuck waiting for a
597 exception_fprintf (gdb_stderr, ex,
598 _("warning: relocating instruction: "));
602 else if (buf[0] == 'O' && buf[1] != 'K')
603 remote_console_output (buf + 1); /* 'O' message from stub */
605 return buf; /* Here's the actual reply. */
610 /* Handle for retreving the remote protocol data from gdbarch. */
611 static struct gdbarch_data *remote_gdbarch_data_handle;
613 static struct remote_arch_state *
614 get_remote_arch_state (void)
616 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
619 /* Fetch the global remote target state. */
621 static struct remote_state *
622 get_remote_state (void)
624 /* Make sure that the remote architecture state has been
625 initialized, because doing so might reallocate rs->buf. Any
626 function which calls getpkt also needs to be mindful of changes
627 to rs->buf, but this call limits the number of places which run
629 get_remote_arch_state ();
631 return get_remote_state_raw ();
635 compare_pnums (const void *lhs_, const void *rhs_)
637 const struct packet_reg * const *lhs = lhs_;
638 const struct packet_reg * const *rhs = rhs_;
640 if ((*lhs)->pnum < (*rhs)->pnum)
642 else if ((*lhs)->pnum == (*rhs)->pnum)
649 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
651 int regnum, num_remote_regs, offset;
652 struct packet_reg **remote_regs;
654 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
656 struct packet_reg *r = ®s[regnum];
658 if (register_size (gdbarch, regnum) == 0)
659 /* Do not try to fetch zero-sized (placeholder) registers. */
662 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
667 /* Define the g/G packet format as the contents of each register
668 with a remote protocol number, in order of ascending protocol
671 remote_regs = alloca (gdbarch_num_regs (gdbarch)
672 * sizeof (struct packet_reg *));
673 for (num_remote_regs = 0, regnum = 0;
674 regnum < gdbarch_num_regs (gdbarch);
676 if (regs[regnum].pnum != -1)
677 remote_regs[num_remote_regs++] = ®s[regnum];
679 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
682 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
684 remote_regs[regnum]->in_g_packet = 1;
685 remote_regs[regnum]->offset = offset;
686 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
692 /* Given the architecture described by GDBARCH, return the remote
693 protocol register's number and the register's offset in the g/G
694 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
695 If the target does not have a mapping for REGNUM, return false,
696 otherwise, return true. */
699 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
700 int *pnum, int *poffset)
703 struct packet_reg *regs;
704 struct cleanup *old_chain;
706 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
708 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
709 old_chain = make_cleanup (xfree, regs);
711 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
713 *pnum = regs[regnum].pnum;
714 *poffset = regs[regnum].offset;
716 do_cleanups (old_chain);
722 init_remote_state (struct gdbarch *gdbarch)
724 struct remote_state *rs = get_remote_state_raw ();
725 struct remote_arch_state *rsa;
727 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
729 /* Use the architecture to build a regnum<->pnum table, which will be
730 1:1 unless a feature set specifies otherwise. */
731 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
732 gdbarch_num_regs (gdbarch),
735 /* Record the maximum possible size of the g packet - it may turn out
737 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
739 /* Default maximum number of characters in a packet body. Many
740 remote stubs have a hardwired buffer size of 400 bytes
741 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
742 as the maximum packet-size to ensure that the packet and an extra
743 NUL character can always fit in the buffer. This stops GDB
744 trashing stubs that try to squeeze an extra NUL into what is
745 already a full buffer (As of 1999-12-04 that was most stubs). */
746 rsa->remote_packet_size = 400 - 1;
748 /* This one is filled in when a ``g'' packet is received. */
749 rsa->actual_register_packet_size = 0;
751 /* Should rsa->sizeof_g_packet needs more space than the
752 default, adjust the size accordingly. Remember that each byte is
753 encoded as two characters. 32 is the overhead for the packet
754 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
755 (``$NN:G...#NN'') is a better guess, the below has been padded a
757 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
758 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
760 /* Make sure that the packet buffer is plenty big enough for
761 this architecture. */
762 if (rs->buf_size < rsa->remote_packet_size)
764 rs->buf_size = 2 * rsa->remote_packet_size;
765 rs->buf = xrealloc (rs->buf, rs->buf_size);
771 /* Return the current allowed size of a remote packet. This is
772 inferred from the current architecture, and should be used to
773 limit the length of outgoing packets. */
775 get_remote_packet_size (void)
777 struct remote_state *rs = get_remote_state ();
778 struct remote_arch_state *rsa = get_remote_arch_state ();
780 if (rs->explicit_packet_size)
781 return rs->explicit_packet_size;
783 return rsa->remote_packet_size;
786 static struct packet_reg *
787 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
789 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
793 struct packet_reg *r = &rsa->regs[regnum];
795 gdb_assert (r->regnum == regnum);
800 static struct packet_reg *
801 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
805 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
807 struct packet_reg *r = &rsa->regs[i];
815 static struct target_ops remote_ops;
817 static struct target_ops extended_remote_ops;
819 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
820 ``forever'' still use the normal timeout mechanism. This is
821 currently used by the ASYNC code to guarentee that target reads
822 during the initial connect always time-out. Once getpkt has been
823 modified to return a timeout indication and, in turn
824 remote_wait()/wait_for_inferior() have gained a timeout parameter
826 static int wait_forever_enabled_p = 1;
828 /* Allow the user to specify what sequence to send to the remote
829 when he requests a program interruption: Although ^C is usually
830 what remote systems expect (this is the default, here), it is
831 sometimes preferable to send a break. On other systems such
832 as the Linux kernel, a break followed by g, which is Magic SysRq g
833 is required in order to interrupt the execution. */
834 const char interrupt_sequence_control_c[] = "Ctrl-C";
835 const char interrupt_sequence_break[] = "BREAK";
836 const char interrupt_sequence_break_g[] = "BREAK-g";
837 static const char *const interrupt_sequence_modes[] =
839 interrupt_sequence_control_c,
840 interrupt_sequence_break,
841 interrupt_sequence_break_g,
844 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
847 show_interrupt_sequence (struct ui_file *file, int from_tty,
848 struct cmd_list_element *c,
851 if (interrupt_sequence_mode == interrupt_sequence_control_c)
852 fprintf_filtered (file,
853 _("Send the ASCII ETX character (Ctrl-c) "
854 "to the remote target to interrupt the "
855 "execution of the program.\n"));
856 else if (interrupt_sequence_mode == interrupt_sequence_break)
857 fprintf_filtered (file,
858 _("send a break signal to the remote target "
859 "to interrupt the execution of the program.\n"));
860 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
861 fprintf_filtered (file,
862 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
863 "the remote target to interrupt the execution "
864 "of Linux kernel.\n"));
866 internal_error (__FILE__, __LINE__,
867 _("Invalid value for interrupt_sequence_mode: %s."),
868 interrupt_sequence_mode);
871 /* This boolean variable specifies whether interrupt_sequence is sent
872 to the remote target when gdb connects to it.
873 This is mostly needed when you debug the Linux kernel: The Linux kernel
874 expects BREAK g which is Magic SysRq g for connecting gdb. */
875 static int interrupt_on_connect = 0;
877 /* This variable is used to implement the "set/show remotebreak" commands.
878 Since these commands are now deprecated in favor of "set/show remote
879 interrupt-sequence", it no longer has any effect on the code. */
880 static int remote_break;
883 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
886 interrupt_sequence_mode = interrupt_sequence_break;
888 interrupt_sequence_mode = interrupt_sequence_control_c;
892 show_remotebreak (struct ui_file *file, int from_tty,
893 struct cmd_list_element *c,
898 /* This variable sets the number of bits in an address that are to be
899 sent in a memory ("M" or "m") packet. Normally, after stripping
900 leading zeros, the entire address would be sent. This variable
901 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
902 initial implementation of remote.c restricted the address sent in
903 memory packets to ``host::sizeof long'' bytes - (typically 32
904 bits). Consequently, for 64 bit targets, the upper 32 bits of an
905 address was never sent. Since fixing this bug may cause a break in
906 some remote targets this variable is principly provided to
907 facilitate backward compatibility. */
909 static unsigned int remote_address_size;
911 /* Temporary to track who currently owns the terminal. See
912 remote_terminal_* for more details. */
914 static int remote_async_terminal_ours_p;
916 /* The executable file to use for "run" on the remote side. */
918 static char *remote_exec_file = "";
921 /* User configurable variables for the number of characters in a
922 memory read/write packet. MIN (rsa->remote_packet_size,
923 rsa->sizeof_g_packet) is the default. Some targets need smaller
924 values (fifo overruns, et.al.) and some users need larger values
925 (speed up transfers). The variables ``preferred_*'' (the user
926 request), ``current_*'' (what was actually set) and ``forced_*''
927 (Positive - a soft limit, negative - a hard limit). */
929 struct memory_packet_config
936 /* Compute the current size of a read/write packet. Since this makes
937 use of ``actual_register_packet_size'' the computation is dynamic. */
940 get_memory_packet_size (struct memory_packet_config *config)
942 struct remote_state *rs = get_remote_state ();
943 struct remote_arch_state *rsa = get_remote_arch_state ();
945 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
946 law?) that some hosts don't cope very well with large alloca()
947 calls. Eventually the alloca() code will be replaced by calls to
948 xmalloc() and make_cleanups() allowing this restriction to either
949 be lifted or removed. */
950 #ifndef MAX_REMOTE_PACKET_SIZE
951 #define MAX_REMOTE_PACKET_SIZE 16384
953 /* NOTE: 20 ensures we can write at least one byte. */
954 #ifndef MIN_REMOTE_PACKET_SIZE
955 #define MIN_REMOTE_PACKET_SIZE 20
960 if (config->size <= 0)
961 what_they_get = MAX_REMOTE_PACKET_SIZE;
963 what_they_get = config->size;
967 what_they_get = get_remote_packet_size ();
968 /* Limit the packet to the size specified by the user. */
970 && what_they_get > config->size)
971 what_they_get = config->size;
973 /* Limit it to the size of the targets ``g'' response unless we have
974 permission from the stub to use a larger packet size. */
975 if (rs->explicit_packet_size == 0
976 && rsa->actual_register_packet_size > 0
977 && what_they_get > rsa->actual_register_packet_size)
978 what_they_get = rsa->actual_register_packet_size;
980 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
981 what_they_get = MAX_REMOTE_PACKET_SIZE;
982 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
983 what_they_get = MIN_REMOTE_PACKET_SIZE;
985 /* Make sure there is room in the global buffer for this packet
986 (including its trailing NUL byte). */
987 if (rs->buf_size < what_they_get + 1)
989 rs->buf_size = 2 * what_they_get;
990 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
993 return what_they_get;
996 /* Update the size of a read/write packet. If they user wants
997 something really big then do a sanity check. */
1000 set_memory_packet_size (char *args, struct memory_packet_config *config)
1002 int fixed_p = config->fixed_p;
1003 long size = config->size;
1006 error (_("Argument required (integer, `fixed' or `limited')."));
1007 else if (strcmp (args, "hard") == 0
1008 || strcmp (args, "fixed") == 0)
1010 else if (strcmp (args, "soft") == 0
1011 || strcmp (args, "limit") == 0)
1017 size = strtoul (args, &end, 0);
1019 error (_("Invalid %s (bad syntax)."), config->name);
1021 /* Instead of explicitly capping the size of a packet to
1022 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
1023 instead allowed to set the size to something arbitrarily
1025 if (size > MAX_REMOTE_PACKET_SIZE)
1026 error (_("Invalid %s (too large)."), config->name);
1030 if (fixed_p && !config->fixed_p)
1032 if (! query (_("The target may not be able to correctly handle a %s\n"
1033 "of %ld bytes. Change the packet size? "),
1034 config->name, size))
1035 error (_("Packet size not changed."));
1037 /* Update the config. */
1038 config->fixed_p = fixed_p;
1039 config->size = size;
1043 show_memory_packet_size (struct memory_packet_config *config)
1045 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1046 if (config->fixed_p)
1047 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1048 get_memory_packet_size (config));
1050 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1051 get_memory_packet_size (config));
1054 static struct memory_packet_config memory_write_packet_config =
1056 "memory-write-packet-size",
1060 set_memory_write_packet_size (char *args, int from_tty)
1062 set_memory_packet_size (args, &memory_write_packet_config);
1066 show_memory_write_packet_size (char *args, int from_tty)
1068 show_memory_packet_size (&memory_write_packet_config);
1072 get_memory_write_packet_size (void)
1074 return get_memory_packet_size (&memory_write_packet_config);
1077 static struct memory_packet_config memory_read_packet_config =
1079 "memory-read-packet-size",
1083 set_memory_read_packet_size (char *args, int from_tty)
1085 set_memory_packet_size (args, &memory_read_packet_config);
1089 show_memory_read_packet_size (char *args, int from_tty)
1091 show_memory_packet_size (&memory_read_packet_config);
1095 get_memory_read_packet_size (void)
1097 long size = get_memory_packet_size (&memory_read_packet_config);
1099 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1100 extra buffer size argument before the memory read size can be
1101 increased beyond this. */
1102 if (size > get_remote_packet_size ())
1103 size = get_remote_packet_size ();
1108 /* Generic configuration support for packets the stub optionally
1109 supports. Allows the user to specify the use of the packet as well
1110 as allowing GDB to auto-detect support in the remote stub. */
1114 PACKET_SUPPORT_UNKNOWN = 0,
1119 struct packet_config
1123 enum auto_boolean detect;
1124 enum packet_support support;
1127 /* Analyze a packet's return value and update the packet config
1138 update_packet_config (struct packet_config *config)
1140 switch (config->detect)
1142 case AUTO_BOOLEAN_TRUE:
1143 config->support = PACKET_ENABLE;
1145 case AUTO_BOOLEAN_FALSE:
1146 config->support = PACKET_DISABLE;
1148 case AUTO_BOOLEAN_AUTO:
1149 config->support = PACKET_SUPPORT_UNKNOWN;
1155 show_packet_config_cmd (struct packet_config *config)
1157 char *support = "internal-error";
1159 switch (config->support)
1162 support = "enabled";
1164 case PACKET_DISABLE:
1165 support = "disabled";
1167 case PACKET_SUPPORT_UNKNOWN:
1168 support = "unknown";
1171 switch (config->detect)
1173 case AUTO_BOOLEAN_AUTO:
1174 printf_filtered (_("Support for the `%s' packet "
1175 "is auto-detected, currently %s.\n"),
1176 config->name, support);
1178 case AUTO_BOOLEAN_TRUE:
1179 case AUTO_BOOLEAN_FALSE:
1180 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1181 config->name, support);
1187 add_packet_config_cmd (struct packet_config *config, const char *name,
1188 const char *title, int legacy)
1194 config->name = name;
1195 config->title = title;
1196 config->detect = AUTO_BOOLEAN_AUTO;
1197 config->support = PACKET_SUPPORT_UNKNOWN;
1198 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1200 show_doc = xstrprintf ("Show current use of remote "
1201 "protocol `%s' (%s) packet",
1203 /* set/show TITLE-packet {auto,on,off} */
1204 cmd_name = xstrprintf ("%s-packet", title);
1205 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1206 &config->detect, set_doc,
1207 show_doc, NULL, /* help_doc */
1208 set_remote_protocol_packet_cmd,
1209 show_remote_protocol_packet_cmd,
1210 &remote_set_cmdlist, &remote_show_cmdlist);
1211 /* The command code copies the documentation strings. */
1214 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1219 legacy_name = xstrprintf ("%s-packet", name);
1220 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1221 &remote_set_cmdlist);
1222 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1223 &remote_show_cmdlist);
1227 static enum packet_result
1228 packet_check_result (const char *buf)
1232 /* The stub recognized the packet request. Check that the
1233 operation succeeded. */
1235 && isxdigit (buf[1]) && isxdigit (buf[2])
1237 /* "Enn" - definitly an error. */
1238 return PACKET_ERROR;
1240 /* Always treat "E." as an error. This will be used for
1241 more verbose error messages, such as E.memtypes. */
1242 if (buf[0] == 'E' && buf[1] == '.')
1243 return PACKET_ERROR;
1245 /* The packet may or may not be OK. Just assume it is. */
1249 /* The stub does not support the packet. */
1250 return PACKET_UNKNOWN;
1253 static enum packet_result
1254 packet_ok (const char *buf, struct packet_config *config)
1256 enum packet_result result;
1258 result = packet_check_result (buf);
1263 /* The stub recognized the packet request. */
1264 switch (config->support)
1266 case PACKET_SUPPORT_UNKNOWN:
1268 fprintf_unfiltered (gdb_stdlog,
1269 "Packet %s (%s) is supported\n",
1270 config->name, config->title);
1271 config->support = PACKET_ENABLE;
1273 case PACKET_DISABLE:
1274 internal_error (__FILE__, __LINE__,
1275 _("packet_ok: attempt to use a disabled packet"));
1281 case PACKET_UNKNOWN:
1282 /* The stub does not support the packet. */
1283 switch (config->support)
1286 if (config->detect == AUTO_BOOLEAN_AUTO)
1287 /* If the stub previously indicated that the packet was
1288 supported then there is a protocol error.. */
1289 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1290 config->name, config->title);
1292 /* The user set it wrong. */
1293 error (_("Enabled packet %s (%s) not recognized by stub"),
1294 config->name, config->title);
1296 case PACKET_SUPPORT_UNKNOWN:
1298 fprintf_unfiltered (gdb_stdlog,
1299 "Packet %s (%s) is NOT supported\n",
1300 config->name, config->title);
1301 config->support = PACKET_DISABLE;
1303 case PACKET_DISABLE:
1325 PACKET_vFile_pwrite,
1327 PACKET_vFile_unlink,
1328 PACKET_vFile_readlink,
1330 PACKET_qXfer_features,
1331 PACKET_qXfer_libraries,
1332 PACKET_qXfer_libraries_svr4,
1333 PACKET_qXfer_memory_map,
1334 PACKET_qXfer_spu_read,
1335 PACKET_qXfer_spu_write,
1336 PACKET_qXfer_osdata,
1337 PACKET_qXfer_threads,
1338 PACKET_qXfer_statictrace_read,
1339 PACKET_qXfer_traceframe_info,
1345 PACKET_QPassSignals,
1346 PACKET_QProgramSignals,
1347 PACKET_qSearch_memory,
1350 PACKET_QStartNoAckMode,
1352 PACKET_qXfer_siginfo_read,
1353 PACKET_qXfer_siginfo_write,
1355 PACKET_ConditionalTracepoints,
1356 PACKET_ConditionalBreakpoints,
1357 PACKET_BreakpointCommands,
1358 PACKET_FastTracepoints,
1359 PACKET_StaticTracepoints,
1360 PACKET_InstallInTrace,
1363 PACKET_TracepointSource,
1366 PACKET_QDisableRandomization,
1368 PACKET_QTBuffer_size,
1371 PACKET_qXfer_btrace,
1375 static struct packet_config remote_protocol_packets[PACKET_MAX];
1378 set_remote_protocol_packet_cmd (char *args, int from_tty,
1379 struct cmd_list_element *c)
1381 struct packet_config *packet;
1383 for (packet = remote_protocol_packets;
1384 packet < &remote_protocol_packets[PACKET_MAX];
1387 if (&packet->detect == c->var)
1389 update_packet_config (packet);
1393 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1398 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1399 struct cmd_list_element *c,
1402 struct packet_config *packet;
1404 for (packet = remote_protocol_packets;
1405 packet < &remote_protocol_packets[PACKET_MAX];
1408 if (&packet->detect == c->var)
1410 show_packet_config_cmd (packet);
1414 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1418 /* Should we try one of the 'Z' requests? */
1422 Z_PACKET_SOFTWARE_BP,
1423 Z_PACKET_HARDWARE_BP,
1430 /* For compatibility with older distributions. Provide a ``set remote
1431 Z-packet ...'' command that updates all the Z packet types. */
1433 static enum auto_boolean remote_Z_packet_detect;
1436 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1437 struct cmd_list_element *c)
1441 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1443 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1444 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1449 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1450 struct cmd_list_element *c,
1455 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1457 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1461 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1462 static struct async_signal_handler *async_sigint_remote_twice_token;
1463 static struct async_signal_handler *async_sigint_remote_token;
1466 /* Asynchronous signal handle registered as event loop source for
1467 when we have pending events ready to be passed to the core. */
1469 static struct async_event_handler *remote_async_inferior_event_token;
1473 static ptid_t magic_null_ptid;
1474 static ptid_t not_sent_ptid;
1475 static ptid_t any_thread_ptid;
1477 /* Find out if the stub attached to PID (and hence GDB should offer to
1478 detach instead of killing it when bailing out). */
1481 remote_query_attached (int pid)
1483 struct remote_state *rs = get_remote_state ();
1484 size_t size = get_remote_packet_size ();
1486 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1489 if (remote_multi_process_p (rs))
1490 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1492 xsnprintf (rs->buf, size, "qAttached");
1495 getpkt (&rs->buf, &rs->buf_size, 0);
1497 switch (packet_ok (rs->buf,
1498 &remote_protocol_packets[PACKET_qAttached]))
1501 if (strcmp (rs->buf, "1") == 0)
1505 warning (_("Remote failure reply: %s"), rs->buf);
1507 case PACKET_UNKNOWN:
1514 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1515 has been invented by GDB, instead of reported by the target. Since
1516 we can be connected to a remote system before before knowing about
1517 any inferior, mark the target with execution when we find the first
1518 inferior. If ATTACHED is 1, then we had just attached to this
1519 inferior. If it is 0, then we just created this inferior. If it
1520 is -1, then try querying the remote stub to find out if it had
1521 attached to the inferior or not. */
1523 static struct inferior *
1524 remote_add_inferior (int fake_pid_p, int pid, int attached)
1526 struct inferior *inf;
1528 /* Check whether this process we're learning about is to be
1529 considered attached, or if is to be considered to have been
1530 spawned by the stub. */
1532 attached = remote_query_attached (pid);
1534 if (gdbarch_has_global_solist (target_gdbarch ()))
1536 /* If the target shares code across all inferiors, then every
1537 attach adds a new inferior. */
1538 inf = add_inferior (pid);
1540 /* ... and every inferior is bound to the same program space.
1541 However, each inferior may still have its own address
1543 inf->aspace = maybe_new_address_space ();
1544 inf->pspace = current_program_space;
1548 /* In the traditional debugging scenario, there's a 1-1 match
1549 between program/address spaces. We simply bind the inferior
1550 to the program space's address space. */
1551 inf = current_inferior ();
1552 inferior_appeared (inf, pid);
1555 inf->attach_flag = attached;
1556 inf->fake_pid_p = fake_pid_p;
1561 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1562 according to RUNNING. */
1565 remote_add_thread (ptid_t ptid, int running)
1569 set_executing (ptid, running);
1570 set_running (ptid, running);
1573 /* Come here when we learn about a thread id from the remote target.
1574 It may be the first time we hear about such thread, so take the
1575 opportunity to add it to GDB's thread list. In case this is the
1576 first time we're noticing its corresponding inferior, add it to
1577 GDB's inferior list as well. */
1580 remote_notice_new_inferior (ptid_t currthread, int running)
1582 /* If this is a new thread, add it to GDB's thread list.
1583 If we leave it up to WFI to do this, bad things will happen. */
1585 if (in_thread_list (currthread) && is_exited (currthread))
1587 /* We're seeing an event on a thread id we knew had exited.
1588 This has to be a new thread reusing the old id. Add it. */
1589 remote_add_thread (currthread, running);
1593 if (!in_thread_list (currthread))
1595 struct inferior *inf = NULL;
1596 int pid = ptid_get_pid (currthread);
1598 if (ptid_is_pid (inferior_ptid)
1599 && pid == ptid_get_pid (inferior_ptid))
1601 /* inferior_ptid has no thread member yet. This can happen
1602 with the vAttach -> remote_wait,"TAAthread:" path if the
1603 stub doesn't support qC. This is the first stop reported
1604 after an attach, so this is the main thread. Update the
1605 ptid in the thread list. */
1606 if (in_thread_list (pid_to_ptid (pid)))
1607 thread_change_ptid (inferior_ptid, currthread);
1610 remote_add_thread (currthread, running);
1611 inferior_ptid = currthread;
1616 if (ptid_equal (magic_null_ptid, inferior_ptid))
1618 /* inferior_ptid is not set yet. This can happen with the
1619 vRun -> remote_wait,"TAAthread:" path if the stub
1620 doesn't support qC. This is the first stop reported
1621 after an attach, so this is the main thread. Update the
1622 ptid in the thread list. */
1623 thread_change_ptid (inferior_ptid, currthread);
1627 /* When connecting to a target remote, or to a target
1628 extended-remote which already was debugging an inferior, we
1629 may not know about it yet. Add it before adding its child
1630 thread, so notifications are emitted in a sensible order. */
1631 if (!in_inferior_list (ptid_get_pid (currthread)))
1633 struct remote_state *rs = get_remote_state ();
1634 int fake_pid_p = !remote_multi_process_p (rs);
1636 inf = remote_add_inferior (fake_pid_p,
1637 ptid_get_pid (currthread), -1);
1640 /* This is really a new thread. Add it. */
1641 remote_add_thread (currthread, running);
1643 /* If we found a new inferior, let the common code do whatever
1644 it needs to with it (e.g., read shared libraries, insert
1647 notice_new_inferior (currthread, running, 0);
1651 /* Return the private thread data, creating it if necessary. */
1653 static struct private_thread_info *
1654 demand_private_info (ptid_t ptid)
1656 struct thread_info *info = find_thread_ptid (ptid);
1662 info->private = xmalloc (sizeof (*(info->private)));
1663 info->private_dtor = free_private_thread_info;
1664 info->private->core = -1;
1665 info->private->extra = 0;
1668 return info->private;
1671 /* Call this function as a result of
1672 1) A halt indication (T packet) containing a thread id
1673 2) A direct query of currthread
1674 3) Successful execution of set thread */
1677 record_currthread (struct remote_state *rs, ptid_t currthread)
1679 rs->general_thread = currthread;
1682 /* If 'QPassSignals' is supported, tell the remote stub what signals
1683 it can simply pass through to the inferior without reporting. */
1686 remote_pass_signals (int numsigs, unsigned char *pass_signals)
1688 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1690 char *pass_packet, *p;
1692 struct remote_state *rs = get_remote_state ();
1694 gdb_assert (numsigs < 256);
1695 for (i = 0; i < numsigs; i++)
1697 if (pass_signals[i])
1700 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1701 strcpy (pass_packet, "QPassSignals:");
1702 p = pass_packet + strlen (pass_packet);
1703 for (i = 0; i < numsigs; i++)
1705 if (pass_signals[i])
1708 *p++ = tohex (i >> 4);
1709 *p++ = tohex (i & 15);
1718 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1720 char *buf = rs->buf;
1722 putpkt (pass_packet);
1723 getpkt (&rs->buf, &rs->buf_size, 0);
1724 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1725 if (rs->last_pass_packet)
1726 xfree (rs->last_pass_packet);
1727 rs->last_pass_packet = pass_packet;
1730 xfree (pass_packet);
1734 /* If 'QProgramSignals' is supported, tell the remote stub what
1735 signals it should pass through to the inferior when detaching. */
1738 remote_program_signals (int numsigs, unsigned char *signals)
1740 if (remote_protocol_packets[PACKET_QProgramSignals].support != PACKET_DISABLE)
1744 struct remote_state *rs = get_remote_state ();
1746 gdb_assert (numsigs < 256);
1747 for (i = 0; i < numsigs; i++)
1752 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1753 strcpy (packet, "QProgramSignals:");
1754 p = packet + strlen (packet);
1755 for (i = 0; i < numsigs; i++)
1757 if (signal_pass_state (i))
1760 *p++ = tohex (i >> 4);
1761 *p++ = tohex (i & 15);
1770 if (!rs->last_program_signals_packet
1771 || strcmp (rs->last_program_signals_packet, packet) != 0)
1773 char *buf = rs->buf;
1776 getpkt (&rs->buf, &rs->buf_size, 0);
1777 packet_ok (buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1778 xfree (rs->last_program_signals_packet);
1779 rs->last_program_signals_packet = packet;
1786 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1787 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1788 thread. If GEN is set, set the general thread, if not, then set
1789 the step/continue thread. */
1791 set_thread (struct ptid ptid, int gen)
1793 struct remote_state *rs = get_remote_state ();
1794 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1795 char *buf = rs->buf;
1796 char *endbuf = rs->buf + get_remote_packet_size ();
1798 if (ptid_equal (state, ptid))
1802 *buf++ = gen ? 'g' : 'c';
1803 if (ptid_equal (ptid, magic_null_ptid))
1804 xsnprintf (buf, endbuf - buf, "0");
1805 else if (ptid_equal (ptid, any_thread_ptid))
1806 xsnprintf (buf, endbuf - buf, "0");
1807 else if (ptid_equal (ptid, minus_one_ptid))
1808 xsnprintf (buf, endbuf - buf, "-1");
1810 write_ptid (buf, endbuf, ptid);
1812 getpkt (&rs->buf, &rs->buf_size, 0);
1814 rs->general_thread = ptid;
1816 rs->continue_thread = ptid;
1820 set_general_thread (struct ptid ptid)
1822 set_thread (ptid, 1);
1826 set_continue_thread (struct ptid ptid)
1828 set_thread (ptid, 0);
1831 /* Change the remote current process. Which thread within the process
1832 ends up selected isn't important, as long as it is the same process
1833 as what INFERIOR_PTID points to.
1835 This comes from that fact that there is no explicit notion of
1836 "selected process" in the protocol. The selected process for
1837 general operations is the process the selected general thread
1841 set_general_process (void)
1843 struct remote_state *rs = get_remote_state ();
1845 /* If the remote can't handle multiple processes, don't bother. */
1846 if (!rs->extended || !remote_multi_process_p (rs))
1849 /* We only need to change the remote current thread if it's pointing
1850 at some other process. */
1851 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1852 set_general_thread (inferior_ptid);
1856 /* Return nonzero if the thread PTID is still alive on the remote
1860 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1862 struct remote_state *rs = get_remote_state ();
1865 if (ptid_equal (ptid, magic_null_ptid))
1866 /* The main thread is always alive. */
1869 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1870 /* The main thread is always alive. This can happen after a
1871 vAttach, if the remote side doesn't support
1876 endp = rs->buf + get_remote_packet_size ();
1879 write_ptid (p, endp, ptid);
1882 getpkt (&rs->buf, &rs->buf_size, 0);
1883 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1886 /* About these extended threadlist and threadinfo packets. They are
1887 variable length packets but, the fields within them are often fixed
1888 length. They are redundent enough to send over UDP as is the
1889 remote protocol in general. There is a matching unit test module
1892 /* WARNING: This threadref data structure comes from the remote O.S.,
1893 libstub protocol encoding, and remote.c. It is not particularly
1896 /* Right now, the internal structure is int. We want it to be bigger.
1897 Plan to fix this. */
1899 typedef int gdb_threadref; /* Internal GDB thread reference. */
1901 /* gdb_ext_thread_info is an internal GDB data structure which is
1902 equivalent to the reply of the remote threadinfo packet. */
1904 struct gdb_ext_thread_info
1906 threadref threadid; /* External form of thread reference. */
1907 int active; /* Has state interesting to GDB?
1909 char display[256]; /* Brief state display, name,
1910 blocked/suspended. */
1911 char shortname[32]; /* To be used to name threads. */
1912 char more_display[256]; /* Long info, statistics, queue depth,
1916 /* The volume of remote transfers can be limited by submitting
1917 a mask containing bits specifying the desired information.
1918 Use a union of these values as the 'selection' parameter to
1919 get_thread_info. FIXME: Make these TAG names more thread specific. */
1921 #define TAG_THREADID 1
1922 #define TAG_EXISTS 2
1923 #define TAG_DISPLAY 4
1924 #define TAG_THREADNAME 8
1925 #define TAG_MOREDISPLAY 16
1927 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1929 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1931 static char *unpack_nibble (char *buf, int *val);
1933 static char *pack_nibble (char *buf, int nibble);
1935 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1937 static char *unpack_byte (char *buf, int *value);
1939 static char *pack_int (char *buf, int value);
1941 static char *unpack_int (char *buf, int *value);
1943 static char *unpack_string (char *src, char *dest, int length);
1945 static char *pack_threadid (char *pkt, threadref *id);
1947 static char *unpack_threadid (char *inbuf, threadref *id);
1949 void int_to_threadref (threadref *id, int value);
1951 static int threadref_to_int (threadref *ref);
1953 static void copy_threadref (threadref *dest, threadref *src);
1955 static int threadmatch (threadref *dest, threadref *src);
1957 static char *pack_threadinfo_request (char *pkt, int mode,
1960 static int remote_unpack_thread_info_response (char *pkt,
1961 threadref *expectedref,
1962 struct gdb_ext_thread_info
1966 static int remote_get_threadinfo (threadref *threadid,
1967 int fieldset, /*TAG mask */
1968 struct gdb_ext_thread_info *info);
1970 static char *pack_threadlist_request (char *pkt, int startflag,
1972 threadref *nextthread);
1974 static int parse_threadlist_response (char *pkt,
1976 threadref *original_echo,
1977 threadref *resultlist,
1980 static int remote_get_threadlist (int startflag,
1981 threadref *nextthread,
1985 threadref *threadlist);
1987 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1989 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1990 void *context, int looplimit);
1992 static int remote_newthread_step (threadref *ref, void *context);
1995 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1996 buffer we're allowed to write to. Returns
1997 BUF+CHARACTERS_WRITTEN. */
2000 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2003 struct remote_state *rs = get_remote_state ();
2005 if (remote_multi_process_p (rs))
2007 pid = ptid_get_pid (ptid);
2009 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2011 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2013 tid = ptid_get_tid (ptid);
2015 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2017 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2022 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2023 passed the last parsed char. Returns null_ptid on error. */
2026 read_ptid (char *buf, char **obuf)
2030 ULONGEST pid = 0, tid = 0;
2034 /* Multi-process ptid. */
2035 pp = unpack_varlen_hex (p + 1, &pid);
2037 error (_("invalid remote ptid: %s"), p);
2040 pp = unpack_varlen_hex (p + 1, &tid);
2043 return ptid_build (pid, 0, tid);
2046 /* No multi-process. Just a tid. */
2047 pp = unpack_varlen_hex (p, &tid);
2049 /* Since the stub is not sending a process id, then default to
2050 what's in inferior_ptid, unless it's null at this point. If so,
2051 then since there's no way to know the pid of the reported
2052 threads, use the magic number. */
2053 if (ptid_equal (inferior_ptid, null_ptid))
2054 pid = ptid_get_pid (magic_null_ptid);
2056 pid = ptid_get_pid (inferior_ptid);
2060 return ptid_build (pid, 0, tid);
2063 /* Encode 64 bits in 16 chars of hex. */
2065 static const char hexchars[] = "0123456789abcdef";
2068 ishex (int ch, int *val)
2070 if ((ch >= 'a') && (ch <= 'f'))
2072 *val = ch - 'a' + 10;
2075 if ((ch >= 'A') && (ch <= 'F'))
2077 *val = ch - 'A' + 10;
2080 if ((ch >= '0') && (ch <= '9'))
2091 if (ch >= 'a' && ch <= 'f')
2092 return ch - 'a' + 10;
2093 if (ch >= '0' && ch <= '9')
2095 if (ch >= 'A' && ch <= 'F')
2096 return ch - 'A' + 10;
2101 stub_unpack_int (char *buff, int fieldlength)
2108 nibble = stubhex (*buff++);
2112 retval = retval << 4;
2118 unpack_varlen_hex (char *buff, /* packet to parse */
2122 ULONGEST retval = 0;
2124 while (ishex (*buff, &nibble))
2127 retval = retval << 4;
2128 retval |= nibble & 0x0f;
2135 unpack_nibble (char *buf, int *val)
2137 *val = fromhex (*buf++);
2142 pack_nibble (char *buf, int nibble)
2144 *buf++ = hexchars[(nibble & 0x0f)];
2149 pack_hex_byte (char *pkt, int byte)
2151 *pkt++ = hexchars[(byte >> 4) & 0xf];
2152 *pkt++ = hexchars[(byte & 0xf)];
2157 unpack_byte (char *buf, int *value)
2159 *value = stub_unpack_int (buf, 2);
2164 pack_int (char *buf, int value)
2166 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2167 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2168 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2169 buf = pack_hex_byte (buf, (value & 0xff));
2174 unpack_int (char *buf, int *value)
2176 *value = stub_unpack_int (buf, 8);
2180 #if 0 /* Currently unused, uncomment when needed. */
2181 static char *pack_string (char *pkt, char *string);
2184 pack_string (char *pkt, char *string)
2189 len = strlen (string);
2191 len = 200; /* Bigger than most GDB packets, junk??? */
2192 pkt = pack_hex_byte (pkt, len);
2196 if ((ch == '\0') || (ch == '#'))
2197 ch = '*'; /* Protect encapsulation. */
2202 #endif /* 0 (unused) */
2205 unpack_string (char *src, char *dest, int length)
2214 pack_threadid (char *pkt, threadref *id)
2217 unsigned char *altid;
2219 altid = (unsigned char *) id;
2220 limit = pkt + BUF_THREAD_ID_SIZE;
2222 pkt = pack_hex_byte (pkt, *altid++);
2228 unpack_threadid (char *inbuf, threadref *id)
2231 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2234 altref = (char *) id;
2236 while (inbuf < limit)
2238 x = stubhex (*inbuf++);
2239 y = stubhex (*inbuf++);
2240 *altref++ = (x << 4) | y;
2245 /* Externally, threadrefs are 64 bits but internally, they are still
2246 ints. This is due to a mismatch of specifications. We would like
2247 to use 64bit thread references internally. This is an adapter
2251 int_to_threadref (threadref *id, int value)
2253 unsigned char *scan;
2255 scan = (unsigned char *) id;
2261 *scan++ = (value >> 24) & 0xff;
2262 *scan++ = (value >> 16) & 0xff;
2263 *scan++ = (value >> 8) & 0xff;
2264 *scan++ = (value & 0xff);
2268 threadref_to_int (threadref *ref)
2271 unsigned char *scan;
2277 value = (value << 8) | ((*scan++) & 0xff);
2282 copy_threadref (threadref *dest, threadref *src)
2285 unsigned char *csrc, *cdest;
2287 csrc = (unsigned char *) src;
2288 cdest = (unsigned char *) dest;
2295 threadmatch (threadref *dest, threadref *src)
2297 /* Things are broken right now, so just assume we got a match. */
2299 unsigned char *srcp, *destp;
2301 srcp = (char *) src;
2302 destp = (char *) dest;
2306 result &= (*srcp++ == *destp++) ? 1 : 0;
2313 threadid:1, # always request threadid
2320 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2323 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2325 *pkt++ = 'q'; /* Info Query */
2326 *pkt++ = 'P'; /* process or thread info */
2327 pkt = pack_int (pkt, mode); /* mode */
2328 pkt = pack_threadid (pkt, id); /* threadid */
2329 *pkt = '\0'; /* terminate */
2333 /* These values tag the fields in a thread info response packet. */
2334 /* Tagging the fields allows us to request specific fields and to
2335 add more fields as time goes by. */
2337 #define TAG_THREADID 1 /* Echo the thread identifier. */
2338 #define TAG_EXISTS 2 /* Is this process defined enough to
2339 fetch registers and its stack? */
2340 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2341 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2342 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2346 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2347 struct gdb_ext_thread_info *info)
2349 struct remote_state *rs = get_remote_state ();
2353 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2356 /* info->threadid = 0; FIXME: implement zero_threadref. */
2358 info->display[0] = '\0';
2359 info->shortname[0] = '\0';
2360 info->more_display[0] = '\0';
2362 /* Assume the characters indicating the packet type have been
2364 pkt = unpack_int (pkt, &mask); /* arg mask */
2365 pkt = unpack_threadid (pkt, &ref);
2368 warning (_("Incomplete response to threadinfo request."));
2369 if (!threadmatch (&ref, expectedref))
2370 { /* This is an answer to a different request. */
2371 warning (_("ERROR RMT Thread info mismatch."));
2374 copy_threadref (&info->threadid, &ref);
2376 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2378 /* Packets are terminated with nulls. */
2379 while ((pkt < limit) && mask && *pkt)
2381 pkt = unpack_int (pkt, &tag); /* tag */
2382 pkt = unpack_byte (pkt, &length); /* length */
2383 if (!(tag & mask)) /* Tags out of synch with mask. */
2385 warning (_("ERROR RMT: threadinfo tag mismatch."));
2389 if (tag == TAG_THREADID)
2393 warning (_("ERROR RMT: length of threadid is not 16."));
2397 pkt = unpack_threadid (pkt, &ref);
2398 mask = mask & ~TAG_THREADID;
2401 if (tag == TAG_EXISTS)
2403 info->active = stub_unpack_int (pkt, length);
2405 mask = mask & ~(TAG_EXISTS);
2408 warning (_("ERROR RMT: 'exists' length too long."));
2414 if (tag == TAG_THREADNAME)
2416 pkt = unpack_string (pkt, &info->shortname[0], length);
2417 mask = mask & ~TAG_THREADNAME;
2420 if (tag == TAG_DISPLAY)
2422 pkt = unpack_string (pkt, &info->display[0], length);
2423 mask = mask & ~TAG_DISPLAY;
2426 if (tag == TAG_MOREDISPLAY)
2428 pkt = unpack_string (pkt, &info->more_display[0], length);
2429 mask = mask & ~TAG_MOREDISPLAY;
2432 warning (_("ERROR RMT: unknown thread info tag."));
2433 break; /* Not a tag we know about. */
2439 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2440 struct gdb_ext_thread_info *info)
2442 struct remote_state *rs = get_remote_state ();
2445 pack_threadinfo_request (rs->buf, fieldset, threadid);
2447 getpkt (&rs->buf, &rs->buf_size, 0);
2449 if (rs->buf[0] == '\0')
2452 result = remote_unpack_thread_info_response (rs->buf + 2,
2457 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2460 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2461 threadref *nextthread)
2463 *pkt++ = 'q'; /* info query packet */
2464 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2465 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2466 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2467 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2472 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2475 parse_threadlist_response (char *pkt, int result_limit,
2476 threadref *original_echo, threadref *resultlist,
2479 struct remote_state *rs = get_remote_state ();
2481 int count, resultcount, done;
2484 /* Assume the 'q' and 'M chars have been stripped. */
2485 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2486 /* done parse past here */
2487 pkt = unpack_byte (pkt, &count); /* count field */
2488 pkt = unpack_nibble (pkt, &done);
2489 /* The first threadid is the argument threadid. */
2490 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2491 while ((count-- > 0) && (pkt < limit))
2493 pkt = unpack_threadid (pkt, resultlist++);
2494 if (resultcount++ >= result_limit)
2503 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2504 int *done, int *result_count, threadref *threadlist)
2506 struct remote_state *rs = get_remote_state ();
2509 /* Trancate result limit to be smaller than the packet size. */
2510 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2511 >= get_remote_packet_size ())
2512 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2514 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2516 getpkt (&rs->buf, &rs->buf_size, 0);
2518 if (*rs->buf == '\0')
2522 parse_threadlist_response (rs->buf + 2, result_limit,
2523 &rs->echo_nextthread, threadlist, done);
2525 if (!threadmatch (&rs->echo_nextthread, nextthread))
2527 /* FIXME: This is a good reason to drop the packet. */
2528 /* Possably, there is a duplicate response. */
2530 retransmit immediatly - race conditions
2531 retransmit after timeout - yes
2533 wait for packet, then exit
2535 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2536 return 0; /* I choose simply exiting. */
2538 if (*result_count <= 0)
2542 warning (_("RMT ERROR : failed to get remote thread list."));
2545 return result; /* break; */
2547 if (*result_count > result_limit)
2550 warning (_("RMT ERROR: threadlist response longer than requested."));
2556 /* This is the interface between remote and threads, remotes upper
2559 /* remote_find_new_threads retrieves the thread list and for each
2560 thread in the list, looks up the thread in GDB's internal list,
2561 adding the thread if it does not already exist. This involves
2562 getting partial thread lists from the remote target so, polling the
2563 quit_flag is required. */
2567 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2570 struct remote_state *rs = get_remote_state ();
2571 int done, i, result_count;
2579 if (loopcount++ > looplimit)
2582 warning (_("Remote fetch threadlist -infinite loop-."));
2585 if (!remote_get_threadlist (startflag, &rs->nextthread,
2586 MAXTHREADLISTRESULTS,
2587 &done, &result_count, rs->resultthreadlist))
2592 /* Clear for later iterations. */
2594 /* Setup to resume next batch of thread references, set nextthread. */
2595 if (result_count >= 1)
2596 copy_threadref (&rs->nextthread,
2597 &rs->resultthreadlist[result_count - 1]);
2599 while (result_count--)
2600 if (!(result = (*stepfunction) (&rs->resultthreadlist[i++], context)))
2607 remote_newthread_step (threadref *ref, void *context)
2609 int pid = ptid_get_pid (inferior_ptid);
2610 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2612 if (!in_thread_list (ptid))
2614 return 1; /* continue iterator */
2617 #define CRAZY_MAX_THREADS 1000
2620 remote_current_thread (ptid_t oldpid)
2622 struct remote_state *rs = get_remote_state ();
2625 getpkt (&rs->buf, &rs->buf_size, 0);
2626 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2627 return read_ptid (&rs->buf[2], NULL);
2632 /* Find new threads for info threads command.
2633 * Original version, using John Metzler's thread protocol.
2637 remote_find_new_threads (void)
2639 remote_threadlist_iterator (remote_newthread_step, 0,
2643 #if defined(HAVE_LIBEXPAT)
2645 typedef struct thread_item
2651 DEF_VEC_O(thread_item_t);
2653 struct threads_parsing_context
2655 VEC (thread_item_t) *items;
2659 start_thread (struct gdb_xml_parser *parser,
2660 const struct gdb_xml_element *element,
2661 void *user_data, VEC(gdb_xml_value_s) *attributes)
2663 struct threads_parsing_context *data = user_data;
2665 struct thread_item item;
2667 struct gdb_xml_value *attr;
2669 id = xml_find_attribute (attributes, "id")->value;
2670 item.ptid = read_ptid (id, NULL);
2672 attr = xml_find_attribute (attributes, "core");
2674 item.core = *(ULONGEST *) attr->value;
2680 VEC_safe_push (thread_item_t, data->items, &item);
2684 end_thread (struct gdb_xml_parser *parser,
2685 const struct gdb_xml_element *element,
2686 void *user_data, const char *body_text)
2688 struct threads_parsing_context *data = user_data;
2690 if (body_text && *body_text)
2691 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2694 const struct gdb_xml_attribute thread_attributes[] = {
2695 { "id", GDB_XML_AF_NONE, NULL, NULL },
2696 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2697 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2700 const struct gdb_xml_element thread_children[] = {
2701 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2704 const struct gdb_xml_element threads_children[] = {
2705 { "thread", thread_attributes, thread_children,
2706 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2707 start_thread, end_thread },
2708 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2711 const struct gdb_xml_element threads_elements[] = {
2712 { "threads", NULL, threads_children,
2713 GDB_XML_EF_NONE, NULL, NULL },
2714 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2717 /* Discard the contents of the constructed thread info context. */
2720 clear_threads_parsing_context (void *p)
2722 struct threads_parsing_context *context = p;
2724 struct thread_item *item;
2726 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2727 xfree (item->extra);
2729 VEC_free (thread_item_t, context->items);
2735 * Find all threads for info threads command.
2736 * Uses new thread protocol contributed by Cisco.
2737 * Falls back and attempts to use the older method (above)
2738 * if the target doesn't respond to the new method.
2742 remote_threads_info (struct target_ops *ops)
2744 struct remote_state *rs = get_remote_state ();
2748 if (rs->remote_desc == 0) /* paranoia */
2749 error (_("Command can only be used when connected to the remote target."));
2751 #if defined(HAVE_LIBEXPAT)
2752 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2754 char *xml = target_read_stralloc (¤t_target,
2755 TARGET_OBJECT_THREADS, NULL);
2757 struct cleanup *back_to = make_cleanup (xfree, xml);
2761 struct threads_parsing_context context;
2763 context.items = NULL;
2764 make_cleanup (clear_threads_parsing_context, &context);
2766 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2767 threads_elements, xml, &context) == 0)
2770 struct thread_item *item;
2773 VEC_iterate (thread_item_t, context.items, i, item);
2776 if (!ptid_equal (item->ptid, null_ptid))
2778 struct private_thread_info *info;
2779 /* In non-stop mode, we assume new found threads
2780 are running until proven otherwise with a
2781 stop reply. In all-stop, we can only get
2782 here if all threads are stopped. */
2783 int running = non_stop ? 1 : 0;
2785 remote_notice_new_inferior (item->ptid, running);
2787 info = demand_private_info (item->ptid);
2788 info->core = item->core;
2789 info->extra = item->extra;
2796 do_cleanups (back_to);
2801 if (rs->use_threadinfo_query)
2803 putpkt ("qfThreadInfo");
2804 getpkt (&rs->buf, &rs->buf_size, 0);
2806 if (bufp[0] != '\0') /* q packet recognized */
2808 struct cleanup *old_chain;
2811 /* remote_notice_new_inferior (in the loop below) may make
2812 new RSP calls, which clobber rs->buf. Work with a
2814 bufp = saved_reply = xstrdup (rs->buf);
2815 old_chain = make_cleanup (free_current_contents, &saved_reply);
2817 while (*bufp++ == 'm') /* reply contains one or more TID */
2821 new_thread = read_ptid (bufp, &bufp);
2822 if (!ptid_equal (new_thread, null_ptid))
2824 /* In non-stop mode, we assume new found threads
2825 are running until proven otherwise with a
2826 stop reply. In all-stop, we can only get
2827 here if all threads are stopped. */
2828 int running = non_stop ? 1 : 0;
2830 remote_notice_new_inferior (new_thread, running);
2833 while (*bufp++ == ','); /* comma-separated list */
2834 free_current_contents (&saved_reply);
2835 putpkt ("qsThreadInfo");
2836 getpkt (&rs->buf, &rs->buf_size, 0);
2837 bufp = saved_reply = xstrdup (rs->buf);
2839 do_cleanups (old_chain);
2844 /* Only qfThreadInfo is supported in non-stop mode. */
2848 /* Else fall back to old method based on jmetzler protocol. */
2849 rs->use_threadinfo_query = 0;
2850 remote_find_new_threads ();
2855 * Collect a descriptive string about the given thread.
2856 * The target may say anything it wants to about the thread
2857 * (typically info about its blocked / runnable state, name, etc.).
2858 * This string will appear in the info threads display.
2860 * Optional: targets are not required to implement this function.
2864 remote_threads_extra_info (struct thread_info *tp)
2866 struct remote_state *rs = get_remote_state ();
2870 struct gdb_ext_thread_info threadinfo;
2871 static char display_buf[100]; /* arbitrary... */
2872 int n = 0; /* position in display_buf */
2874 if (rs->remote_desc == 0) /* paranoia */
2875 internal_error (__FILE__, __LINE__,
2876 _("remote_threads_extra_info"));
2878 if (ptid_equal (tp->ptid, magic_null_ptid)
2879 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2880 /* This is the main thread which was added by GDB. The remote
2881 server doesn't know about it. */
2884 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2886 struct thread_info *info = find_thread_ptid (tp->ptid);
2888 if (info && info->private)
2889 return info->private->extra;
2894 if (rs->use_threadextra_query)
2897 char *endb = rs->buf + get_remote_packet_size ();
2899 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2901 write_ptid (b, endb, tp->ptid);
2904 getpkt (&rs->buf, &rs->buf_size, 0);
2905 if (rs->buf[0] != 0)
2907 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2908 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2909 display_buf [result] = '\0';
2914 /* If the above query fails, fall back to the old method. */
2915 rs->use_threadextra_query = 0;
2916 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2917 | TAG_MOREDISPLAY | TAG_DISPLAY;
2918 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2919 if (remote_get_threadinfo (&id, set, &threadinfo))
2920 if (threadinfo.active)
2922 if (*threadinfo.shortname)
2923 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2924 " Name: %s,", threadinfo.shortname);
2925 if (*threadinfo.display)
2926 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2927 " State: %s,", threadinfo.display);
2928 if (*threadinfo.more_display)
2929 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2930 " Priority: %s", threadinfo.more_display);
2934 /* For purely cosmetic reasons, clear up trailing commas. */
2935 if (',' == display_buf[n-1])
2936 display_buf[n-1] = ' ';
2945 remote_static_tracepoint_marker_at (CORE_ADDR addr,
2946 struct static_tracepoint_marker *marker)
2948 struct remote_state *rs = get_remote_state ();
2951 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2953 p += hexnumstr (p, addr);
2955 getpkt (&rs->buf, &rs->buf_size, 0);
2959 error (_("Remote failure reply: %s"), p);
2963 parse_static_tracepoint_marker_definition (p, &p, marker);
2970 static VEC(static_tracepoint_marker_p) *
2971 remote_static_tracepoint_markers_by_strid (const char *strid)
2973 struct remote_state *rs = get_remote_state ();
2974 VEC(static_tracepoint_marker_p) *markers = NULL;
2975 struct static_tracepoint_marker *marker = NULL;
2976 struct cleanup *old_chain;
2979 /* Ask for a first packet of static tracepoint marker
2982 getpkt (&rs->buf, &rs->buf_size, 0);
2985 error (_("Remote failure reply: %s"), p);
2987 old_chain = make_cleanup (free_current_marker, &marker);
2992 marker = XCNEW (struct static_tracepoint_marker);
2996 parse_static_tracepoint_marker_definition (p, &p, marker);
2998 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3000 VEC_safe_push (static_tracepoint_marker_p,
3006 release_static_tracepoint_marker (marker);
3007 memset (marker, 0, sizeof (*marker));
3010 while (*p++ == ','); /* comma-separated list */
3011 /* Ask for another packet of static tracepoint definition. */
3013 getpkt (&rs->buf, &rs->buf_size, 0);
3017 do_cleanups (old_chain);
3022 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3025 remote_get_ada_task_ptid (long lwp, long thread)
3027 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
3031 /* Restart the remote side; this is an extended protocol operation. */
3034 extended_remote_restart (void)
3036 struct remote_state *rs = get_remote_state ();
3038 /* Send the restart command; for reasons I don't understand the
3039 remote side really expects a number after the "R". */
3040 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3043 remote_fileio_reset ();
3046 /* Clean up connection to a remote debugger. */
3051 struct remote_state *rs = get_remote_state ();
3053 if (rs->remote_desc == NULL)
3054 return; /* already closed */
3056 /* Make sure we leave stdin registered in the event loop, and we
3057 don't leave the async SIGINT signal handler installed. */
3058 remote_terminal_ours ();
3060 serial_close (rs->remote_desc);
3061 rs->remote_desc = NULL;
3063 /* We don't have a connection to the remote stub anymore. Get rid
3064 of all the inferiors and their threads we were controlling.
3065 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3066 will be unable to find the thread corresponding to (pid, 0, 0). */
3067 inferior_ptid = null_ptid;
3068 discard_all_inferiors ();
3070 /* We are closing the remote target, so we should discard
3071 everything of this target. */
3072 discard_pending_stop_replies_in_queue (rs);
3074 if (remote_async_inferior_event_token)
3075 delete_async_event_handler (&remote_async_inferior_event_token);
3077 remote_notif_state_xfree (rs->notif_state);
3079 trace_reset_local_state ();
3082 /* Query the remote side for the text, data and bss offsets. */
3087 struct remote_state *rs = get_remote_state ();
3090 int lose, num_segments = 0, do_sections, do_segments;
3091 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3092 struct section_offsets *offs;
3093 struct symfile_segment_data *data;
3095 if (symfile_objfile == NULL)
3098 putpkt ("qOffsets");
3099 getpkt (&rs->buf, &rs->buf_size, 0);
3102 if (buf[0] == '\000')
3103 return; /* Return silently. Stub doesn't support
3107 warning (_("Remote failure reply: %s"), buf);
3111 /* Pick up each field in turn. This used to be done with scanf, but
3112 scanf will make trouble if CORE_ADDR size doesn't match
3113 conversion directives correctly. The following code will work
3114 with any size of CORE_ADDR. */
3115 text_addr = data_addr = bss_addr = 0;
3119 if (strncmp (ptr, "Text=", 5) == 0)
3122 /* Don't use strtol, could lose on big values. */
3123 while (*ptr && *ptr != ';')
3124 text_addr = (text_addr << 4) + fromhex (*ptr++);
3126 if (strncmp (ptr, ";Data=", 6) == 0)
3129 while (*ptr && *ptr != ';')
3130 data_addr = (data_addr << 4) + fromhex (*ptr++);
3135 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3138 while (*ptr && *ptr != ';')
3139 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3141 if (bss_addr != data_addr)
3142 warning (_("Target reported unsupported offsets: %s"), buf);
3147 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3150 /* Don't use strtol, could lose on big values. */
3151 while (*ptr && *ptr != ';')
3152 text_addr = (text_addr << 4) + fromhex (*ptr++);
3155 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3158 while (*ptr && *ptr != ';')
3159 data_addr = (data_addr << 4) + fromhex (*ptr++);
3167 error (_("Malformed response to offset query, %s"), buf);
3168 else if (*ptr != '\0')
3169 warning (_("Target reported unsupported offsets: %s"), buf);
3171 offs = ((struct section_offsets *)
3172 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3173 memcpy (offs, symfile_objfile->section_offsets,
3174 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3176 data = get_symfile_segment_data (symfile_objfile->obfd);
3177 do_segments = (data != NULL);
3178 do_sections = num_segments == 0;
3180 if (num_segments > 0)
3182 segments[0] = text_addr;
3183 segments[1] = data_addr;
3185 /* If we have two segments, we can still try to relocate everything
3186 by assuming that the .text and .data offsets apply to the whole
3187 text and data segments. Convert the offsets given in the packet
3188 to base addresses for symfile_map_offsets_to_segments. */
3189 else if (data && data->num_segments == 2)
3191 segments[0] = data->segment_bases[0] + text_addr;
3192 segments[1] = data->segment_bases[1] + data_addr;
3195 /* If the object file has only one segment, assume that it is text
3196 rather than data; main programs with no writable data are rare,
3197 but programs with no code are useless. Of course the code might
3198 have ended up in the data segment... to detect that we would need
3199 the permissions here. */
3200 else if (data && data->num_segments == 1)
3202 segments[0] = data->segment_bases[0] + text_addr;
3205 /* There's no way to relocate by segment. */
3211 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3212 offs, num_segments, segments);
3214 if (ret == 0 && !do_sections)
3215 error (_("Can not handle qOffsets TextSeg "
3216 "response with this symbol file"));
3223 free_symfile_segment_data (data);
3227 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3229 /* This is a temporary kludge to force data and bss to use the
3230 same offsets because that's what nlmconv does now. The real
3231 solution requires changes to the stub and remote.c that I
3232 don't have time to do right now. */
3234 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3235 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3238 objfile_relocate (symfile_objfile, offs);
3241 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3242 threads we know are stopped already. This is used during the
3243 initial remote connection in non-stop mode --- threads that are
3244 reported as already being stopped are left stopped. */
3247 set_stop_requested_callback (struct thread_info *thread, void *data)
3249 /* If we have a stop reply for this thread, it must be stopped. */
3250 if (peek_stop_reply (thread->ptid))
3251 set_stop_requested (thread->ptid, 1);
3256 /* Send interrupt_sequence to remote target. */
3258 send_interrupt_sequence (void)
3260 struct remote_state *rs = get_remote_state ();
3262 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3263 remote_serial_write ("\x03", 1);
3264 else if (interrupt_sequence_mode == interrupt_sequence_break)
3265 serial_send_break (rs->remote_desc);
3266 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3268 serial_send_break (rs->remote_desc);
3269 remote_serial_write ("g", 1);
3272 internal_error (__FILE__, __LINE__,
3273 _("Invalid value for interrupt_sequence_mode: %s."),
3274 interrupt_sequence_mode);
3278 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3279 and extract the PTID. Returns NULL_PTID if not found. */
3282 stop_reply_extract_thread (char *stop_reply)
3284 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3288 /* Txx r:val ; r:val (...) */
3291 /* Look for "register" named "thread". */
3296 p1 = strchr (p, ':');
3300 if (strncmp (p, "thread", p1 - p) == 0)
3301 return read_ptid (++p1, &p);
3303 p1 = strchr (p, ';');
3315 /* Query the remote target for which is the current thread/process,
3316 add it to our tables, and update INFERIOR_PTID. The caller is
3317 responsible for setting the state such that the remote end is ready
3318 to return the current thread.
3320 This function is called after handling the '?' or 'vRun' packets,
3321 whose response is a stop reply from which we can also try
3322 extracting the thread. If the target doesn't support the explicit
3323 qC query, we infer the current thread from that stop reply, passed
3324 in in WAIT_STATUS, which may be NULL. */
3327 add_current_inferior_and_thread (char *wait_status)
3329 struct remote_state *rs = get_remote_state ();
3331 ptid_t ptid = null_ptid;
3333 inferior_ptid = null_ptid;
3335 /* Now, if we have thread information, update inferior_ptid. First
3336 if we have a stop reply handy, maybe it's a T stop reply with a
3337 "thread" register we can extract the current thread from. If
3338 not, ask the remote which is the current thread, with qC. The
3339 former method avoids a roundtrip. Note we don't use
3340 remote_parse_stop_reply as that makes use of the target
3341 architecture, which we haven't yet fully determined at this
3343 if (wait_status != NULL)
3344 ptid = stop_reply_extract_thread (wait_status);
3345 if (ptid_equal (ptid, null_ptid))
3346 ptid = remote_current_thread (inferior_ptid);
3348 if (!ptid_equal (ptid, null_ptid))
3350 if (!remote_multi_process_p (rs))
3353 inferior_ptid = ptid;
3357 /* Without this, some commands which require an active target
3358 (such as kill) won't work. This variable serves (at least)
3359 double duty as both the pid of the target process (if it has
3360 such), and as a flag indicating that a target is active. */
3361 inferior_ptid = magic_null_ptid;
3365 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3367 /* Add the main thread. */
3368 add_thread_silent (inferior_ptid);
3372 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3374 struct remote_state *rs = get_remote_state ();
3375 struct packet_config *noack_config;
3376 char *wait_status = NULL;
3378 immediate_quit++; /* Allow user to interrupt it. */
3381 if (interrupt_on_connect)
3382 send_interrupt_sequence ();
3384 /* Ack any packet which the remote side has already sent. */
3385 serial_write (rs->remote_desc, "+", 1);
3387 /* Signal other parts that we're going through the initial setup,
3388 and so things may not be stable yet. */
3389 rs->starting_up = 1;
3391 /* The first packet we send to the target is the optional "supported
3392 packets" request. If the target can answer this, it will tell us
3393 which later probes to skip. */
3394 remote_query_supported ();
3396 /* If the stub wants to get a QAllow, compose one and send it. */
3397 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3398 remote_set_permissions ();
3400 /* Next, we possibly activate noack mode.
3402 If the QStartNoAckMode packet configuration is set to AUTO,
3403 enable noack mode if the stub reported a wish for it with
3406 If set to TRUE, then enable noack mode even if the stub didn't
3407 report it in qSupported. If the stub doesn't reply OK, the
3408 session ends with an error.
3410 If FALSE, then don't activate noack mode, regardless of what the
3411 stub claimed should be the default with qSupported. */
3413 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3415 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3416 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3417 && noack_config->support == PACKET_ENABLE))
3419 putpkt ("QStartNoAckMode");
3420 getpkt (&rs->buf, &rs->buf_size, 0);
3421 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3427 /* Tell the remote that we are using the extended protocol. */
3429 getpkt (&rs->buf, &rs->buf_size, 0);
3432 /* Let the target know which signals it is allowed to pass down to
3434 update_signals_program_target ();
3436 /* Next, if the target can specify a description, read it. We do
3437 this before anything involving memory or registers. */
3438 target_find_description ();
3440 /* Next, now that we know something about the target, update the
3441 address spaces in the program spaces. */
3442 update_address_spaces ();
3444 /* On OSs where the list of libraries is global to all
3445 processes, we fetch them early. */
3446 if (gdbarch_has_global_solist (target_gdbarch ()))
3447 solib_add (NULL, from_tty, target, auto_solib_add);
3451 if (!rs->non_stop_aware)
3452 error (_("Non-stop mode requested, but remote "
3453 "does not support non-stop"));
3455 putpkt ("QNonStop:1");
3456 getpkt (&rs->buf, &rs->buf_size, 0);
3458 if (strcmp (rs->buf, "OK") != 0)
3459 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3461 /* Find about threads and processes the stub is already
3462 controlling. We default to adding them in the running state.
3463 The '?' query below will then tell us about which threads are
3465 remote_threads_info (target);
3467 else if (rs->non_stop_aware)
3469 /* Don't assume that the stub can operate in all-stop mode.
3470 Request it explicitly. */
3471 putpkt ("QNonStop:0");
3472 getpkt (&rs->buf, &rs->buf_size, 0);
3474 if (strcmp (rs->buf, "OK") != 0)
3475 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3478 /* Upload TSVs regardless of whether the target is running or not. The
3479 remote stub, such as GDBserver, may have some predefined or builtin
3480 TSVs, even if the target is not running. */
3481 if (remote_get_trace_status (current_trace_status ()) != -1)
3483 struct uploaded_tsv *uploaded_tsvs = NULL;
3485 remote_upload_trace_state_variables (&uploaded_tsvs);
3486 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3489 /* Check whether the target is running now. */
3491 getpkt (&rs->buf, &rs->buf_size, 0);
3497 struct inferior *inf;
3499 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3502 error (_("The target is not running (try extended-remote?)"));
3504 /* We're connected, but not running. Drop out before we
3505 call start_remote. */
3506 rs->starting_up = 0;
3511 /* Save the reply for later. */
3512 wait_status = alloca (strlen (rs->buf) + 1);
3513 strcpy (wait_status, rs->buf);
3516 /* Let the stub know that we want it to return the thread. */
3517 set_continue_thread (minus_one_ptid);
3519 add_current_inferior_and_thread (wait_status);
3521 /* init_wait_for_inferior should be called before get_offsets in order
3522 to manage `inserted' flag in bp loc in a correct state.
3523 breakpoint_init_inferior, called from init_wait_for_inferior, set
3524 `inserted' flag to 0, while before breakpoint_re_set, called from
3525 start_remote, set `inserted' flag to 1. In the initialization of
3526 inferior, breakpoint_init_inferior should be called first, and then
3527 breakpoint_re_set can be called. If this order is broken, state of
3528 `inserted' flag is wrong, and cause some problems on breakpoint
3530 init_wait_for_inferior ();
3532 get_offsets (); /* Get text, data & bss offsets. */
3534 /* If we could not find a description using qXfer, and we know
3535 how to do it some other way, try again. This is not
3536 supported for non-stop; it could be, but it is tricky if
3537 there are no stopped threads when we connect. */
3538 if (remote_read_description_p (target)
3539 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3541 target_clear_description ();
3542 target_find_description ();
3545 /* Use the previously fetched status. */
3546 gdb_assert (wait_status != NULL);
3547 strcpy (rs->buf, wait_status);
3548 rs->cached_wait_status = 1;
3551 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3555 /* Clear WFI global state. Do this before finding about new
3556 threads and inferiors, and setting the current inferior.
3557 Otherwise we would clear the proceed status of the current
3558 inferior when we want its stop_soon state to be preserved
3559 (see notice_new_inferior). */
3560 init_wait_for_inferior ();
3562 /* In non-stop, we will either get an "OK", meaning that there
3563 are no stopped threads at this time; or, a regular stop
3564 reply. In the latter case, there may be more than one thread
3565 stopped --- we pull them all out using the vStopped
3567 if (strcmp (rs->buf, "OK") != 0)
3569 struct notif_client *notif = ¬if_client_stop;
3571 /* remote_notif_get_pending_replies acks this one, and gets
3573 rs->notif_state->pending_event[notif_client_stop.id]
3574 = remote_notif_parse (notif, rs->buf);
3575 remote_notif_get_pending_events (notif);
3577 /* Make sure that threads that were stopped remain
3579 iterate_over_threads (set_stop_requested_callback, NULL);
3582 if (target_can_async_p ())
3583 target_async (inferior_event_handler, 0);
3585 if (thread_count () == 0)
3588 error (_("The target is not running (try extended-remote?)"));
3590 /* We're connected, but not running. Drop out before we
3591 call start_remote. */
3592 rs->starting_up = 0;
3596 /* Let the stub know that we want it to return the thread. */
3598 /* Force the stub to choose a thread. */
3599 set_general_thread (null_ptid);
3602 inferior_ptid = remote_current_thread (minus_one_ptid);
3603 if (ptid_equal (inferior_ptid, minus_one_ptid))
3604 error (_("remote didn't report the current thread in non-stop mode"));
3606 get_offsets (); /* Get text, data & bss offsets. */
3608 /* In non-stop mode, any cached wait status will be stored in
3609 the stop reply queue. */
3610 gdb_assert (wait_status == NULL);
3612 /* Report all signals during attach/startup. */
3613 remote_pass_signals (0, NULL);
3616 /* If we connected to a live target, do some additional setup. */
3617 if (target_has_execution)
3619 if (exec_bfd) /* No use without an exec file. */
3620 remote_check_symbols ();
3623 /* Possibly the target has been engaged in a trace run started
3624 previously; find out where things are at. */
3625 if (remote_get_trace_status (current_trace_status ()) != -1)
3627 struct uploaded_tp *uploaded_tps = NULL;
3629 if (current_trace_status ()->running)
3630 printf_filtered (_("Trace is already running on the target.\n"));
3632 remote_upload_tracepoints (&uploaded_tps);
3634 merge_uploaded_tracepoints (&uploaded_tps);
3637 /* The thread and inferior lists are now synchronized with the
3638 target, our symbols have been relocated, and we're merged the
3639 target's tracepoints with ours. We're done with basic start
3641 rs->starting_up = 0;
3643 /* If breakpoints are global, insert them now. */
3644 if (gdbarch_has_global_breakpoints (target_gdbarch ())
3645 && breakpoints_always_inserted_mode ())
3646 insert_breakpoints ();
3649 /* Open a connection to a remote debugger.
3650 NAME is the filename used for communication. */
3653 remote_open (char *name, int from_tty)
3655 remote_open_1 (name, from_tty, &remote_ops, 0);
3658 /* Open a connection to a remote debugger using the extended
3659 remote gdb protocol. NAME is the filename used for communication. */
3662 extended_remote_open (char *name, int from_tty)
3664 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3667 /* Generic code for opening a connection to a remote target. */
3670 init_all_packet_configs (void)
3674 for (i = 0; i < PACKET_MAX; i++)
3675 update_packet_config (&remote_protocol_packets[i]);
3678 /* Symbol look-up. */
3681 remote_check_symbols (void)
3683 struct remote_state *rs = get_remote_state ();
3684 char *msg, *reply, *tmp;
3685 struct minimal_symbol *sym;
3688 /* The remote side has no concept of inferiors that aren't running
3689 yet, it only knows about running processes. If we're connected
3690 but our current inferior is not running, we should not invite the
3691 remote target to request symbol lookups related to its
3692 (unrelated) current process. */
3693 if (!target_has_execution)
3696 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3699 /* Make sure the remote is pointing at the right process. Note
3700 there's no way to select "no process". */
3701 set_general_process ();
3703 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3704 because we need both at the same time. */
3705 msg = alloca (get_remote_packet_size ());
3707 /* Invite target to request symbol lookups. */
3709 putpkt ("qSymbol::");
3710 getpkt (&rs->buf, &rs->buf_size, 0);
3711 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3714 while (strncmp (reply, "qSymbol:", 8) == 0)
3717 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3719 sym = lookup_minimal_symbol (msg, NULL, NULL);
3721 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3724 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3725 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3727 /* If this is a function address, return the start of code
3728 instead of any data function descriptor. */
3729 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3733 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3734 phex_nz (sym_addr, addr_size), &reply[8]);
3738 getpkt (&rs->buf, &rs->buf_size, 0);
3743 static struct serial *
3744 remote_serial_open (char *name)
3746 static int udp_warning = 0;
3748 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3749 of in ser-tcp.c, because it is the remote protocol assuming that the
3750 serial connection is reliable and not the serial connection promising
3752 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3754 warning (_("The remote protocol may be unreliable over UDP.\n"
3755 "Some events may be lost, rendering further debugging "
3760 return serial_open (name);
3763 /* Inform the target of our permission settings. The permission flags
3764 work without this, but if the target knows the settings, it can do
3765 a couple things. First, it can add its own check, to catch cases
3766 that somehow manage to get by the permissions checks in target
3767 methods. Second, if the target is wired to disallow particular
3768 settings (for instance, a system in the field that is not set up to
3769 be able to stop at a breakpoint), it can object to any unavailable
3773 remote_set_permissions (void)
3775 struct remote_state *rs = get_remote_state ();
3777 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3778 "WriteReg:%x;WriteMem:%x;"
3779 "InsertBreak:%x;InsertTrace:%x;"
3780 "InsertFastTrace:%x;Stop:%x",
3781 may_write_registers, may_write_memory,
3782 may_insert_breakpoints, may_insert_tracepoints,
3783 may_insert_fast_tracepoints, may_stop);
3785 getpkt (&rs->buf, &rs->buf_size, 0);
3787 /* If the target didn't like the packet, warn the user. Do not try
3788 to undo the user's settings, that would just be maddening. */
3789 if (strcmp (rs->buf, "OK") != 0)
3790 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3793 /* This type describes each known response to the qSupported
3795 struct protocol_feature
3797 /* The name of this protocol feature. */
3800 /* The default for this protocol feature. */
3801 enum packet_support default_support;
3803 /* The function to call when this feature is reported, or after
3804 qSupported processing if the feature is not supported.
3805 The first argument points to this structure. The second
3806 argument indicates whether the packet requested support be
3807 enabled, disabled, or probed (or the default, if this function
3808 is being called at the end of processing and this feature was
3809 not reported). The third argument may be NULL; if not NULL, it
3810 is a NUL-terminated string taken from the packet following
3811 this feature's name and an equals sign. */
3812 void (*func) (const struct protocol_feature *, enum packet_support,
3815 /* The corresponding packet for this feature. Only used if
3816 FUNC is remote_supported_packet. */
3821 remote_supported_packet (const struct protocol_feature *feature,
3822 enum packet_support support,
3823 const char *argument)
3827 warning (_("Remote qSupported response supplied an unexpected value for"
3828 " \"%s\"."), feature->name);
3832 if (remote_protocol_packets[feature->packet].support
3833 == PACKET_SUPPORT_UNKNOWN)
3834 remote_protocol_packets[feature->packet].support = support;
3838 remote_packet_size (const struct protocol_feature *feature,
3839 enum packet_support support, const char *value)
3841 struct remote_state *rs = get_remote_state ();
3846 if (support != PACKET_ENABLE)
3849 if (value == NULL || *value == '\0')
3851 warning (_("Remote target reported \"%s\" without a size."),
3857 packet_size = strtol (value, &value_end, 16);
3858 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3860 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3861 feature->name, value);
3865 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3867 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3868 packet_size, MAX_REMOTE_PACKET_SIZE);
3869 packet_size = MAX_REMOTE_PACKET_SIZE;
3872 /* Record the new maximum packet size. */
3873 rs->explicit_packet_size = packet_size;
3877 remote_multi_process_feature (const struct protocol_feature *feature,
3878 enum packet_support support, const char *value)
3880 struct remote_state *rs = get_remote_state ();
3882 rs->multi_process_aware = (support == PACKET_ENABLE);
3886 remote_non_stop_feature (const struct protocol_feature *feature,
3887 enum packet_support support, const char *value)
3889 struct remote_state *rs = get_remote_state ();
3891 rs->non_stop_aware = (support == PACKET_ENABLE);
3895 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3896 enum packet_support support,
3899 struct remote_state *rs = get_remote_state ();
3901 rs->cond_tracepoints = (support == PACKET_ENABLE);
3905 remote_cond_breakpoint_feature (const struct protocol_feature *feature,
3906 enum packet_support support,
3909 struct remote_state *rs = get_remote_state ();
3911 rs->cond_breakpoints = (support == PACKET_ENABLE);
3915 remote_breakpoint_commands_feature (const struct protocol_feature *feature,
3916 enum packet_support support,
3919 struct remote_state *rs = get_remote_state ();
3921 rs->breakpoint_commands = (support == PACKET_ENABLE);
3925 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3926 enum packet_support support,
3929 struct remote_state *rs = get_remote_state ();
3931 rs->fast_tracepoints = (support == PACKET_ENABLE);
3935 remote_static_tracepoint_feature (const struct protocol_feature *feature,
3936 enum packet_support support,
3939 struct remote_state *rs = get_remote_state ();
3941 rs->static_tracepoints = (support == PACKET_ENABLE);
3945 remote_install_in_trace_feature (const struct protocol_feature *feature,
3946 enum packet_support support,
3949 struct remote_state *rs = get_remote_state ();
3951 rs->install_in_trace = (support == PACKET_ENABLE);
3955 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3956 enum packet_support support,
3959 struct remote_state *rs = get_remote_state ();
3961 rs->disconnected_tracing = (support == PACKET_ENABLE);
3965 remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3966 enum packet_support support,
3969 struct remote_state *rs = get_remote_state ();
3971 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3975 remote_string_tracing_feature (const struct protocol_feature *feature,
3976 enum packet_support support,
3979 struct remote_state *rs = get_remote_state ();
3981 rs->string_tracing = (support == PACKET_ENABLE);
3985 remote_augmented_libraries_svr4_read_feature
3986 (const struct protocol_feature *feature,
3987 enum packet_support support, const char *value)
3989 struct remote_state *rs = get_remote_state ();
3991 rs->augmented_libraries_svr4_read = (support == PACKET_ENABLE);
3994 static const struct protocol_feature remote_protocol_features[] = {
3995 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3996 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3997 PACKET_qXfer_auxv },
3998 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3999 PACKET_qXfer_features },
4000 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4001 PACKET_qXfer_libraries },
4002 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4003 PACKET_qXfer_libraries_svr4 },
4004 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4005 remote_augmented_libraries_svr4_read_feature, -1 },
4006 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4007 PACKET_qXfer_memory_map },
4008 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4009 PACKET_qXfer_spu_read },
4010 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4011 PACKET_qXfer_spu_write },
4012 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4013 PACKET_qXfer_osdata },
4014 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4015 PACKET_qXfer_threads },
4016 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4017 PACKET_qXfer_traceframe_info },
4018 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4019 PACKET_QPassSignals },
4020 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4021 PACKET_QProgramSignals },
4022 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4023 PACKET_QStartNoAckMode },
4024 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
4025 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
4026 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4027 PACKET_qXfer_siginfo_read },
4028 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4029 PACKET_qXfer_siginfo_write },
4030 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
4031 PACKET_ConditionalTracepoints },
4032 { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
4033 PACKET_ConditionalBreakpoints },
4034 { "BreakpointCommands", PACKET_DISABLE, remote_breakpoint_commands_feature,
4035 PACKET_BreakpointCommands },
4036 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
4037 PACKET_FastTracepoints },
4038 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
4039 PACKET_StaticTracepoints },
4040 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
4041 PACKET_InstallInTrace},
4042 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
4044 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4046 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4048 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4049 PACKET_TracepointSource },
4050 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4052 { "EnableDisableTracepoints", PACKET_DISABLE,
4053 remote_enable_disable_tracepoint_feature, -1 },
4054 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4055 PACKET_qXfer_fdpic },
4056 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4058 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4059 PACKET_QDisableRandomization },
4060 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4061 { "QTBuffer:size", PACKET_DISABLE,
4062 remote_supported_packet, PACKET_QTBuffer_size},
4063 { "tracenz", PACKET_DISABLE,
4064 remote_string_tracing_feature, -1 },
4065 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4066 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4067 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4068 PACKET_qXfer_btrace }
4071 static char *remote_support_xml;
4073 /* Register string appended to "xmlRegisters=" in qSupported query. */
4076 register_remote_support_xml (const char *xml)
4078 #if defined(HAVE_LIBEXPAT)
4079 if (remote_support_xml == NULL)
4080 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4083 char *copy = xstrdup (remote_support_xml + 13);
4084 char *p = strtok (copy, ",");
4088 if (strcmp (p, xml) == 0)
4095 while ((p = strtok (NULL, ",")) != NULL);
4098 remote_support_xml = reconcat (remote_support_xml,
4099 remote_support_xml, ",", xml,
4106 remote_query_supported_append (char *msg, const char *append)
4109 return reconcat (msg, msg, ";", append, (char *) NULL);
4111 return xstrdup (append);
4115 remote_query_supported (void)
4117 struct remote_state *rs = get_remote_state ();
4120 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4122 /* The packet support flags are handled differently for this packet
4123 than for most others. We treat an error, a disabled packet, and
4124 an empty response identically: any features which must be reported
4125 to be used will be automatically disabled. An empty buffer
4126 accomplishes this, since that is also the representation for a list
4127 containing no features. */
4130 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
4133 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4135 q = remote_query_supported_append (q, "multiprocess+");
4137 if (remote_support_xml)
4138 q = remote_query_supported_append (q, remote_support_xml);
4140 q = remote_query_supported_append (q, "qRelocInsn+");
4142 q = reconcat (q, "qSupported:", q, (char *) NULL);
4145 do_cleanups (old_chain);
4147 getpkt (&rs->buf, &rs->buf_size, 0);
4149 /* If an error occured, warn, but do not return - just reset the
4150 buffer to empty and go on to disable features. */
4151 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4154 warning (_("Remote failure reply: %s"), rs->buf);
4159 memset (seen, 0, sizeof (seen));
4164 enum packet_support is_supported;
4165 char *p, *end, *name_end, *value;
4167 /* First separate out this item from the rest of the packet. If
4168 there's another item after this, we overwrite the separator
4169 (terminated strings are much easier to work with). */
4171 end = strchr (p, ';');
4174 end = p + strlen (p);
4184 warning (_("empty item in \"qSupported\" response"));
4189 name_end = strchr (p, '=');
4192 /* This is a name=value entry. */
4193 is_supported = PACKET_ENABLE;
4194 value = name_end + 1;
4203 is_supported = PACKET_ENABLE;
4207 is_supported = PACKET_DISABLE;
4211 is_supported = PACKET_SUPPORT_UNKNOWN;
4215 warning (_("unrecognized item \"%s\" "
4216 "in \"qSupported\" response"), p);
4222 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4223 if (strcmp (remote_protocol_features[i].name, p) == 0)
4225 const struct protocol_feature *feature;
4228 feature = &remote_protocol_features[i];
4229 feature->func (feature, is_supported, value);
4234 /* If we increased the packet size, make sure to increase the global
4235 buffer size also. We delay this until after parsing the entire
4236 qSupported packet, because this is the same buffer we were
4238 if (rs->buf_size < rs->explicit_packet_size)
4240 rs->buf_size = rs->explicit_packet_size;
4241 rs->buf = xrealloc (rs->buf, rs->buf_size);
4244 /* Handle the defaults for unmentioned features. */
4245 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4248 const struct protocol_feature *feature;
4250 feature = &remote_protocol_features[i];
4251 feature->func (feature, feature->default_support, NULL);
4255 /* Remove any of the remote.c targets from target stack. Upper targets depend
4256 on it so remove them first. */
4259 remote_unpush_target (void)
4261 pop_all_targets_above (process_stratum - 1);
4265 remote_open_1 (char *name, int from_tty,
4266 struct target_ops *target, int extended_p)
4268 struct remote_state *rs = get_remote_state ();
4271 error (_("To open a remote debug connection, you need to specify what\n"
4272 "serial device is attached to the remote system\n"
4273 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4275 /* See FIXME above. */
4276 if (!target_async_permitted)
4277 wait_forever_enabled_p = 1;
4279 /* If we're connected to a running target, target_preopen will kill it.
4280 Ask this question first, before target_preopen has a chance to kill
4282 if (rs->remote_desc != NULL && !have_inferiors ())
4285 && !query (_("Already connected to a remote target. Disconnect? ")))
4286 error (_("Still connected."));
4289 /* Here the possibly existing remote target gets unpushed. */
4290 target_preopen (from_tty);
4292 /* Make sure we send the passed signals list the next time we resume. */
4293 xfree (rs->last_pass_packet);
4294 rs->last_pass_packet = NULL;
4296 /* Make sure we send the program signals list the next time we
4298 xfree (rs->last_program_signals_packet);
4299 rs->last_program_signals_packet = NULL;
4301 remote_fileio_reset ();
4302 reopen_exec_file ();
4305 rs->remote_desc = remote_serial_open (name);
4306 if (!rs->remote_desc)
4307 perror_with_name (name);
4309 if (baud_rate != -1)
4311 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4313 /* The requested speed could not be set. Error out to
4314 top level after closing remote_desc. Take care to
4315 set remote_desc to NULL to avoid closing remote_desc
4317 serial_close (rs->remote_desc);
4318 rs->remote_desc = NULL;
4319 perror_with_name (name);
4323 serial_raw (rs->remote_desc);
4325 /* If there is something sitting in the buffer we might take it as a
4326 response to a command, which would be bad. */
4327 serial_flush_input (rs->remote_desc);
4331 puts_filtered ("Remote debugging using ");
4332 puts_filtered (name);
4333 puts_filtered ("\n");
4335 push_target (target); /* Switch to using remote target now. */
4337 /* Register extra event sources in the event loop. */
4338 remote_async_inferior_event_token
4339 = create_async_event_handler (remote_async_inferior_event_handler,
4341 rs->notif_state = remote_notif_state_allocate ();
4343 /* Reset the target state; these things will be queried either by
4344 remote_query_supported or as they are needed. */
4345 init_all_packet_configs ();
4346 rs->cached_wait_status = 0;
4347 rs->explicit_packet_size = 0;
4349 rs->multi_process_aware = 0;
4350 rs->extended = extended_p;
4351 rs->non_stop_aware = 0;
4352 rs->waiting_for_stop_reply = 0;
4353 rs->ctrlc_pending_p = 0;
4355 rs->general_thread = not_sent_ptid;
4356 rs->continue_thread = not_sent_ptid;
4357 rs->remote_traceframe_number = -1;
4359 /* Probe for ability to use "ThreadInfo" query, as required. */
4360 rs->use_threadinfo_query = 1;
4361 rs->use_threadextra_query = 1;
4363 if (target_async_permitted)
4365 /* With this target we start out by owning the terminal. */
4366 remote_async_terminal_ours_p = 1;
4368 /* FIXME: cagney/1999-09-23: During the initial connection it is
4369 assumed that the target is already ready and able to respond to
4370 requests. Unfortunately remote_start_remote() eventually calls
4371 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4372 around this. Eventually a mechanism that allows
4373 wait_for_inferior() to expect/get timeouts will be
4375 wait_forever_enabled_p = 0;
4378 /* First delete any symbols previously loaded from shared libraries. */
4379 no_shared_libraries (NULL, 0);
4382 init_thread_list ();
4384 /* Start the remote connection. If error() or QUIT, discard this
4385 target (we'd otherwise be in an inconsistent state) and then
4386 propogate the error on up the exception chain. This ensures that
4387 the caller doesn't stumble along blindly assuming that the
4388 function succeeded. The CLI doesn't have this problem but other
4389 UI's, such as MI do.
4391 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4392 this function should return an error indication letting the
4393 caller restore the previous state. Unfortunately the command
4394 ``target remote'' is directly wired to this function making that
4395 impossible. On a positive note, the CLI side of this problem has
4396 been fixed - the function set_cmd_context() makes it possible for
4397 all the ``target ....'' commands to share a common callback
4398 function. See cli-dump.c. */
4400 volatile struct gdb_exception ex;
4402 TRY_CATCH (ex, RETURN_MASK_ALL)
4404 remote_start_remote (from_tty, target, extended_p);
4408 /* Pop the partially set up target - unless something else did
4409 already before throwing the exception. */
4410 if (rs->remote_desc != NULL)
4411 remote_unpush_target ();
4412 if (target_async_permitted)
4413 wait_forever_enabled_p = 1;
4414 throw_exception (ex);
4418 if (target_async_permitted)
4419 wait_forever_enabled_p = 1;
4422 /* This takes a program previously attached to and detaches it. After
4423 this is done, GDB can be used to debug some other program. We
4424 better not have left any breakpoints in the target program or it'll
4425 die when it hits one. */
4428 remote_detach_1 (char *args, int from_tty, int extended)
4430 int pid = ptid_get_pid (inferior_ptid);
4431 struct remote_state *rs = get_remote_state ();
4434 error (_("Argument given to \"detach\" when remotely debugging."));
4436 if (!target_has_execution)
4437 error (_("No process to detach from."));
4441 char *exec_file = get_exec_file (0);
4442 if (exec_file == NULL)
4444 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4445 target_pid_to_str (pid_to_ptid (pid)));
4446 gdb_flush (gdb_stdout);
4449 /* Tell the remote target to detach. */
4450 if (remote_multi_process_p (rs))
4451 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4453 strcpy (rs->buf, "D");
4456 getpkt (&rs->buf, &rs->buf_size, 0);
4458 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4460 else if (rs->buf[0] == '\0')
4461 error (_("Remote doesn't know how to detach"));
4463 error (_("Can't detach process."));
4465 if (from_tty && !extended)
4466 puts_filtered (_("Ending remote debugging.\n"));
4468 target_mourn_inferior ();
4472 remote_detach (struct target_ops *ops, char *args, int from_tty)
4474 remote_detach_1 (args, from_tty, 0);
4478 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
4480 remote_detach_1 (args, from_tty, 1);
4483 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4486 remote_disconnect (struct target_ops *target, char *args, int from_tty)
4489 error (_("Argument given to \"disconnect\" when remotely debugging."));
4491 /* Make sure we unpush even the extended remote targets; mourn
4492 won't do it. So call remote_mourn_1 directly instead of
4493 target_mourn_inferior. */
4494 remote_mourn_1 (target);
4497 puts_filtered ("Ending remote debugging.\n");
4500 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4501 be chatty about it. */
4504 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4506 struct remote_state *rs = get_remote_state ();
4508 char *wait_status = NULL;
4510 pid = parse_pid_to_attach (args);
4512 /* Remote PID can be freely equal to getpid, do not check it here the same
4513 way as in other targets. */
4515 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4516 error (_("This target does not support attaching to a process"));
4520 char *exec_file = get_exec_file (0);
4523 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4524 target_pid_to_str (pid_to_ptid (pid)));
4526 printf_unfiltered (_("Attaching to %s\n"),
4527 target_pid_to_str (pid_to_ptid (pid)));
4529 gdb_flush (gdb_stdout);
4532 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4534 getpkt (&rs->buf, &rs->buf_size, 0);
4536 if (packet_ok (rs->buf,
4537 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
4541 /* Save the reply for later. */
4542 wait_status = alloca (strlen (rs->buf) + 1);
4543 strcpy (wait_status, rs->buf);
4545 else if (strcmp (rs->buf, "OK") != 0)
4546 error (_("Attaching to %s failed with: %s"),
4547 target_pid_to_str (pid_to_ptid (pid)),
4550 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4551 error (_("This target does not support attaching to a process"));
4553 error (_("Attaching to %s failed"),
4554 target_pid_to_str (pid_to_ptid (pid)));
4556 set_current_inferior (remote_add_inferior (0, pid, 1));
4558 inferior_ptid = pid_to_ptid (pid);
4562 struct thread_info *thread;
4564 /* Get list of threads. */
4565 remote_threads_info (target);
4567 thread = first_thread_of_process (pid);
4569 inferior_ptid = thread->ptid;
4571 inferior_ptid = pid_to_ptid (pid);
4573 /* Invalidate our notion of the remote current thread. */
4574 record_currthread (rs, minus_one_ptid);
4578 /* Now, if we have thread information, update inferior_ptid. */
4579 inferior_ptid = remote_current_thread (inferior_ptid);
4581 /* Add the main thread to the thread list. */
4582 add_thread_silent (inferior_ptid);
4585 /* Next, if the target can specify a description, read it. We do
4586 this before anything involving memory or registers. */
4587 target_find_description ();
4591 /* Use the previously fetched status. */
4592 gdb_assert (wait_status != NULL);
4594 if (target_can_async_p ())
4596 struct notif_event *reply
4597 = remote_notif_parse (¬if_client_stop, wait_status);
4599 push_stop_reply ((struct stop_reply *) reply);
4601 target_async (inferior_event_handler, 0);
4605 gdb_assert (wait_status != NULL);
4606 strcpy (rs->buf, wait_status);
4607 rs->cached_wait_status = 1;
4611 gdb_assert (wait_status == NULL);
4615 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4617 extended_remote_attach_1 (ops, args, from_tty);
4620 /* Convert hex digit A to a number. */
4625 if (a >= '0' && a <= '9')
4627 else if (a >= 'a' && a <= 'f')
4628 return a - 'a' + 10;
4629 else if (a >= 'A' && a <= 'F')
4630 return a - 'A' + 10;
4632 error (_("Reply contains invalid hex digit %d"), a);
4636 hex2bin (const char *hex, gdb_byte *bin, int count)
4640 for (i = 0; i < count; i++)
4642 if (hex[0] == 0 || hex[1] == 0)
4644 /* Hex string is short, or of uneven length.
4645 Return the count that has been converted so far. */
4648 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4654 /* Convert number NIB to a hex digit. */
4662 return 'a' + nib - 10;
4666 bin2hex (const gdb_byte *bin, char *hex, int count)
4670 /* May use a length, or a nul-terminated string as input. */
4672 count = strlen ((char *) bin);
4674 for (i = 0; i < count; i++)
4676 *hex++ = tohex ((*bin >> 4) & 0xf);
4677 *hex++ = tohex (*bin++ & 0xf);
4683 /* Check for the availability of vCont. This function should also check
4687 remote_vcont_probe (struct remote_state *rs)
4691 strcpy (rs->buf, "vCont?");
4693 getpkt (&rs->buf, &rs->buf_size, 0);
4696 /* Make sure that the features we assume are supported. */
4697 if (strncmp (buf, "vCont", 5) == 0)
4700 int support_s, support_S, support_c, support_C;
4706 rs->supports_vCont.t = 0;
4707 rs->supports_vCont.r = 0;
4708 while (p && *p == ';')
4711 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4713 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4715 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4717 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4719 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4720 rs->supports_vCont.t = 1;
4721 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4722 rs->supports_vCont.r = 1;
4724 p = strchr (p, ';');
4727 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4728 BUF will make packet_ok disable the packet. */
4729 if (!support_s || !support_S || !support_c || !support_C)
4733 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4736 /* Helper function for building "vCont" resumptions. Write a
4737 resumption to P. ENDP points to one-passed-the-end of the buffer
4738 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4739 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4740 resumed thread should be single-stepped and/or signalled. If PTID
4741 equals minus_one_ptid, then all threads are resumed; if PTID
4742 represents a process, then all threads of the process are resumed;
4743 the thread to be stepped and/or signalled is given in the global
4747 append_resumption (char *p, char *endp,
4748 ptid_t ptid, int step, enum gdb_signal siggnal)
4750 struct remote_state *rs = get_remote_state ();
4752 if (step && siggnal != GDB_SIGNAL_0)
4753 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4755 /* GDB is willing to range step. */
4756 && use_range_stepping
4757 /* Target supports range stepping. */
4758 && rs->supports_vCont.r
4759 /* We don't currently support range stepping multiple
4760 threads with a wildcard (though the protocol allows it,
4761 so stubs shouldn't make an active effort to forbid
4763 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4765 struct thread_info *tp;
4767 if (ptid_equal (ptid, minus_one_ptid))
4769 /* If we don't know about the target thread's tid, then
4770 we're resuming magic_null_ptid (see caller). */
4771 tp = find_thread_ptid (magic_null_ptid);
4774 tp = find_thread_ptid (ptid);
4775 gdb_assert (tp != NULL);
4777 if (tp->control.may_range_step)
4779 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4781 p += xsnprintf (p, endp - p, ";r%s,%s",
4782 phex_nz (tp->control.step_range_start,
4784 phex_nz (tp->control.step_range_end,
4788 p += xsnprintf (p, endp - p, ";s");
4791 p += xsnprintf (p, endp - p, ";s");
4792 else if (siggnal != GDB_SIGNAL_0)
4793 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4795 p += xsnprintf (p, endp - p, ";c");
4797 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4801 /* All (-1) threads of process. */
4802 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4804 p += xsnprintf (p, endp - p, ":");
4805 p = write_ptid (p, endp, nptid);
4807 else if (!ptid_equal (ptid, minus_one_ptid))
4809 p += xsnprintf (p, endp - p, ":");
4810 p = write_ptid (p, endp, ptid);
4816 /* Append a vCont continue-with-signal action for threads that have a
4817 non-zero stop signal. */
4820 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4822 struct thread_info *thread;
4824 ALL_THREADS (thread)
4825 if (ptid_match (thread->ptid, ptid)
4826 && !ptid_equal (inferior_ptid, thread->ptid)
4827 && thread->suspend.stop_signal != GDB_SIGNAL_0
4828 && signal_pass_state (thread->suspend.stop_signal))
4830 p = append_resumption (p, endp, thread->ptid,
4831 0, thread->suspend.stop_signal);
4832 thread->suspend.stop_signal = GDB_SIGNAL_0;
4838 /* Resume the remote inferior by using a "vCont" packet. The thread
4839 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4840 resumed thread should be single-stepped and/or signalled. If PTID
4841 equals minus_one_ptid, then all threads are resumed; the thread to
4842 be stepped and/or signalled is given in the global INFERIOR_PTID.
4843 This function returns non-zero iff it resumes the inferior.
4845 This function issues a strict subset of all possible vCont commands at the
4849 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4851 struct remote_state *rs = get_remote_state ();
4855 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4856 remote_vcont_probe (rs);
4858 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4862 endp = rs->buf + get_remote_packet_size ();
4864 /* If we could generate a wider range of packets, we'd have to worry
4865 about overflowing BUF. Should there be a generic
4866 "multi-part-packet" packet? */
4868 p += xsnprintf (p, endp - p, "vCont");
4870 if (ptid_equal (ptid, magic_null_ptid))
4872 /* MAGIC_NULL_PTID means that we don't have any active threads,
4873 so we don't have any TID numbers the inferior will
4874 understand. Make sure to only send forms that do not specify
4876 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4878 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4880 /* Resume all threads (of all processes, or of a single
4881 process), with preference for INFERIOR_PTID. This assumes
4882 inferior_ptid belongs to the set of all threads we are about
4884 if (step || siggnal != GDB_SIGNAL_0)
4886 /* Step inferior_ptid, with or without signal. */
4887 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4890 /* Also pass down any pending signaled resumption for other
4891 threads not the current. */
4892 p = append_pending_thread_resumptions (p, endp, ptid);
4894 /* And continue others without a signal. */
4895 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4899 /* Scheduler locking; resume only PTID. */
4900 append_resumption (p, endp, ptid, step, siggnal);
4903 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4908 /* In non-stop, the stub replies to vCont with "OK". The stop
4909 reply will be reported asynchronously by means of a `%Stop'
4911 getpkt (&rs->buf, &rs->buf_size, 0);
4912 if (strcmp (rs->buf, "OK") != 0)
4913 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4919 /* Tell the remote machine to resume. */
4922 remote_resume (struct target_ops *ops,
4923 ptid_t ptid, int step, enum gdb_signal siggnal)
4925 struct remote_state *rs = get_remote_state ();
4928 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4929 (explained in remote-notif.c:handle_notification) so
4930 remote_notif_process is not called. We need find a place where
4931 it is safe to start a 'vNotif' sequence. It is good to do it
4932 before resuming inferior, because inferior was stopped and no RSP
4933 traffic at that moment. */
4935 remote_notif_process (rs->notif_state, ¬if_client_stop);
4937 rs->last_sent_signal = siggnal;
4938 rs->last_sent_step = step;
4940 /* The vCont packet doesn't need to specify threads via Hc. */
4941 /* No reverse support (yet) for vCont. */
4942 if (execution_direction != EXEC_REVERSE)
4943 if (remote_vcont_resume (ptid, step, siggnal))
4946 /* All other supported resume packets do use Hc, so set the continue
4948 if (ptid_equal (ptid, minus_one_ptid))
4949 set_continue_thread (any_thread_ptid);
4951 set_continue_thread (ptid);
4954 if (execution_direction == EXEC_REVERSE)
4956 /* We don't pass signals to the target in reverse exec mode. */
4957 if (info_verbose && siggnal != GDB_SIGNAL_0)
4958 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4962 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4963 error (_("Remote reverse-step not supported."));
4965 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4966 error (_("Remote reverse-continue not supported."));
4968 strcpy (buf, step ? "bs" : "bc");
4970 else if (siggnal != GDB_SIGNAL_0)
4972 buf[0] = step ? 'S' : 'C';
4973 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4974 buf[2] = tohex (((int) siggnal) & 0xf);
4978 strcpy (buf, step ? "s" : "c");
4983 /* We are about to start executing the inferior, let's register it
4984 with the event loop. NOTE: this is the one place where all the
4985 execution commands end up. We could alternatively do this in each
4986 of the execution commands in infcmd.c. */
4987 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4988 into infcmd.c in order to allow inferior function calls to work
4989 NOT asynchronously. */
4990 if (target_can_async_p ())
4991 target_async (inferior_event_handler, 0);
4993 /* We've just told the target to resume. The remote server will
4994 wait for the inferior to stop, and then send a stop reply. In
4995 the mean time, we can't start another command/query ourselves
4996 because the stub wouldn't be ready to process it. This applies
4997 only to the base all-stop protocol, however. In non-stop (which
4998 only supports vCont), the stub replies with an "OK", and is
4999 immediate able to process further serial input. */
5001 rs->waiting_for_stop_reply = 1;
5005 /* Set up the signal handler for SIGINT, while the target is
5006 executing, ovewriting the 'regular' SIGINT signal handler. */
5008 async_initialize_sigint_signal_handler (void)
5010 signal (SIGINT, async_handle_remote_sigint);
5013 /* Signal handler for SIGINT, while the target is executing. */
5015 async_handle_remote_sigint (int sig)
5017 signal (sig, async_handle_remote_sigint_twice);
5018 mark_async_signal_handler (async_sigint_remote_token);
5021 /* Signal handler for SIGINT, installed after SIGINT has already been
5022 sent once. It will take effect the second time that the user sends
5025 async_handle_remote_sigint_twice (int sig)
5027 signal (sig, async_handle_remote_sigint);
5028 mark_async_signal_handler (async_sigint_remote_twice_token);
5031 /* Perform the real interruption of the target execution, in response
5034 async_remote_interrupt (gdb_client_data arg)
5037 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5039 target_stop (inferior_ptid);
5042 /* Perform interrupt, if the first attempt did not succeed. Just give
5043 up on the target alltogether. */
5045 async_remote_interrupt_twice (gdb_client_data arg)
5048 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5053 /* Reinstall the usual SIGINT handlers, after the target has
5056 async_cleanup_sigint_signal_handler (void *dummy)
5058 signal (SIGINT, handle_sigint);
5061 /* Send ^C to target to halt it. Target will respond, and send us a
5063 static void (*ofunc) (int);
5065 /* The command line interface's stop routine. This function is installed
5066 as a signal handler for SIGINT. The first time a user requests a
5067 stop, we call remote_stop to send a break or ^C. If there is no
5068 response from the target (it didn't stop when the user requested it),
5069 we ask the user if he'd like to detach from the target. */
5071 sync_remote_interrupt (int signo)
5073 /* If this doesn't work, try more severe steps. */
5074 signal (signo, sync_remote_interrupt_twice);
5076 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5079 /* The user typed ^C twice. */
5082 sync_remote_interrupt_twice (int signo)
5084 signal (signo, ofunc);
5085 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5086 signal (signo, sync_remote_interrupt);
5089 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5090 thread, all threads of a remote process, or all threads of all
5094 remote_stop_ns (ptid_t ptid)
5096 struct remote_state *rs = get_remote_state ();
5098 char *endp = rs->buf + get_remote_packet_size ();
5100 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
5101 remote_vcont_probe (rs);
5103 if (!rs->supports_vCont.t)
5104 error (_("Remote server does not support stopping threads"));
5106 if (ptid_equal (ptid, minus_one_ptid)
5107 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5108 p += xsnprintf (p, endp - p, "vCont;t");
5113 p += xsnprintf (p, endp - p, "vCont;t:");
5115 if (ptid_is_pid (ptid))
5116 /* All (-1) threads of process. */
5117 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
5120 /* Small optimization: if we already have a stop reply for
5121 this thread, no use in telling the stub we want this
5123 if (peek_stop_reply (ptid))
5129 write_ptid (p, endp, nptid);
5132 /* In non-stop, we get an immediate OK reply. The stop reply will
5133 come in asynchronously by notification. */
5135 getpkt (&rs->buf, &rs->buf_size, 0);
5136 if (strcmp (rs->buf, "OK") != 0)
5137 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5140 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5141 remote target. It is undefined which thread of which process
5142 reports the stop. */
5145 remote_stop_as (ptid_t ptid)
5147 struct remote_state *rs = get_remote_state ();
5149 rs->ctrlc_pending_p = 1;
5151 /* If the inferior is stopped already, but the core didn't know
5152 about it yet, just ignore the request. The cached wait status
5153 will be collected in remote_wait. */
5154 if (rs->cached_wait_status)
5157 /* Send interrupt_sequence to remote target. */
5158 send_interrupt_sequence ();
5161 /* This is the generic stop called via the target vector. When a target
5162 interrupt is requested, either by the command line or the GUI, we
5163 will eventually end up here. */
5166 remote_stop (ptid_t ptid)
5169 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5172 remote_stop_ns (ptid);
5174 remote_stop_as (ptid);
5177 /* Ask the user what to do when an interrupt is received. */
5180 interrupt_query (void)
5182 target_terminal_ours ();
5184 if (target_can_async_p ())
5186 signal (SIGINT, handle_sigint);
5191 if (query (_("Interrupted while waiting for the program.\n\
5192 Give up (and stop debugging it)? ")))
5194 remote_unpush_target ();
5199 target_terminal_inferior ();
5202 /* Enable/disable target terminal ownership. Most targets can use
5203 terminal groups to control terminal ownership. Remote targets are
5204 different in that explicit transfer of ownership to/from GDB/target
5208 remote_terminal_inferior (void)
5210 if (!target_async_permitted)
5211 /* Nothing to do. */
5214 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5215 idempotent. The event-loop GDB talking to an asynchronous target
5216 with a synchronous command calls this function from both
5217 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5218 transfer the terminal to the target when it shouldn't this guard
5220 if (!remote_async_terminal_ours_p)
5222 delete_file_handler (input_fd);
5223 remote_async_terminal_ours_p = 0;
5224 async_initialize_sigint_signal_handler ();
5225 /* NOTE: At this point we could also register our selves as the
5226 recipient of all input. Any characters typed could then be
5227 passed on down to the target. */
5231 remote_terminal_ours (void)
5233 if (!target_async_permitted)
5234 /* Nothing to do. */
5237 /* See FIXME in remote_terminal_inferior. */
5238 if (remote_async_terminal_ours_p)
5240 async_cleanup_sigint_signal_handler (NULL);
5241 add_file_handler (input_fd, stdin_event_handler, 0);
5242 remote_async_terminal_ours_p = 1;
5246 remote_console_output (char *msg)
5250 for (p = msg; p[0] && p[1]; p += 2)
5253 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5257 fputs_unfiltered (tb, gdb_stdtarg);
5259 gdb_flush (gdb_stdtarg);
5262 typedef struct cached_reg
5265 gdb_byte data[MAX_REGISTER_SIZE];
5268 DEF_VEC_O(cached_reg_t);
5270 typedef struct stop_reply
5272 struct notif_event base;
5274 /* The identifier of the thread about this event */
5277 /* The remote state this event is associated with. When the remote
5278 connection, represented by a remote_state object, is closed,
5279 all the associated stop_reply events should be released. */
5280 struct remote_state *rs;
5282 struct target_waitstatus ws;
5284 /* Expedited registers. This makes remote debugging a bit more
5285 efficient for those targets that provide critical registers as
5286 part of their normal status mechanism (as another roundtrip to
5287 fetch them is avoided). */
5288 VEC(cached_reg_t) *regcache;
5290 int stopped_by_watchpoint_p;
5291 CORE_ADDR watch_data_address;
5296 DECLARE_QUEUE_P (stop_reply_p);
5297 DEFINE_QUEUE_P (stop_reply_p);
5298 /* The list of already fetched and acknowledged stop events. This
5299 queue is used for notification Stop, and other notifications
5300 don't need queue for their events, because the notification events
5301 of Stop can't be consumed immediately, so that events should be
5302 queued first, and be consumed by remote_wait_{ns,as} one per
5303 time. Other notifications can consume their events immediately,
5304 so queue is not needed for them. */
5305 static QUEUE (stop_reply_p) *stop_reply_queue;
5308 stop_reply_xfree (struct stop_reply *r)
5310 notif_event_xfree ((struct notif_event *) r);
5314 remote_notif_stop_parse (struct notif_client *self, char *buf,
5315 struct notif_event *event)
5317 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5321 remote_notif_stop_ack (struct notif_client *self, char *buf,
5322 struct notif_event *event)
5324 struct stop_reply *stop_reply = (struct stop_reply *) event;
5327 putpkt ((char *) self->ack_command);
5329 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5330 /* We got an unknown stop reply. */
5331 error (_("Unknown stop reply"));
5333 push_stop_reply (stop_reply);
5337 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5339 /* We can't get pending events in remote_notif_process for
5340 notification stop, and we have to do this in remote_wait_ns
5341 instead. If we fetch all queued events from stub, remote stub
5342 may exit and we have no chance to process them back in
5344 mark_async_event_handler (remote_async_inferior_event_token);
5349 stop_reply_dtr (struct notif_event *event)
5351 struct stop_reply *r = (struct stop_reply *) event;
5353 VEC_free (cached_reg_t, r->regcache);
5356 static struct notif_event *
5357 remote_notif_stop_alloc_reply (void)
5359 struct notif_event *r
5360 = (struct notif_event *) XMALLOC (struct stop_reply);
5362 r->dtr = stop_reply_dtr;
5367 /* A client of notification Stop. */
5369 struct notif_client notif_client_stop =
5373 remote_notif_stop_parse,
5374 remote_notif_stop_ack,
5375 remote_notif_stop_can_get_pending_events,
5376 remote_notif_stop_alloc_reply,
5380 /* A parameter to pass data in and out. */
5382 struct queue_iter_param
5385 struct stop_reply *output;
5388 /* Remove stop replies in the queue if its pid is equal to the given
5392 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5393 QUEUE_ITER (stop_reply_p) *iter,
5397 struct queue_iter_param *param = data;
5398 struct inferior *inf = param->input;
5400 if (ptid_get_pid (event->ptid) == inf->pid)
5402 stop_reply_xfree (event);
5403 QUEUE_remove_elem (stop_reply_p, q, iter);
5409 /* Discard all pending stop replies of inferior INF. */
5412 discard_pending_stop_replies (struct inferior *inf)
5415 struct queue_iter_param param;
5416 struct stop_reply *reply;
5417 struct remote_state *rs = get_remote_state ();
5418 struct remote_notif_state *rns = rs->notif_state;
5420 /* This function can be notified when an inferior exists. When the
5421 target is not remote, the notification state is NULL. */
5422 if (rs->remote_desc == NULL)
5425 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5427 /* Discard the in-flight notification. */
5428 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5430 stop_reply_xfree (reply);
5431 rns->pending_event[notif_client_stop.id] = NULL;
5435 param.output = NULL;
5436 /* Discard the stop replies we have already pulled with
5438 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5439 remove_stop_reply_for_inferior, ¶m);
5442 /* If its remote state is equal to the given remote state,
5443 remove EVENT from the stop reply queue. */
5446 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5447 QUEUE_ITER (stop_reply_p) *iter,
5451 struct queue_iter_param *param = data;
5452 struct remote_state *rs = param->input;
5454 if (event->rs == rs)
5456 stop_reply_xfree (event);
5457 QUEUE_remove_elem (stop_reply_p, q, iter);
5463 /* Discard the stop replies for RS in stop_reply_queue. */
5466 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5468 struct queue_iter_param param;
5471 param.output = NULL;
5472 /* Discard the stop replies we have already pulled with
5474 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5475 remove_stop_reply_of_remote_state, ¶m);
5478 /* A parameter to pass data in and out. */
5481 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5482 QUEUE_ITER (stop_reply_p) *iter,
5486 struct queue_iter_param *param = data;
5487 ptid_t *ptid = param->input;
5489 if (ptid_match (event->ptid, *ptid))
5491 param->output = event;
5492 QUEUE_remove_elem (stop_reply_p, q, iter);
5499 /* Remove the first reply in 'stop_reply_queue' which matches
5502 static struct stop_reply *
5503 remote_notif_remove_queued_reply (ptid_t ptid)
5505 struct queue_iter_param param;
5507 param.input = &ptid;
5508 param.output = NULL;
5510 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5511 remote_notif_remove_once_on_match, ¶m);
5513 fprintf_unfiltered (gdb_stdlog,
5514 "notif: discard queued event: 'Stop' in %s\n",
5515 target_pid_to_str (ptid));
5517 return param.output;
5520 /* Look for a queued stop reply belonging to PTID. If one is found,
5521 remove it from the queue, and return it. Returns NULL if none is
5522 found. If there are still queued events left to process, tell the
5523 event loop to get back to target_wait soon. */
5525 static struct stop_reply *
5526 queued_stop_reply (ptid_t ptid)
5528 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5530 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5531 /* There's still at least an event left. */
5532 mark_async_event_handler (remote_async_inferior_event_token);
5537 /* Push a fully parsed stop reply in the stop reply queue. Since we
5538 know that we now have at least one queued event left to pass to the
5539 core side, tell the event loop to get back to target_wait soon. */
5542 push_stop_reply (struct stop_reply *new_event)
5544 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5547 fprintf_unfiltered (gdb_stdlog,
5548 "notif: push 'Stop' %s to queue %d\n",
5549 target_pid_to_str (new_event->ptid),
5550 QUEUE_length (stop_reply_p,
5553 mark_async_event_handler (remote_async_inferior_event_token);
5557 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5558 QUEUE_ITER (stop_reply_p) *iter,
5559 struct stop_reply *event,
5562 ptid_t *ptid = data;
5564 return !(ptid_equal (*ptid, event->ptid)
5565 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5568 /* Returns true if we have a stop reply for PTID. */
5571 peek_stop_reply (ptid_t ptid)
5573 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5574 stop_reply_match_ptid_and_ws, &ptid);
5577 /* Parse the stop reply in BUF. Either the function succeeds, and the
5578 result is stored in EVENT, or throws an error. */
5581 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5583 struct remote_arch_state *rsa = get_remote_arch_state ();
5587 event->ptid = null_ptid;
5588 event->rs = get_remote_state ();
5589 event->ws.kind = TARGET_WAITKIND_IGNORE;
5590 event->ws.value.integer = 0;
5591 event->stopped_by_watchpoint_p = 0;
5592 event->regcache = NULL;
5597 case 'T': /* Status with PC, SP, FP, ... */
5598 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5599 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5601 n... = register number
5602 r... = register contents
5605 p = &buf[3]; /* after Txx */
5613 /* If the packet contains a register number, save it in
5614 pnum and set p1 to point to the character following it.
5615 Otherwise p1 points to p. */
5617 /* If this packet is an awatch packet, don't parse the 'a'
5618 as a register number. */
5620 if (strncmp (p, "awatch", strlen("awatch")) != 0
5621 && strncmp (p, "core", strlen ("core") != 0))
5623 /* Read the ``P'' register number. */
5624 pnum = strtol (p, &p_temp, 16);
5630 if (p1 == p) /* No register number present here. */
5632 p1 = strchr (p, ':');
5634 error (_("Malformed packet(a) (missing colon): %s\n\
5637 if (strncmp (p, "thread", p1 - p) == 0)
5638 event->ptid = read_ptid (++p1, &p);
5639 else if ((strncmp (p, "watch", p1 - p) == 0)
5640 || (strncmp (p, "rwatch", p1 - p) == 0)
5641 || (strncmp (p, "awatch", p1 - p) == 0))
5643 event->stopped_by_watchpoint_p = 1;
5644 p = unpack_varlen_hex (++p1, &addr);
5645 event->watch_data_address = (CORE_ADDR) addr;
5647 else if (strncmp (p, "library", p1 - p) == 0)
5651 while (*p_temp && *p_temp != ';')
5654 event->ws.kind = TARGET_WAITKIND_LOADED;
5657 else if (strncmp (p, "replaylog", p1 - p) == 0)
5659 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5660 /* p1 will indicate "begin" or "end", but it makes
5661 no difference for now, so ignore it. */
5662 p_temp = strchr (p1 + 1, ';');
5666 else if (strncmp (p, "core", p1 - p) == 0)
5670 p = unpack_varlen_hex (++p1, &c);
5675 /* Silently skip unknown optional info. */
5676 p_temp = strchr (p1 + 1, ';');
5683 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5684 cached_reg_t cached_reg;
5689 error (_("Malformed packet(b) (missing colon): %s\n\
5695 error (_("Remote sent bad register number %s: %s\n\
5697 hex_string (pnum), p, buf);
5699 cached_reg.num = reg->regnum;
5701 fieldsize = hex2bin (p, cached_reg.data,
5702 register_size (target_gdbarch (),
5705 if (fieldsize < register_size (target_gdbarch (),
5707 warning (_("Remote reply is too short: %s"), buf);
5709 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5713 error (_("Remote register badly formatted: %s\nhere: %s"),
5718 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5722 case 'S': /* Old style status, just signal only. */
5726 event->ws.kind = TARGET_WAITKIND_STOPPED;
5727 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5728 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5729 event->ws.value.sig = (enum gdb_signal) sig;
5731 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5734 case 'W': /* Target exited. */
5741 /* GDB used to accept only 2 hex chars here. Stubs should
5742 only send more if they detect GDB supports multi-process
5744 p = unpack_varlen_hex (&buf[1], &value);
5748 /* The remote process exited. */
5749 event->ws.kind = TARGET_WAITKIND_EXITED;
5750 event->ws.value.integer = value;
5754 /* The remote process exited with a signal. */
5755 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5756 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5757 event->ws.value.sig = (enum gdb_signal) value;
5759 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5762 /* If no process is specified, assume inferior_ptid. */
5763 pid = ptid_get_pid (inferior_ptid);
5772 else if (strncmp (p,
5773 "process:", sizeof ("process:") - 1) == 0)
5777 p += sizeof ("process:") - 1;
5778 unpack_varlen_hex (p, &upid);
5782 error (_("unknown stop reply packet: %s"), buf);
5785 error (_("unknown stop reply packet: %s"), buf);
5786 event->ptid = pid_to_ptid (pid);
5791 if (non_stop && ptid_equal (event->ptid, null_ptid))
5792 error (_("No process or thread specified in stop reply: %s"), buf);
5795 /* When the stub wants to tell GDB about a new notification reply, it
5796 sends a notification (%Stop, for example). Those can come it at
5797 any time, hence, we have to make sure that any pending
5798 putpkt/getpkt sequence we're making is finished, before querying
5799 the stub for more events with the corresponding ack command
5800 (vStopped, for example). E.g., if we started a vStopped sequence
5801 immediately upon receiving the notification, something like this
5809 1.6) <-- (registers reply to step #1.3)
5811 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5814 To solve this, whenever we parse a %Stop notification successfully,
5815 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5816 doing whatever we were doing:
5822 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5823 2.5) <-- (registers reply to step #2.3)
5825 Eventualy after step #2.5, we return to the event loop, which
5826 notices there's an event on the
5827 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5828 associated callback --- the function below. At this point, we're
5829 always safe to start a vStopped sequence. :
5832 2.7) <-- T05 thread:2
5838 remote_notif_get_pending_events (struct notif_client *nc)
5840 struct remote_state *rs = get_remote_state ();
5842 if (rs->notif_state->pending_event[nc->id] != NULL)
5845 fprintf_unfiltered (gdb_stdlog,
5846 "notif: process: '%s' ack pending event\n",
5850 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5851 rs->notif_state->pending_event[nc->id] = NULL;
5855 getpkt (&rs->buf, &rs->buf_size, 0);
5856 if (strcmp (rs->buf, "OK") == 0)
5859 remote_notif_ack (nc, rs->buf);
5865 fprintf_unfiltered (gdb_stdlog,
5866 "notif: process: '%s' no pending reply\n",
5871 /* Called when it is decided that STOP_REPLY holds the info of the
5872 event that is to be returned to the core. This function always
5873 destroys STOP_REPLY. */
5876 process_stop_reply (struct stop_reply *stop_reply,
5877 struct target_waitstatus *status)
5881 *status = stop_reply->ws;
5882 ptid = stop_reply->ptid;
5884 /* If no thread/process was reported by the stub, assume the current
5886 if (ptid_equal (ptid, null_ptid))
5887 ptid = inferior_ptid;
5889 if (status->kind != TARGET_WAITKIND_EXITED
5890 && status->kind != TARGET_WAITKIND_SIGNALLED)
5892 struct remote_state *rs = get_remote_state ();
5894 /* Expedited registers. */
5895 if (stop_reply->regcache)
5897 struct regcache *regcache
5898 = get_thread_arch_regcache (ptid, target_gdbarch ());
5903 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5905 regcache_raw_supply (regcache, reg->num, reg->data);
5906 VEC_free (cached_reg_t, stop_reply->regcache);
5909 rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5910 rs->remote_watch_data_address = stop_reply->watch_data_address;
5912 remote_notice_new_inferior (ptid, 0);
5913 demand_private_info (ptid)->core = stop_reply->core;
5916 stop_reply_xfree (stop_reply);
5920 /* The non-stop mode version of target_wait. */
5923 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5925 struct remote_state *rs = get_remote_state ();
5926 struct stop_reply *stop_reply;
5930 /* If in non-stop mode, get out of getpkt even if a
5931 notification is received. */
5933 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5934 0 /* forever */, &is_notif);
5937 if (ret != -1 && !is_notif)
5940 case 'E': /* Error of some sort. */
5941 /* We're out of sync with the target now. Did it continue
5942 or not? We can't tell which thread it was in non-stop,
5943 so just ignore this. */
5944 warning (_("Remote failure reply: %s"), rs->buf);
5946 case 'O': /* Console output. */
5947 remote_console_output (rs->buf + 1);
5950 warning (_("Invalid remote reply: %s"), rs->buf);
5954 /* Acknowledge a pending stop reply that may have arrived in the
5956 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
5957 remote_notif_get_pending_events (¬if_client_stop);
5959 /* If indeed we noticed a stop reply, we're done. */
5960 stop_reply = queued_stop_reply (ptid);
5961 if (stop_reply != NULL)
5962 return process_stop_reply (stop_reply, status);
5964 /* Still no event. If we're just polling for an event, then
5965 return to the event loop. */
5966 if (options & TARGET_WNOHANG)
5968 status->kind = TARGET_WAITKIND_IGNORE;
5969 return minus_one_ptid;
5972 /* Otherwise do a blocking wait. */
5973 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5974 1 /* forever */, &is_notif);
5978 /* Wait until the remote machine stops, then return, storing status in
5979 STATUS just as `wait' would. */
5982 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5984 struct remote_state *rs = get_remote_state ();
5985 ptid_t event_ptid = null_ptid;
5987 struct stop_reply *stop_reply;
5991 status->kind = TARGET_WAITKIND_IGNORE;
5992 status->value.integer = 0;
5994 stop_reply = queued_stop_reply (ptid);
5995 if (stop_reply != NULL)
5996 return process_stop_reply (stop_reply, status);
5998 if (rs->cached_wait_status)
5999 /* Use the cached wait status, but only once. */
6000 rs->cached_wait_status = 0;
6006 if (!target_is_async_p ())
6008 ofunc = signal (SIGINT, sync_remote_interrupt);
6009 /* If the user hit C-c before this packet, or between packets,
6010 pretend that it was hit right here. */
6011 if (check_quit_flag ())
6014 sync_remote_interrupt (SIGINT);
6018 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6019 _never_ wait for ever -> test on target_is_async_p().
6020 However, before we do that we need to ensure that the caller
6021 knows how to take the target into/out of async mode. */
6022 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6023 wait_forever_enabled_p, &is_notif);
6025 if (!target_is_async_p ())
6026 signal (SIGINT, ofunc);
6028 /* GDB gets a notification. Return to core as this event is
6030 if (ret != -1 && is_notif)
6031 return minus_one_ptid;
6036 rs->remote_stopped_by_watchpoint_p = 0;
6038 /* We got something. */
6039 rs->waiting_for_stop_reply = 0;
6041 /* Assume that the target has acknowledged Ctrl-C unless we receive
6042 an 'F' or 'O' packet. */
6043 if (buf[0] != 'F' && buf[0] != 'O')
6044 rs->ctrlc_pending_p = 0;
6048 case 'E': /* Error of some sort. */
6049 /* We're out of sync with the target now. Did it continue or
6050 not? Not is more likely, so report a stop. */
6051 warning (_("Remote failure reply: %s"), buf);
6052 status->kind = TARGET_WAITKIND_STOPPED;
6053 status->value.sig = GDB_SIGNAL_0;
6055 case 'F': /* File-I/O request. */
6056 remote_fileio_request (buf, rs->ctrlc_pending_p);
6057 rs->ctrlc_pending_p = 0;
6059 case 'T': case 'S': case 'X': case 'W':
6061 struct stop_reply *stop_reply
6062 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6065 event_ptid = process_stop_reply (stop_reply, status);
6068 case 'O': /* Console output. */
6069 remote_console_output (buf + 1);
6071 /* The target didn't really stop; keep waiting. */
6072 rs->waiting_for_stop_reply = 1;
6076 if (rs->last_sent_signal != GDB_SIGNAL_0)
6078 /* Zero length reply means that we tried 'S' or 'C' and the
6079 remote system doesn't support it. */
6080 target_terminal_ours_for_output ();
6082 ("Can't send signals to this remote system. %s not sent.\n",
6083 gdb_signal_to_name (rs->last_sent_signal));
6084 rs->last_sent_signal = GDB_SIGNAL_0;
6085 target_terminal_inferior ();
6087 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6088 putpkt ((char *) buf);
6090 /* We just told the target to resume, so a stop reply is in
6092 rs->waiting_for_stop_reply = 1;
6095 /* else fallthrough */
6097 warning (_("Invalid remote reply: %s"), buf);
6099 rs->waiting_for_stop_reply = 1;
6103 if (status->kind == TARGET_WAITKIND_IGNORE)
6105 /* Nothing interesting happened. If we're doing a non-blocking
6106 poll, we're done. Otherwise, go back to waiting. */
6107 if (options & TARGET_WNOHANG)
6108 return minus_one_ptid;
6112 else if (status->kind != TARGET_WAITKIND_EXITED
6113 && status->kind != TARGET_WAITKIND_SIGNALLED)
6115 if (!ptid_equal (event_ptid, null_ptid))
6116 record_currthread (rs, event_ptid);
6118 event_ptid = inferior_ptid;
6121 /* A process exit. Invalidate our notion of current thread. */
6122 record_currthread (rs, minus_one_ptid);
6127 /* Wait until the remote machine stops, then return, storing status in
6128 STATUS just as `wait' would. */
6131 remote_wait (struct target_ops *ops,
6132 ptid_t ptid, struct target_waitstatus *status, int options)
6137 event_ptid = remote_wait_ns (ptid, status, options);
6139 event_ptid = remote_wait_as (ptid, status, options);
6141 if (target_can_async_p ())
6143 /* If there are are events left in the queue tell the event loop
6145 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6146 mark_async_event_handler (remote_async_inferior_event_token);
6152 /* Fetch a single register using a 'p' packet. */
6155 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6157 struct remote_state *rs = get_remote_state ();
6159 char regp[MAX_REGISTER_SIZE];
6162 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
6165 if (reg->pnum == -1)
6170 p += hexnumstr (p, reg->pnum);
6173 getpkt (&rs->buf, &rs->buf_size, 0);
6177 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6181 case PACKET_UNKNOWN:
6184 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6185 gdbarch_register_name (get_regcache_arch (regcache),
6190 /* If this register is unfetchable, tell the regcache. */
6193 regcache_raw_supply (regcache, reg->regnum, NULL);
6197 /* Otherwise, parse and supply the value. */
6203 error (_("fetch_register_using_p: early buf termination"));
6205 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6208 regcache_raw_supply (regcache, reg->regnum, regp);
6212 /* Fetch the registers included in the target's 'g' packet. */
6215 send_g_packet (void)
6217 struct remote_state *rs = get_remote_state ();
6220 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6221 remote_send (&rs->buf, &rs->buf_size);
6223 /* We can get out of synch in various cases. If the first character
6224 in the buffer is not a hex character, assume that has happened
6225 and try to fetch another packet to read. */
6226 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6227 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6228 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6229 && rs->buf[0] != 'x') /* New: unavailable register value. */
6232 fprintf_unfiltered (gdb_stdlog,
6233 "Bad register packet; fetching a new packet\n");
6234 getpkt (&rs->buf, &rs->buf_size, 0);
6237 buf_len = strlen (rs->buf);
6239 /* Sanity check the received packet. */
6240 if (buf_len % 2 != 0)
6241 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6247 process_g_packet (struct regcache *regcache)
6249 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6250 struct remote_state *rs = get_remote_state ();
6251 struct remote_arch_state *rsa = get_remote_arch_state ();
6256 buf_len = strlen (rs->buf);
6258 /* Further sanity checks, with knowledge of the architecture. */
6259 if (buf_len > 2 * rsa->sizeof_g_packet)
6260 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6262 /* Save the size of the packet sent to us by the target. It is used
6263 as a heuristic when determining the max size of packets that the
6264 target can safely receive. */
6265 if (rsa->actual_register_packet_size == 0)
6266 rsa->actual_register_packet_size = buf_len;
6268 /* If this is smaller than we guessed the 'g' packet would be,
6269 update our records. A 'g' reply that doesn't include a register's
6270 value implies either that the register is not available, or that
6271 the 'p' packet must be used. */
6272 if (buf_len < 2 * rsa->sizeof_g_packet)
6274 rsa->sizeof_g_packet = buf_len / 2;
6276 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6278 if (rsa->regs[i].pnum == -1)
6281 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6282 rsa->regs[i].in_g_packet = 0;
6284 rsa->regs[i].in_g_packet = 1;
6288 regs = alloca (rsa->sizeof_g_packet);
6290 /* Unimplemented registers read as all bits zero. */
6291 memset (regs, 0, rsa->sizeof_g_packet);
6293 /* Reply describes registers byte by byte, each byte encoded as two
6294 hex characters. Suck them all up, then supply them to the
6295 register cacheing/storage mechanism. */
6298 for (i = 0; i < rsa->sizeof_g_packet; i++)
6300 if (p[0] == 0 || p[1] == 0)
6301 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6302 internal_error (__FILE__, __LINE__,
6303 _("unexpected end of 'g' packet reply"));
6305 if (p[0] == 'x' && p[1] == 'x')
6306 regs[i] = 0; /* 'x' */
6308 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6312 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6314 struct packet_reg *r = &rsa->regs[i];
6318 if (r->offset * 2 >= strlen (rs->buf))
6319 /* This shouldn't happen - we adjusted in_g_packet above. */
6320 internal_error (__FILE__, __LINE__,
6321 _("unexpected end of 'g' packet reply"));
6322 else if (rs->buf[r->offset * 2] == 'x')
6324 gdb_assert (r->offset * 2 < strlen (rs->buf));
6325 /* The register isn't available, mark it as such (at
6326 the same time setting the value to zero). */
6327 regcache_raw_supply (regcache, r->regnum, NULL);
6330 regcache_raw_supply (regcache, r->regnum,
6337 fetch_registers_using_g (struct regcache *regcache)
6340 process_g_packet (regcache);
6343 /* Make the remote selected traceframe match GDB's selected
6347 set_remote_traceframe (void)
6350 struct remote_state *rs = get_remote_state ();
6352 if (rs->remote_traceframe_number == get_traceframe_number ())
6355 /* Avoid recursion, remote_trace_find calls us again. */
6356 rs->remote_traceframe_number = get_traceframe_number ();
6358 newnum = target_trace_find (tfind_number,
6359 get_traceframe_number (), 0, 0, NULL);
6361 /* Should not happen. If it does, all bets are off. */
6362 if (newnum != get_traceframe_number ())
6363 warning (_("could not set remote traceframe"));
6367 remote_fetch_registers (struct target_ops *ops,
6368 struct regcache *regcache, int regnum)
6370 struct remote_arch_state *rsa = get_remote_arch_state ();
6373 set_remote_traceframe ();
6374 set_general_thread (inferior_ptid);
6378 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6380 gdb_assert (reg != NULL);
6382 /* If this register might be in the 'g' packet, try that first -
6383 we are likely to read more than one register. If this is the
6384 first 'g' packet, we might be overly optimistic about its
6385 contents, so fall back to 'p'. */
6386 if (reg->in_g_packet)
6388 fetch_registers_using_g (regcache);
6389 if (reg->in_g_packet)
6393 if (fetch_register_using_p (regcache, reg))
6396 /* This register is not available. */
6397 regcache_raw_supply (regcache, reg->regnum, NULL);
6402 fetch_registers_using_g (regcache);
6404 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6405 if (!rsa->regs[i].in_g_packet)
6406 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6408 /* This register is not available. */
6409 regcache_raw_supply (regcache, i, NULL);
6413 /* Prepare to store registers. Since we may send them all (using a
6414 'G' request), we have to read out the ones we don't want to change
6418 remote_prepare_to_store (struct regcache *regcache)
6420 struct remote_arch_state *rsa = get_remote_arch_state ();
6422 gdb_byte buf[MAX_REGISTER_SIZE];
6424 /* Make sure the entire registers array is valid. */
6425 switch (remote_protocol_packets[PACKET_P].support)
6427 case PACKET_DISABLE:
6428 case PACKET_SUPPORT_UNKNOWN:
6429 /* Make sure all the necessary registers are cached. */
6430 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6431 if (rsa->regs[i].in_g_packet)
6432 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6439 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6440 packet was not recognized. */
6443 store_register_using_P (const struct regcache *regcache,
6444 struct packet_reg *reg)
6446 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6447 struct remote_state *rs = get_remote_state ();
6448 /* Try storing a single register. */
6449 char *buf = rs->buf;
6450 gdb_byte regp[MAX_REGISTER_SIZE];
6453 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
6456 if (reg->pnum == -1)
6459 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6460 p = buf + strlen (buf);
6461 regcache_raw_collect (regcache, reg->regnum, regp);
6462 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6464 getpkt (&rs->buf, &rs->buf_size, 0);
6466 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6471 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6472 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6473 case PACKET_UNKNOWN:
6476 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6480 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6481 contents of the register cache buffer. FIXME: ignores errors. */
6484 store_registers_using_G (const struct regcache *regcache)
6486 struct remote_state *rs = get_remote_state ();
6487 struct remote_arch_state *rsa = get_remote_arch_state ();
6491 /* Extract all the registers in the regcache copying them into a
6496 regs = alloca (rsa->sizeof_g_packet);
6497 memset (regs, 0, rsa->sizeof_g_packet);
6498 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6500 struct packet_reg *r = &rsa->regs[i];
6503 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6507 /* Command describes registers byte by byte,
6508 each byte encoded as two hex characters. */
6511 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6513 bin2hex (regs, p, rsa->sizeof_g_packet);
6515 getpkt (&rs->buf, &rs->buf_size, 0);
6516 if (packet_check_result (rs->buf) == PACKET_ERROR)
6517 error (_("Could not write registers; remote failure reply '%s'"),
6521 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6522 of the register cache buffer. FIXME: ignores errors. */
6525 remote_store_registers (struct target_ops *ops,
6526 struct regcache *regcache, int regnum)
6528 struct remote_arch_state *rsa = get_remote_arch_state ();
6531 set_remote_traceframe ();
6532 set_general_thread (inferior_ptid);
6536 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6538 gdb_assert (reg != NULL);
6540 /* Always prefer to store registers using the 'P' packet if
6541 possible; we often change only a small number of registers.
6542 Sometimes we change a larger number; we'd need help from a
6543 higher layer to know to use 'G'. */
6544 if (store_register_using_P (regcache, reg))
6547 /* For now, don't complain if we have no way to write the
6548 register. GDB loses track of unavailable registers too
6549 easily. Some day, this may be an error. We don't have
6550 any way to read the register, either... */
6551 if (!reg->in_g_packet)
6554 store_registers_using_G (regcache);
6558 store_registers_using_G (regcache);
6560 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6561 if (!rsa->regs[i].in_g_packet)
6562 if (!store_register_using_P (regcache, &rsa->regs[i]))
6563 /* See above for why we do not issue an error here. */
6568 /* Return the number of hex digits in num. */
6571 hexnumlen (ULONGEST num)
6575 for (i = 0; num != 0; i++)
6581 /* Set BUF to the minimum number of hex digits representing NUM. */
6584 hexnumstr (char *buf, ULONGEST num)
6586 int len = hexnumlen (num);
6588 return hexnumnstr (buf, num, len);
6592 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6595 hexnumnstr (char *buf, ULONGEST num, int width)
6601 for (i = width - 1; i >= 0; i--)
6603 buf[i] = "0123456789abcdef"[(num & 0xf)];
6610 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6613 remote_address_masked (CORE_ADDR addr)
6615 unsigned int address_size = remote_address_size;
6617 /* If "remoteaddresssize" was not set, default to target address size. */
6619 address_size = gdbarch_addr_bit (target_gdbarch ());
6621 if (address_size > 0
6622 && address_size < (sizeof (ULONGEST) * 8))
6624 /* Only create a mask when that mask can safely be constructed
6625 in a ULONGEST variable. */
6628 mask = (mask << address_size) - 1;
6634 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
6635 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6636 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6637 (which may be more than *OUT_LEN due to escape characters). The
6638 total number of bytes in the output buffer will be at most
6642 remote_escape_output (const gdb_byte *buffer, int len,
6643 gdb_byte *out_buf, int *out_len,
6646 int input_index, output_index;
6649 for (input_index = 0; input_index < len; input_index++)
6651 gdb_byte b = buffer[input_index];
6653 if (b == '$' || b == '#' || b == '}')
6655 /* These must be escaped. */
6656 if (output_index + 2 > out_maxlen)
6658 out_buf[output_index++] = '}';
6659 out_buf[output_index++] = b ^ 0x20;
6663 if (output_index + 1 > out_maxlen)
6665 out_buf[output_index++] = b;
6669 *out_len = input_index;
6670 return output_index;
6673 /* Convert BUFFER, escaped data LEN bytes long, into binary data
6674 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6675 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6677 This function reverses remote_escape_output. It allows more
6678 escaped characters than that function does, in particular because
6679 '*' must be escaped to avoid the run-length encoding processing
6680 in reading packets. */
6683 remote_unescape_input (const gdb_byte *buffer, int len,
6684 gdb_byte *out_buf, int out_maxlen)
6686 int input_index, output_index;
6691 for (input_index = 0; input_index < len; input_index++)
6693 gdb_byte b = buffer[input_index];
6695 if (output_index + 1 > out_maxlen)
6697 warning (_("Received too much data from remote target;"
6698 " ignoring overflow."));
6699 return output_index;
6704 out_buf[output_index++] = b ^ 0x20;
6710 out_buf[output_index++] = b;
6714 error (_("Unmatched escape character in target response."));
6716 return output_index;
6719 /* Determine whether the remote target supports binary downloading.
6720 This is accomplished by sending a no-op memory write of zero length
6721 to the target at the specified address. It does not suffice to send
6722 the whole packet, since many stubs strip the eighth bit and
6723 subsequently compute a wrong checksum, which causes real havoc with
6726 NOTE: This can still lose if the serial line is not eight-bit
6727 clean. In cases like this, the user should clear "remote
6731 check_binary_download (CORE_ADDR addr)
6733 struct remote_state *rs = get_remote_state ();
6735 switch (remote_protocol_packets[PACKET_X].support)
6737 case PACKET_DISABLE:
6741 case PACKET_SUPPORT_UNKNOWN:
6747 p += hexnumstr (p, (ULONGEST) addr);
6749 p += hexnumstr (p, (ULONGEST) 0);
6753 putpkt_binary (rs->buf, (int) (p - rs->buf));
6754 getpkt (&rs->buf, &rs->buf_size, 0);
6756 if (rs->buf[0] == '\0')
6759 fprintf_unfiltered (gdb_stdlog,
6760 "binary downloading NOT "
6761 "supported by target\n");
6762 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6767 fprintf_unfiltered (gdb_stdlog,
6768 "binary downloading supported by target\n");
6769 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6776 /* Write memory data directly to the remote machine.
6777 This does not inform the data cache; the data cache uses this.
6778 HEADER is the starting part of the packet.
6779 MEMADDR is the address in the remote memory space.
6780 MYADDR is the address of the buffer in our space.
6781 LEN is the number of bytes.
6782 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6783 should send data as binary ('X'), or hex-encoded ('M').
6785 The function creates packet of the form
6786 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6788 where encoding of <DATA> is termined by PACKET_FORMAT.
6790 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6793 Returns the number of bytes transferred, or a negative value (an
6794 'enum target_xfer_error' value) for error. Only transfer a single
6798 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6799 const gdb_byte *myaddr, ssize_t len,
6800 char packet_format, int use_length)
6802 struct remote_state *rs = get_remote_state ();
6812 if (packet_format != 'X' && packet_format != 'M')
6813 internal_error (__FILE__, __LINE__,
6814 _("remote_write_bytes_aux: bad packet format"));
6819 payload_size = get_memory_write_packet_size ();
6821 /* The packet buffer will be large enough for the payload;
6822 get_memory_packet_size ensures this. */
6825 /* Compute the size of the actual payload by subtracting out the
6826 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6828 payload_size -= strlen ("$,:#NN");
6830 /* The comma won't be used. */
6832 header_length = strlen (header);
6833 payload_size -= header_length;
6834 payload_size -= hexnumlen (memaddr);
6836 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6838 strcat (rs->buf, header);
6839 p = rs->buf + strlen (header);
6841 /* Compute a best guess of the number of bytes actually transfered. */
6842 if (packet_format == 'X')
6844 /* Best guess at number of bytes that will fit. */
6845 todo = min (len, payload_size);
6847 payload_size -= hexnumlen (todo);
6848 todo = min (todo, payload_size);
6852 /* Num bytes that will fit. */
6853 todo = min (len, payload_size / 2);
6855 payload_size -= hexnumlen (todo);
6856 todo = min (todo, payload_size / 2);
6860 internal_error (__FILE__, __LINE__,
6861 _("minimum packet size too small to write data"));
6863 /* If we already need another packet, then try to align the end
6864 of this packet to a useful boundary. */
6865 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6866 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6868 /* Append "<memaddr>". */
6869 memaddr = remote_address_masked (memaddr);
6870 p += hexnumstr (p, (ULONGEST) memaddr);
6877 /* Append <len>. Retain the location/size of <len>. It may need to
6878 be adjusted once the packet body has been created. */
6880 plenlen = hexnumstr (p, (ULONGEST) todo);
6888 /* Append the packet body. */
6889 if (packet_format == 'X')
6891 /* Binary mode. Send target system values byte by byte, in
6892 increasing byte addresses. Only escape certain critical
6894 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6895 &nr_bytes, payload_size);
6897 /* If not all TODO bytes fit, then we'll need another packet. Make
6898 a second try to keep the end of the packet aligned. Don't do
6899 this if the packet is tiny. */
6900 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6904 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6906 if (new_nr_bytes != nr_bytes)
6907 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6908 (gdb_byte *) p, &nr_bytes,
6912 p += payload_length;
6913 if (use_length && nr_bytes < todo)
6915 /* Escape chars have filled up the buffer prematurely,
6916 and we have actually sent fewer bytes than planned.
6917 Fix-up the length field of the packet. Use the same
6918 number of characters as before. */
6919 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6920 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6925 /* Normal mode: Send target system values byte by byte, in
6926 increasing byte addresses. Each byte is encoded as a two hex
6928 nr_bytes = bin2hex (myaddr, p, todo);
6932 putpkt_binary (rs->buf, (int) (p - rs->buf));
6933 getpkt (&rs->buf, &rs->buf_size, 0);
6935 if (rs->buf[0] == 'E')
6936 return TARGET_XFER_E_IO;
6938 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6939 fewer bytes than we'd planned. */
6943 /* Write memory data directly to the remote machine.
6944 This does not inform the data cache; the data cache uses this.
6945 MEMADDR is the address in the remote memory space.
6946 MYADDR is the address of the buffer in our space.
6947 LEN is the number of bytes.
6949 Returns number of bytes transferred, or a negative value (an 'enum
6950 target_xfer_error' value) for error. Only transfer a single
6954 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
6956 char *packet_format = 0;
6958 /* Check whether the target supports binary download. */
6959 check_binary_download (memaddr);
6961 switch (remote_protocol_packets[PACKET_X].support)
6964 packet_format = "X";
6966 case PACKET_DISABLE:
6967 packet_format = "M";
6969 case PACKET_SUPPORT_UNKNOWN:
6970 internal_error (__FILE__, __LINE__,
6971 _("remote_write_bytes: bad internal state"));
6973 internal_error (__FILE__, __LINE__, _("bad switch"));
6976 return remote_write_bytes_aux (packet_format,
6977 memaddr, myaddr, len, packet_format[0], 1);
6980 /* Read memory data directly from the remote machine.
6981 This does not use the data cache; the data cache uses this.
6982 MEMADDR is the address in the remote memory space.
6983 MYADDR is the address of the buffer in our space.
6984 LEN is the number of bytes.
6986 Returns number of bytes transferred, or a negative value (an 'enum
6987 target_xfer_error' value) for error. */
6990 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6992 struct remote_state *rs = get_remote_state ();
6993 int max_buf_size; /* Max size of packet output buffer. */
7001 max_buf_size = get_memory_read_packet_size ();
7002 /* The packet buffer will be large enough for the payload;
7003 get_memory_packet_size ensures this. */
7005 /* Number if bytes that will fit. */
7006 todo = min (len, max_buf_size / 2);
7008 /* Construct "m"<memaddr>","<len>". */
7009 memaddr = remote_address_masked (memaddr);
7012 p += hexnumstr (p, (ULONGEST) memaddr);
7014 p += hexnumstr (p, (ULONGEST) todo);
7017 getpkt (&rs->buf, &rs->buf_size, 0);
7018 if (rs->buf[0] == 'E'
7019 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7020 && rs->buf[3] == '\0')
7021 return TARGET_XFER_E_IO;
7022 /* Reply describes memory byte by byte, each byte encoded as two hex
7025 i = hex2bin (p, myaddr, todo);
7026 /* Return what we have. Let higher layers handle partial reads. */
7032 /* Sends a packet with content determined by the printf format string
7033 FORMAT and the remaining arguments, then gets the reply. Returns
7034 whether the packet was a success, a failure, or unknown. */
7036 static enum packet_result
7037 remote_send_printf (const char *format, ...)
7039 struct remote_state *rs = get_remote_state ();
7040 int max_size = get_remote_packet_size ();
7043 va_start (ap, format);
7046 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7047 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7049 if (putpkt (rs->buf) < 0)
7050 error (_("Communication problem with target."));
7053 getpkt (&rs->buf, &rs->buf_size, 0);
7055 return packet_check_result (rs->buf);
7059 restore_remote_timeout (void *p)
7061 int value = *(int *)p;
7063 remote_timeout = value;
7066 /* Flash writing can take quite some time. We'll set
7067 effectively infinite timeout for flash operations.
7068 In future, we'll need to decide on a better approach. */
7069 static const int remote_flash_timeout = 1000;
7072 remote_flash_erase (struct target_ops *ops,
7073 ULONGEST address, LONGEST length)
7075 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7076 int saved_remote_timeout = remote_timeout;
7077 enum packet_result ret;
7078 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7079 &saved_remote_timeout);
7081 remote_timeout = remote_flash_timeout;
7083 ret = remote_send_printf ("vFlashErase:%s,%s",
7084 phex (address, addr_size),
7088 case PACKET_UNKNOWN:
7089 error (_("Remote target does not support flash erase"));
7091 error (_("Error erasing flash with vFlashErase packet"));
7096 do_cleanups (back_to);
7100 remote_flash_write (struct target_ops *ops,
7101 ULONGEST address, LONGEST length,
7102 const gdb_byte *data)
7104 int saved_remote_timeout = remote_timeout;
7106 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7107 &saved_remote_timeout);
7109 remote_timeout = remote_flash_timeout;
7110 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
7111 do_cleanups (back_to);
7117 remote_flash_done (struct target_ops *ops)
7119 int saved_remote_timeout = remote_timeout;
7121 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7122 &saved_remote_timeout);
7124 remote_timeout = remote_flash_timeout;
7125 ret = remote_send_printf ("vFlashDone");
7126 do_cleanups (back_to);
7130 case PACKET_UNKNOWN:
7131 error (_("Remote target does not support vFlashDone"));
7133 error (_("Error finishing flash operation"));
7140 remote_files_info (struct target_ops *ignore)
7142 puts_filtered ("Debugging a target over a serial line.\n");
7145 /* Stuff for dealing with the packets which are part of this protocol.
7146 See comment at top of file for details. */
7148 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7149 error to higher layers. Called when a serial error is detected.
7150 The exception message is STRING, followed by a colon and a blank,
7151 the system error message for errno at function entry and final dot
7152 for output compatibility with throw_perror_with_name. */
7155 unpush_and_perror (const char *string)
7157 int saved_errno = errno;
7159 remote_unpush_target ();
7160 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7161 safe_strerror (saved_errno));
7164 /* Read a single character from the remote end. */
7167 readchar (int timeout)
7170 struct remote_state *rs = get_remote_state ();
7172 ch = serial_readchar (rs->remote_desc, timeout);
7177 switch ((enum serial_rc) ch)
7180 remote_unpush_target ();
7181 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7184 unpush_and_perror (_("Remote communication error. "
7185 "Target disconnected."));
7187 case SERIAL_TIMEOUT:
7193 /* Wrapper for serial_write that closes the target and throws if
7197 remote_serial_write (const char *str, int len)
7199 struct remote_state *rs = get_remote_state ();
7201 if (serial_write (rs->remote_desc, str, len))
7203 unpush_and_perror (_("Remote communication error. "
7204 "Target disconnected."));
7208 /* Send the command in *BUF to the remote machine, and read the reply
7209 into *BUF. Report an error if we get an error reply. Resize
7210 *BUF using xrealloc if necessary to hold the result, and update
7214 remote_send (char **buf,
7218 getpkt (buf, sizeof_buf, 0);
7220 if ((*buf)[0] == 'E')
7221 error (_("Remote failure reply: %s"), *buf);
7224 /* Return a pointer to an xmalloc'ed string representing an escaped
7225 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7226 etc. The caller is responsible for releasing the returned
7230 escape_buffer (const char *buf, int n)
7232 struct cleanup *old_chain;
7233 struct ui_file *stb;
7236 stb = mem_fileopen ();
7237 old_chain = make_cleanup_ui_file_delete (stb);
7239 fputstrn_unfiltered (buf, n, 0, stb);
7240 str = ui_file_xstrdup (stb, NULL);
7241 do_cleanups (old_chain);
7245 /* Display a null-terminated packet on stdout, for debugging, using C
7249 print_packet (char *buf)
7251 puts_filtered ("\"");
7252 fputstr_filtered (buf, '"', gdb_stdout);
7253 puts_filtered ("\"");
7259 return putpkt_binary (buf, strlen (buf));
7262 /* Send a packet to the remote machine, with error checking. The data
7263 of the packet is in BUF. The string in BUF can be at most
7264 get_remote_packet_size () - 5 to account for the $, # and checksum,
7265 and for a possible /0 if we are debugging (remote_debug) and want
7266 to print the sent packet as a string. */
7269 putpkt_binary (char *buf, int cnt)
7271 struct remote_state *rs = get_remote_state ();
7273 unsigned char csum = 0;
7274 char *buf2 = alloca (cnt + 6);
7281 /* Catch cases like trying to read memory or listing threads while
7282 we're waiting for a stop reply. The remote server wouldn't be
7283 ready to handle this request, so we'd hang and timeout. We don't
7284 have to worry about this in synchronous mode, because in that
7285 case it's not possible to issue a command while the target is
7286 running. This is not a problem in non-stop mode, because in that
7287 case, the stub is always ready to process serial input. */
7288 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
7289 error (_("Cannot execute this command while the target is running."));
7291 /* We're sending out a new packet. Make sure we don't look at a
7292 stale cached response. */
7293 rs->cached_wait_status = 0;
7295 /* Copy the packet into buffer BUF2, encapsulating it
7296 and giving it a checksum. */
7301 for (i = 0; i < cnt; i++)
7307 *p++ = tohex ((csum >> 4) & 0xf);
7308 *p++ = tohex (csum & 0xf);
7310 /* Send it over and over until we get a positive ack. */
7314 int started_error_output = 0;
7318 struct cleanup *old_chain;
7322 str = escape_buffer (buf2, p - buf2);
7323 old_chain = make_cleanup (xfree, str);
7324 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7325 gdb_flush (gdb_stdlog);
7326 do_cleanups (old_chain);
7328 remote_serial_write (buf2, p - buf2);
7330 /* If this is a no acks version of the remote protocol, send the
7331 packet and move on. */
7335 /* Read until either a timeout occurs (-2) or '+' is read.
7336 Handle any notification that arrives in the mean time. */
7339 ch = readchar (remote_timeout);
7347 case SERIAL_TIMEOUT:
7350 if (started_error_output)
7352 putchar_unfiltered ('\n');
7353 started_error_output = 0;
7362 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7366 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7368 case SERIAL_TIMEOUT:
7372 break; /* Retransmit buffer. */
7376 fprintf_unfiltered (gdb_stdlog,
7377 "Packet instead of Ack, ignoring it\n");
7378 /* It's probably an old response sent because an ACK
7379 was lost. Gobble up the packet and ack it so it
7380 doesn't get retransmitted when we resend this
7383 remote_serial_write ("+", 1);
7384 continue; /* Now, go look for +. */
7391 /* If we got a notification, handle it, and go back to looking
7393 /* We've found the start of a notification. Now
7394 collect the data. */
7395 val = read_frame (&rs->buf, &rs->buf_size);
7400 struct cleanup *old_chain;
7403 str = escape_buffer (rs->buf, val);
7404 old_chain = make_cleanup (xfree, str);
7405 fprintf_unfiltered (gdb_stdlog,
7406 " Notification received: %s\n",
7408 do_cleanups (old_chain);
7410 handle_notification (rs->notif_state, rs->buf);
7411 /* We're in sync now, rewait for the ack. */
7418 if (!started_error_output)
7420 started_error_output = 1;
7421 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7423 fputc_unfiltered (ch & 0177, gdb_stdlog);
7424 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7433 if (!started_error_output)
7435 started_error_output = 1;
7436 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7438 fputc_unfiltered (ch & 0177, gdb_stdlog);
7442 break; /* Here to retransmit. */
7446 /* This is wrong. If doing a long backtrace, the user should be
7447 able to get out next time we call QUIT, without anything as
7448 violent as interrupt_query. If we want to provide a way out of
7449 here without getting to the next QUIT, it should be based on
7450 hitting ^C twice as in remote_wait. */
7461 /* Come here after finding the start of a frame when we expected an
7462 ack. Do our best to discard the rest of this packet. */
7471 c = readchar (remote_timeout);
7474 case SERIAL_TIMEOUT:
7475 /* Nothing we can do. */
7478 /* Discard the two bytes of checksum and stop. */
7479 c = readchar (remote_timeout);
7481 c = readchar (remote_timeout);
7484 case '*': /* Run length encoding. */
7485 /* Discard the repeat count. */
7486 c = readchar (remote_timeout);
7491 /* A regular character. */
7497 /* Come here after finding the start of the frame. Collect the rest
7498 into *BUF, verifying the checksum, length, and handling run-length
7499 compression. NUL terminate the buffer. If there is not enough room,
7500 expand *BUF using xrealloc.
7502 Returns -1 on error, number of characters in buffer (ignoring the
7503 trailing NULL) on success. (could be extended to return one of the
7504 SERIAL status indications). */
7507 read_frame (char **buf_p,
7514 struct remote_state *rs = get_remote_state ();
7521 c = readchar (remote_timeout);
7524 case SERIAL_TIMEOUT:
7526 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7530 fputs_filtered ("Saw new packet start in middle of old one\n",
7532 return -1; /* Start a new packet, count retries. */
7535 unsigned char pktcsum;
7541 check_0 = readchar (remote_timeout);
7543 check_1 = readchar (remote_timeout);
7545 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7548 fputs_filtered ("Timeout in checksum, retrying\n",
7552 else if (check_0 < 0 || check_1 < 0)
7555 fputs_filtered ("Communication error in checksum\n",
7560 /* Don't recompute the checksum; with no ack packets we
7561 don't have any way to indicate a packet retransmission
7566 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7567 if (csum == pktcsum)
7572 struct cleanup *old_chain;
7575 str = escape_buffer (buf, bc);
7576 old_chain = make_cleanup (xfree, str);
7577 fprintf_unfiltered (gdb_stdlog,
7578 "Bad checksum, sentsum=0x%x, "
7579 "csum=0x%x, buf=%s\n",
7580 pktcsum, csum, str);
7581 do_cleanups (old_chain);
7583 /* Number of characters in buffer ignoring trailing
7587 case '*': /* Run length encoding. */
7592 c = readchar (remote_timeout);
7594 repeat = c - ' ' + 3; /* Compute repeat count. */
7596 /* The character before ``*'' is repeated. */
7598 if (repeat > 0 && repeat <= 255 && bc > 0)
7600 if (bc + repeat - 1 >= *sizeof_buf - 1)
7602 /* Make some more room in the buffer. */
7603 *sizeof_buf += repeat;
7604 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7608 memset (&buf[bc], buf[bc - 1], repeat);
7614 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7618 if (bc >= *sizeof_buf - 1)
7620 /* Make some more room in the buffer. */
7622 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7633 /* Read a packet from the remote machine, with error checking, and
7634 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7635 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7636 rather than timing out; this is used (in synchronous mode) to wait
7637 for a target that is is executing user code to stop. */
7638 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7639 don't have to change all the calls to getpkt to deal with the
7640 return value, because at the moment I don't know what the right
7641 thing to do it for those. */
7649 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7653 /* Read a packet from the remote machine, with error checking, and
7654 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7655 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7656 rather than timing out; this is used (in synchronous mode) to wait
7657 for a target that is is executing user code to stop. If FOREVER ==
7658 0, this function is allowed to time out gracefully and return an
7659 indication of this to the caller. Otherwise return the number of
7660 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7661 enough reason to return to the caller. *IS_NOTIF is an output
7662 boolean that indicates whether *BUF holds a notification or not
7663 (a regular packet). */
7666 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7667 int expecting_notif, int *is_notif)
7669 struct remote_state *rs = get_remote_state ();
7675 /* We're reading a new response. Make sure we don't look at a
7676 previously cached response. */
7677 rs->cached_wait_status = 0;
7679 strcpy (*buf, "timeout");
7682 timeout = watchdog > 0 ? watchdog : -1;
7683 else if (expecting_notif)
7684 timeout = 0; /* There should already be a char in the buffer. If
7687 timeout = remote_timeout;
7691 /* Process any number of notifications, and then return when
7695 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7697 for (tries = 1; tries <= MAX_TRIES; tries++)
7699 /* This can loop forever if the remote side sends us
7700 characters continuously, but if it pauses, we'll get
7701 SERIAL_TIMEOUT from readchar because of timeout. Then
7702 we'll count that as a retry.
7704 Note that even when forever is set, we will only wait
7705 forever prior to the start of a packet. After that, we
7706 expect characters to arrive at a brisk pace. They should
7707 show up within remote_timeout intervals. */
7709 c = readchar (timeout);
7710 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7712 if (c == SERIAL_TIMEOUT)
7714 if (expecting_notif)
7715 return -1; /* Don't complain, it's normal to not get
7716 anything in this case. */
7718 if (forever) /* Watchdog went off? Kill the target. */
7721 remote_unpush_target ();
7722 throw_error (TARGET_CLOSE_ERROR,
7723 _("Watchdog timeout has expired. "
7724 "Target detached."));
7727 fputs_filtered ("Timed out.\n", gdb_stdlog);
7731 /* We've found the start of a packet or notification.
7732 Now collect the data. */
7733 val = read_frame (buf, sizeof_buf);
7738 remote_serial_write ("-", 1);
7741 if (tries > MAX_TRIES)
7743 /* We have tried hard enough, and just can't receive the
7744 packet/notification. Give up. */
7745 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7747 /* Skip the ack char if we're in no-ack mode. */
7748 if (!rs->noack_mode)
7749 remote_serial_write ("+", 1);
7753 /* If we got an ordinary packet, return that to our caller. */
7758 struct cleanup *old_chain;
7761 str = escape_buffer (*buf, val);
7762 old_chain = make_cleanup (xfree, str);
7763 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7764 do_cleanups (old_chain);
7767 /* Skip the ack char if we're in no-ack mode. */
7768 if (!rs->noack_mode)
7769 remote_serial_write ("+", 1);
7770 if (is_notif != NULL)
7775 /* If we got a notification, handle it, and go back to looking
7779 gdb_assert (c == '%');
7783 struct cleanup *old_chain;
7786 str = escape_buffer (*buf, val);
7787 old_chain = make_cleanup (xfree, str);
7788 fprintf_unfiltered (gdb_stdlog,
7789 " Notification received: %s\n",
7791 do_cleanups (old_chain);
7793 if (is_notif != NULL)
7796 handle_notification (rs->notif_state, *buf);
7798 /* Notifications require no acknowledgement. */
7800 if (expecting_notif)
7807 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7809 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7813 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7816 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7821 /* A helper function that just calls putpkt; for type correctness. */
7824 putpkt_for_catch_errors (void *arg)
7826 return putpkt (arg);
7830 remote_kill (struct target_ops *ops)
7832 /* Use catch_errors so the user can quit from gdb even when we
7833 aren't on speaking terms with the remote system. */
7834 catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
7836 /* Don't wait for it to die. I'm not really sure it matters whether
7837 we do or not. For the existing stubs, kill is a noop. */
7838 target_mourn_inferior ();
7842 remote_vkill (int pid, struct remote_state *rs)
7844 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7847 /* Tell the remote target to detach. */
7848 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7850 getpkt (&rs->buf, &rs->buf_size, 0);
7852 if (packet_ok (rs->buf,
7853 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7855 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7862 extended_remote_kill (struct target_ops *ops)
7865 int pid = ptid_get_pid (inferior_ptid);
7866 struct remote_state *rs = get_remote_state ();
7868 res = remote_vkill (pid, rs);
7869 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7871 /* Don't try 'k' on a multi-process aware stub -- it has no way
7872 to specify the pid. */
7876 getpkt (&rs->buf, &rs->buf_size, 0);
7877 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7880 /* Don't wait for it to die. I'm not really sure it matters whether
7881 we do or not. For the existing stubs, kill is a noop. */
7887 error (_("Can't kill process"));
7889 target_mourn_inferior ();
7893 remote_mourn (struct target_ops *ops)
7895 remote_mourn_1 (ops);
7898 /* Worker function for remote_mourn. */
7900 remote_mourn_1 (struct target_ops *target)
7902 unpush_target (target);
7904 /* remote_close takes care of doing most of the clean up. */
7905 generic_mourn_inferior ();
7909 extended_remote_mourn_1 (struct target_ops *target)
7911 struct remote_state *rs = get_remote_state ();
7913 /* In case we got here due to an error, but we're going to stay
7915 rs->waiting_for_stop_reply = 0;
7917 /* If the current general thread belonged to the process we just
7918 detached from or has exited, the remote side current general
7919 thread becomes undefined. Considering a case like this:
7921 - We just got here due to a detach.
7922 - The process that we're detaching from happens to immediately
7923 report a global breakpoint being hit in non-stop mode, in the
7924 same thread we had selected before.
7925 - GDB attaches to this process again.
7926 - This event happens to be the next event we handle.
7928 GDB would consider that the current general thread didn't need to
7929 be set on the stub side (with Hg), since for all it knew,
7930 GENERAL_THREAD hadn't changed.
7932 Notice that although in all-stop mode, the remote server always
7933 sets the current thread to the thread reporting the stop event,
7934 that doesn't happen in non-stop mode; in non-stop, the stub *must
7935 not* change the current thread when reporting a breakpoint hit,
7936 due to the decoupling of event reporting and event handling.
7938 To keep things simple, we always invalidate our notion of the
7940 record_currthread (rs, minus_one_ptid);
7942 /* Unlike "target remote", we do not want to unpush the target; then
7943 the next time the user says "run", we won't be connected. */
7945 /* Call common code to mark the inferior as not running. */
7946 generic_mourn_inferior ();
7948 if (!have_inferiors ())
7950 if (!remote_multi_process_p (rs))
7952 /* Check whether the target is running now - some remote stubs
7953 automatically restart after kill. */
7955 getpkt (&rs->buf, &rs->buf_size, 0);
7957 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7959 /* Assume that the target has been restarted. Set
7960 inferior_ptid so that bits of core GDB realizes
7961 there's something here, e.g., so that the user can
7962 say "kill" again. */
7963 inferior_ptid = magic_null_ptid;
7970 extended_remote_mourn (struct target_ops *ops)
7972 extended_remote_mourn_1 (ops);
7976 extended_remote_supports_disable_randomization (void)
7978 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7983 extended_remote_disable_randomization (int val)
7985 struct remote_state *rs = get_remote_state ();
7988 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7991 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7993 error (_("Target does not support QDisableRandomization."));
7994 if (strcmp (reply, "OK") != 0)
7995 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7999 extended_remote_run (char *args)
8001 struct remote_state *rs = get_remote_state ();
8004 /* If the user has disabled vRun support, or we have detected that
8005 support is not available, do not try it. */
8006 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
8009 strcpy (rs->buf, "vRun;");
8010 len = strlen (rs->buf);
8012 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8013 error (_("Remote file name too long for run packet"));
8014 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
8016 gdb_assert (args != NULL);
8019 struct cleanup *back_to;
8023 argv = gdb_buildargv (args);
8024 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
8025 for (i = 0; argv[i] != NULL; i++)
8027 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8028 error (_("Argument list too long for run packet"));
8029 rs->buf[len++] = ';';
8030 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
8032 do_cleanups (back_to);
8035 rs->buf[len++] = '\0';
8038 getpkt (&rs->buf, &rs->buf_size, 0);
8040 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
8042 /* We have a wait response. All is well. */
8045 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
8046 /* It wasn't disabled before, but it is now. */
8050 if (remote_exec_file[0] == '\0')
8051 error (_("Running the default executable on the remote target failed; "
8052 "try \"set remote exec-file\"?"));
8054 error (_("Running \"%s\" on the remote target failed"),
8059 /* In the extended protocol we want to be able to do things like
8060 "run" and have them basically work as expected. So we need
8061 a special create_inferior function. We support changing the
8062 executable file and the command line arguments, but not the
8066 extended_remote_create_inferior_1 (char *exec_file, char *args,
8067 char **env, int from_tty)
8071 struct remote_state *rs = get_remote_state ();
8073 /* If running asynchronously, register the target file descriptor
8074 with the event loop. */
8075 if (target_can_async_p ())
8076 target_async (inferior_event_handler, 0);
8078 /* Disable address space randomization if requested (and supported). */
8079 if (extended_remote_supports_disable_randomization ())
8080 extended_remote_disable_randomization (disable_randomization);
8082 /* Now restart the remote server. */
8083 run_worked = extended_remote_run (args) != -1;
8086 /* vRun was not supported. Fail if we need it to do what the
8088 if (remote_exec_file[0])
8089 error (_("Remote target does not support \"set remote exec-file\""));
8091 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8093 /* Fall back to "R". */
8094 extended_remote_restart ();
8097 if (!have_inferiors ())
8099 /* Clean up from the last time we ran, before we mark the target
8100 running again. This will mark breakpoints uninserted, and
8101 get_offsets may insert breakpoints. */
8102 init_thread_list ();
8103 init_wait_for_inferior ();
8106 /* vRun's success return is a stop reply. */
8107 stop_reply = run_worked ? rs->buf : NULL;
8108 add_current_inferior_and_thread (stop_reply);
8110 /* Get updated offsets, if the stub uses qOffsets. */
8115 extended_remote_create_inferior (struct target_ops *ops,
8116 char *exec_file, char *args,
8117 char **env, int from_tty)
8119 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
8123 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8124 the list of conditions (in agent expression bytecode format), if any, the
8125 target needs to evaluate. The output is placed into the packet buffer
8126 started from BUF and ended at BUF_END. */
8129 remote_add_target_side_condition (struct gdbarch *gdbarch,
8130 struct bp_target_info *bp_tgt, char *buf,
8133 struct agent_expr *aexpr = NULL;
8136 char *buf_start = buf;
8138 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8141 buf += strlen (buf);
8142 xsnprintf (buf, buf_end - buf, "%s", ";");
8145 /* Send conditions to the target and free the vector. */
8147 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8150 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8151 buf += strlen (buf);
8152 for (i = 0; i < aexpr->len; ++i)
8153 buf = pack_hex_byte (buf, aexpr->buf[i]);
8157 VEC_free (agent_expr_p, bp_tgt->conditions);
8162 remote_add_target_side_commands (struct gdbarch *gdbarch,
8163 struct bp_target_info *bp_tgt, char *buf)
8165 struct agent_expr *aexpr = NULL;
8168 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8171 buf += strlen (buf);
8173 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8174 buf += strlen (buf);
8176 /* Concatenate all the agent expressions that are commands into the
8179 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8182 sprintf (buf, "X%x,", aexpr->len);
8183 buf += strlen (buf);
8184 for (i = 0; i < aexpr->len; ++i)
8185 buf = pack_hex_byte (buf, aexpr->buf[i]);
8189 VEC_free (agent_expr_p, bp_tgt->tcommands);
8192 /* Insert a breakpoint. On targets that have software breakpoint
8193 support, we ask the remote target to do the work; on targets
8194 which don't, we insert a traditional memory breakpoint. */
8197 remote_insert_breakpoint (struct gdbarch *gdbarch,
8198 struct bp_target_info *bp_tgt)
8200 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8201 If it succeeds, then set the support to PACKET_ENABLE. If it
8202 fails, and the user has explicitly requested the Z support then
8203 report an error, otherwise, mark it disabled and go on. */
8205 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8207 CORE_ADDR addr = bp_tgt->placed_address;
8208 struct remote_state *rs;
8211 struct condition_list *cond = NULL;
8213 /* Make sure the remote is pointing at the right process, if
8215 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8216 set_general_process ();
8218 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8220 rs = get_remote_state ();
8222 endbuf = rs->buf + get_remote_packet_size ();
8227 addr = (ULONGEST) remote_address_masked (addr);
8228 p += hexnumstr (p, addr);
8229 xsnprintf (p, endbuf - p, ",%d", bpsize);
8231 if (remote_supports_cond_breakpoints ())
8232 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8234 if (remote_can_run_breakpoint_commands ())
8235 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8238 getpkt (&rs->buf, &rs->buf_size, 0);
8240 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8245 bp_tgt->placed_address = addr;
8246 bp_tgt->placed_size = bpsize;
8248 case PACKET_UNKNOWN:
8253 return memory_insert_breakpoint (gdbarch, bp_tgt);
8257 remote_remove_breakpoint (struct gdbarch *gdbarch,
8258 struct bp_target_info *bp_tgt)
8260 CORE_ADDR addr = bp_tgt->placed_address;
8261 struct remote_state *rs = get_remote_state ();
8263 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8266 char *endbuf = rs->buf + get_remote_packet_size ();
8268 /* Make sure the remote is pointing at the right process, if
8270 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8271 set_general_process ();
8277 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8278 p += hexnumstr (p, addr);
8279 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8282 getpkt (&rs->buf, &rs->buf_size, 0);
8284 return (rs->buf[0] == 'E');
8287 return memory_remove_breakpoint (gdbarch, bp_tgt);
8291 watchpoint_to_Z_packet (int type)
8296 return Z_PACKET_WRITE_WP;
8299 return Z_PACKET_READ_WP;
8302 return Z_PACKET_ACCESS_WP;
8305 internal_error (__FILE__, __LINE__,
8306 _("hw_bp_to_z: bad watchpoint type %d"), type);
8311 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
8312 struct expression *cond)
8314 struct remote_state *rs = get_remote_state ();
8315 char *endbuf = rs->buf + get_remote_packet_size ();
8317 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8319 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8322 /* Make sure the remote is pointing at the right process, if
8324 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8325 set_general_process ();
8327 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8328 p = strchr (rs->buf, '\0');
8329 addr = remote_address_masked (addr);
8330 p += hexnumstr (p, (ULONGEST) addr);
8331 xsnprintf (p, endbuf - p, ",%x", len);
8334 getpkt (&rs->buf, &rs->buf_size, 0);
8336 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8340 case PACKET_UNKNOWN:
8345 internal_error (__FILE__, __LINE__,
8346 _("remote_insert_watchpoint: reached end of function"));
8350 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8351 CORE_ADDR start, int length)
8353 CORE_ADDR diff = remote_address_masked (addr - start);
8355 return diff < length;
8360 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
8361 struct expression *cond)
8363 struct remote_state *rs = get_remote_state ();
8364 char *endbuf = rs->buf + get_remote_packet_size ();
8366 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8368 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8371 /* Make sure the remote is pointing at the right process, if
8373 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8374 set_general_process ();
8376 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8377 p = strchr (rs->buf, '\0');
8378 addr = remote_address_masked (addr);
8379 p += hexnumstr (p, (ULONGEST) addr);
8380 xsnprintf (p, endbuf - p, ",%x", len);
8382 getpkt (&rs->buf, &rs->buf_size, 0);
8384 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8387 case PACKET_UNKNOWN:
8392 internal_error (__FILE__, __LINE__,
8393 _("remote_remove_watchpoint: reached end of function"));
8397 int remote_hw_watchpoint_limit = -1;
8398 int remote_hw_watchpoint_length_limit = -1;
8399 int remote_hw_breakpoint_limit = -1;
8402 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
8404 if (remote_hw_watchpoint_length_limit == 0)
8406 else if (remote_hw_watchpoint_length_limit < 0)
8408 else if (len <= remote_hw_watchpoint_length_limit)
8415 remote_check_watch_resources (int type, int cnt, int ot)
8417 if (type == bp_hardware_breakpoint)
8419 if (remote_hw_breakpoint_limit == 0)
8421 else if (remote_hw_breakpoint_limit < 0)
8423 else if (cnt <= remote_hw_breakpoint_limit)
8428 if (remote_hw_watchpoint_limit == 0)
8430 else if (remote_hw_watchpoint_limit < 0)
8434 else if (cnt <= remote_hw_watchpoint_limit)
8441 remote_stopped_by_watchpoint (void)
8443 struct remote_state *rs = get_remote_state ();
8445 return rs->remote_stopped_by_watchpoint_p;
8449 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8451 struct remote_state *rs = get_remote_state ();
8454 if (remote_stopped_by_watchpoint ())
8456 *addr_p = rs->remote_watch_data_address;
8465 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
8466 struct bp_target_info *bp_tgt)
8469 struct remote_state *rs;
8473 /* The length field should be set to the size of a breakpoint
8474 instruction, even though we aren't inserting one ourselves. */
8476 gdbarch_remote_breakpoint_from_pc
8477 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
8479 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8482 /* Make sure the remote is pointing at the right process, if
8484 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8485 set_general_process ();
8487 rs = get_remote_state ();
8489 endbuf = rs->buf + get_remote_packet_size ();
8495 addr = remote_address_masked (bp_tgt->placed_address);
8496 p += hexnumstr (p, (ULONGEST) addr);
8497 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8499 if (remote_supports_cond_breakpoints ())
8500 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8502 if (remote_can_run_breakpoint_commands ())
8503 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8506 getpkt (&rs->buf, &rs->buf_size, 0);
8508 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8511 if (rs->buf[1] == '.')
8513 message = strchr (rs->buf + 2, '.');
8515 error (_("Remote failure reply: %s"), message + 1);
8518 case PACKET_UNKNOWN:
8523 internal_error (__FILE__, __LINE__,
8524 _("remote_insert_hw_breakpoint: reached end of function"));
8529 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
8530 struct bp_target_info *bp_tgt)
8533 struct remote_state *rs = get_remote_state ();
8535 char *endbuf = rs->buf + get_remote_packet_size ();
8537 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8540 /* Make sure the remote is pointing at the right process, if
8542 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8543 set_general_process ();
8549 addr = remote_address_masked (bp_tgt->placed_address);
8550 p += hexnumstr (p, (ULONGEST) addr);
8551 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8554 getpkt (&rs->buf, &rs->buf_size, 0);
8556 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8559 case PACKET_UNKNOWN:
8564 internal_error (__FILE__, __LINE__,
8565 _("remote_remove_hw_breakpoint: reached end of function"));
8568 /* Verify memory using the "qCRC:" request. */
8571 remote_verify_memory (struct target_ops *ops,
8572 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8574 struct remote_state *rs = get_remote_state ();
8575 unsigned long host_crc, target_crc;
8578 /* Make sure the remote is pointing at the right process. */
8579 set_general_process ();
8581 /* FIXME: assumes lma can fit into long. */
8582 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8583 (long) lma, (long) size);
8586 /* Be clever; compute the host_crc before waiting for target
8588 host_crc = xcrc32 (data, size, 0xffffffff);
8590 getpkt (&rs->buf, &rs->buf_size, 0);
8591 if (rs->buf[0] == 'E')
8594 if (rs->buf[0] != 'C')
8595 error (_("remote target does not support this operation"));
8597 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8598 target_crc = target_crc * 16 + fromhex (*tmp);
8600 return (host_crc == target_crc);
8603 /* compare-sections command
8605 With no arguments, compares each loadable section in the exec bfd
8606 with the same memory range on the target, and reports mismatches.
8607 Useful for verifying the image on the target against the exec file. */
8610 compare_sections_command (char *args, int from_tty)
8613 struct cleanup *old_chain;
8615 const char *sectname;
8623 error (_("command cannot be used without an exec file"));
8625 /* Make sure the remote is pointing at the right process. */
8626 set_general_process ();
8628 for (s = exec_bfd->sections; s; s = s->next)
8630 if (!(s->flags & SEC_LOAD))
8631 continue; /* Skip non-loadable section. */
8633 size = bfd_get_section_size (s);
8635 continue; /* Skip zero-length section. */
8637 sectname = bfd_get_section_name (exec_bfd, s);
8638 if (args && strcmp (args, sectname) != 0)
8639 continue; /* Not the section selected by user. */
8641 matched = 1; /* Do this section. */
8644 sectdata = xmalloc (size);
8645 old_chain = make_cleanup (xfree, sectdata);
8646 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8648 res = target_verify_memory (sectdata, lma, size);
8651 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8652 paddress (target_gdbarch (), lma),
8653 paddress (target_gdbarch (), lma + size));
8655 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8656 paddress (target_gdbarch (), lma),
8657 paddress (target_gdbarch (), lma + size));
8659 printf_filtered ("matched.\n");
8662 printf_filtered ("MIS-MATCHED!\n");
8666 do_cleanups (old_chain);
8669 warning (_("One or more sections of the remote executable does not match\n\
8670 the loaded file\n"));
8671 if (args && !matched)
8672 printf_filtered (_("No loaded section named '%s'.\n"), args);
8675 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8676 into remote target. The number of bytes written to the remote
8677 target is returned, or -1 for error. */
8680 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8681 const char *annex, const gdb_byte *writebuf,
8682 ULONGEST offset, LONGEST len,
8683 struct packet_config *packet)
8687 struct remote_state *rs = get_remote_state ();
8688 int max_size = get_memory_write_packet_size ();
8690 if (packet->support == PACKET_DISABLE)
8693 /* Insert header. */
8694 i = snprintf (rs->buf, max_size,
8695 "qXfer:%s:write:%s:%s:",
8696 object_name, annex ? annex : "",
8697 phex_nz (offset, sizeof offset));
8698 max_size -= (i + 1);
8700 /* Escape as much data as fits into rs->buf. */
8701 buf_len = remote_escape_output
8702 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8704 if (putpkt_binary (rs->buf, i + buf_len) < 0
8705 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8706 || packet_ok (rs->buf, packet) != PACKET_OK)
8709 unpack_varlen_hex (rs->buf, &n);
8713 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8714 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8715 number of bytes read is returned, or 0 for EOF, or -1 for error.
8716 The number of bytes read may be less than LEN without indicating an
8717 EOF. PACKET is checked and updated to indicate whether the remote
8718 target supports this object. */
8721 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8723 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8724 struct packet_config *packet)
8726 struct remote_state *rs = get_remote_state ();
8727 LONGEST i, n, packet_len;
8729 if (packet->support == PACKET_DISABLE)
8732 /* Check whether we've cached an end-of-object packet that matches
8734 if (rs->finished_object)
8736 if (strcmp (object_name, rs->finished_object) == 0
8737 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8738 && offset == rs->finished_offset)
8741 /* Otherwise, we're now reading something different. Discard
8743 xfree (rs->finished_object);
8744 xfree (rs->finished_annex);
8745 rs->finished_object = NULL;
8746 rs->finished_annex = NULL;
8749 /* Request only enough to fit in a single packet. The actual data
8750 may not, since we don't know how much of it will need to be escaped;
8751 the target is free to respond with slightly less data. We subtract
8752 five to account for the response type and the protocol frame. */
8753 n = min (get_remote_packet_size () - 5, len);
8754 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8755 object_name, annex ? annex : "",
8756 phex_nz (offset, sizeof offset),
8757 phex_nz (n, sizeof n));
8758 i = putpkt (rs->buf);
8763 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8764 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8767 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8768 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8770 /* 'm' means there is (or at least might be) more data after this
8771 batch. That does not make sense unless there's at least one byte
8772 of data in this reply. */
8773 if (rs->buf[0] == 'm' && packet_len == 1)
8774 error (_("Remote qXfer reply contained no data."));
8776 /* Got some data. */
8777 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8778 packet_len - 1, readbuf, n);
8780 /* 'l' is an EOF marker, possibly including a final block of data,
8781 or possibly empty. If we have the final block of a non-empty
8782 object, record this fact to bypass a subsequent partial read. */
8783 if (rs->buf[0] == 'l' && offset + i > 0)
8785 rs->finished_object = xstrdup (object_name);
8786 rs->finished_annex = xstrdup (annex ? annex : "");
8787 rs->finished_offset = offset + i;
8794 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8795 const char *annex, gdb_byte *readbuf,
8796 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
8798 struct remote_state *rs;
8803 set_remote_traceframe ();
8804 set_general_thread (inferior_ptid);
8806 rs = get_remote_state ();
8808 /* Handle memory using the standard memory routines. */
8809 if (object == TARGET_OBJECT_MEMORY)
8813 /* If the remote target is connected but not running, we should
8814 pass this request down to a lower stratum (e.g. the executable
8816 if (!target_has_execution)
8819 if (writebuf != NULL)
8820 xfered = remote_write_bytes (offset, writebuf, len);
8822 xfered = remote_read_bytes (offset, readbuf, len);
8827 /* Handle SPU memory using qxfer packets. */
8828 if (object == TARGET_OBJECT_SPU)
8831 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8832 &remote_protocol_packets
8833 [PACKET_qXfer_spu_read]);
8835 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8836 &remote_protocol_packets
8837 [PACKET_qXfer_spu_write]);
8840 /* Handle extra signal info using qxfer packets. */
8841 if (object == TARGET_OBJECT_SIGNAL_INFO)
8844 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8845 &remote_protocol_packets
8846 [PACKET_qXfer_siginfo_read]);
8848 return remote_write_qxfer (ops, "siginfo", annex,
8849 writebuf, offset, len,
8850 &remote_protocol_packets
8851 [PACKET_qXfer_siginfo_write]);
8854 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8857 return remote_read_qxfer (ops, "statictrace", annex,
8858 readbuf, offset, len,
8859 &remote_protocol_packets
8860 [PACKET_qXfer_statictrace_read]);
8865 /* Only handle flash writes. */
8866 if (writebuf != NULL)
8872 case TARGET_OBJECT_FLASH:
8873 return remote_flash_write (ops, offset, len, writebuf);
8880 /* Map pre-existing objects onto letters. DO NOT do this for new
8881 objects!!! Instead specify new query packets. */
8884 case TARGET_OBJECT_AVR:
8888 case TARGET_OBJECT_AUXV:
8889 gdb_assert (annex == NULL);
8890 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8891 &remote_protocol_packets[PACKET_qXfer_auxv]);
8893 case TARGET_OBJECT_AVAILABLE_FEATURES:
8894 return remote_read_qxfer
8895 (ops, "features", annex, readbuf, offset, len,
8896 &remote_protocol_packets[PACKET_qXfer_features]);
8898 case TARGET_OBJECT_LIBRARIES:
8899 return remote_read_qxfer
8900 (ops, "libraries", annex, readbuf, offset, len,
8901 &remote_protocol_packets[PACKET_qXfer_libraries]);
8903 case TARGET_OBJECT_LIBRARIES_SVR4:
8904 return remote_read_qxfer
8905 (ops, "libraries-svr4", annex, readbuf, offset, len,
8906 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8908 case TARGET_OBJECT_MEMORY_MAP:
8909 gdb_assert (annex == NULL);
8910 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8911 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8913 case TARGET_OBJECT_OSDATA:
8914 /* Should only get here if we're connected. */
8915 gdb_assert (rs->remote_desc);
8916 return remote_read_qxfer
8917 (ops, "osdata", annex, readbuf, offset, len,
8918 &remote_protocol_packets[PACKET_qXfer_osdata]);
8920 case TARGET_OBJECT_THREADS:
8921 gdb_assert (annex == NULL);
8922 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8923 &remote_protocol_packets[PACKET_qXfer_threads]);
8925 case TARGET_OBJECT_TRACEFRAME_INFO:
8926 gdb_assert (annex == NULL);
8927 return remote_read_qxfer
8928 (ops, "traceframe-info", annex, readbuf, offset, len,
8929 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8931 case TARGET_OBJECT_FDPIC:
8932 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8933 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8935 case TARGET_OBJECT_OPENVMS_UIB:
8936 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
8937 &remote_protocol_packets[PACKET_qXfer_uib]);
8939 case TARGET_OBJECT_BTRACE:
8940 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
8941 &remote_protocol_packets[PACKET_qXfer_btrace]);
8947 /* Note: a zero OFFSET and LEN can be used to query the minimum
8949 if (offset == 0 && len == 0)
8950 return (get_remote_packet_size ());
8951 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8952 large enough let the caller deal with it. */
8953 if (len < get_remote_packet_size ())
8955 len = get_remote_packet_size ();
8957 /* Except for querying the minimum buffer size, target must be open. */
8958 if (!rs->remote_desc)
8959 error (_("remote query is only available after target open"));
8961 gdb_assert (annex != NULL);
8962 gdb_assert (readbuf != NULL);
8968 /* We used one buffer char for the remote protocol q command and
8969 another for the query type. As the remote protocol encapsulation
8970 uses 4 chars plus one extra in case we are debugging
8971 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8974 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8976 /* Bad caller may have sent forbidden characters. */
8977 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8982 gdb_assert (annex[i] == '\0');
8984 i = putpkt (rs->buf);
8988 getpkt (&rs->buf, &rs->buf_size, 0);
8989 strcpy ((char *) readbuf, rs->buf);
8991 return strlen ((char *) readbuf);
8995 remote_search_memory (struct target_ops* ops,
8996 CORE_ADDR start_addr, ULONGEST search_space_len,
8997 const gdb_byte *pattern, ULONGEST pattern_len,
8998 CORE_ADDR *found_addrp)
9000 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9001 struct remote_state *rs = get_remote_state ();
9002 int max_size = get_memory_write_packet_size ();
9003 struct packet_config *packet =
9004 &remote_protocol_packets[PACKET_qSearch_memory];
9005 /* Number of packet bytes used to encode the pattern;
9006 this could be more than PATTERN_LEN due to escape characters. */
9007 int escaped_pattern_len;
9008 /* Amount of pattern that was encodable in the packet. */
9009 int used_pattern_len;
9012 ULONGEST found_addr;
9014 /* Don't go to the target if we don't have to.
9015 This is done before checking packet->support to avoid the possibility that
9016 a success for this edge case means the facility works in general. */
9017 if (pattern_len > search_space_len)
9019 if (pattern_len == 0)
9021 *found_addrp = start_addr;
9025 /* If we already know the packet isn't supported, fall back to the simple
9026 way of searching memory. */
9028 if (packet->support == PACKET_DISABLE)
9030 /* Target doesn't provided special support, fall back and use the
9031 standard support (copy memory and do the search here). */
9032 return simple_search_memory (ops, start_addr, search_space_len,
9033 pattern, pattern_len, found_addrp);
9036 /* Make sure the remote is pointing at the right process. */
9037 set_general_process ();
9039 /* Insert header. */
9040 i = snprintf (rs->buf, max_size,
9041 "qSearch:memory:%s;%s;",
9042 phex_nz (start_addr, addr_size),
9043 phex_nz (search_space_len, sizeof (search_space_len)));
9044 max_size -= (i + 1);
9046 /* Escape as much data as fits into rs->buf. */
9047 escaped_pattern_len =
9048 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9049 &used_pattern_len, max_size);
9051 /* Bail if the pattern is too large. */
9052 if (used_pattern_len != pattern_len)
9053 error (_("Pattern is too large to transmit to remote target."));
9055 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9056 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9057 || packet_ok (rs->buf, packet) != PACKET_OK)
9059 /* The request may not have worked because the command is not
9060 supported. If so, fall back to the simple way. */
9061 if (packet->support == PACKET_DISABLE)
9063 return simple_search_memory (ops, start_addr, search_space_len,
9064 pattern, pattern_len, found_addrp);
9069 if (rs->buf[0] == '0')
9071 else if (rs->buf[0] == '1')
9074 if (rs->buf[1] != ',')
9075 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9076 unpack_varlen_hex (rs->buf + 2, &found_addr);
9077 *found_addrp = found_addr;
9080 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9086 remote_rcmd (char *command,
9087 struct ui_file *outbuf)
9089 struct remote_state *rs = get_remote_state ();
9092 if (!rs->remote_desc)
9093 error (_("remote rcmd is only available after target open"));
9095 /* Send a NULL command across as an empty command. */
9096 if (command == NULL)
9099 /* The query prefix. */
9100 strcpy (rs->buf, "qRcmd,");
9101 p = strchr (rs->buf, '\0');
9103 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9104 > get_remote_packet_size ())
9105 error (_("\"monitor\" command ``%s'' is too long."), command);
9107 /* Encode the actual command. */
9108 bin2hex ((gdb_byte *) command, p, 0);
9110 if (putpkt (rs->buf) < 0)
9111 error (_("Communication problem with target."));
9113 /* get/display the response */
9118 /* XXX - see also remote_get_noisy_reply(). */
9119 QUIT; /* Allow user to bail out with ^C. */
9121 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9123 /* Timeout. Continue to (try to) read responses.
9124 This is better than stopping with an error, assuming the stub
9125 is still executing the (long) monitor command.
9126 If needed, the user can interrupt gdb using C-c, obtaining
9127 an effect similar to stop on timeout. */
9132 error (_("Target does not support this command."));
9133 if (buf[0] == 'O' && buf[1] != 'K')
9135 remote_console_output (buf + 1); /* 'O' message from stub. */
9138 if (strcmp (buf, "OK") == 0)
9140 if (strlen (buf) == 3 && buf[0] == 'E'
9141 && isdigit (buf[1]) && isdigit (buf[2]))
9143 error (_("Protocol error with Rcmd"));
9145 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9147 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9149 fputc_unfiltered (c, outbuf);
9155 static VEC(mem_region_s) *
9156 remote_memory_map (struct target_ops *ops)
9158 VEC(mem_region_s) *result = NULL;
9159 char *text = target_read_stralloc (¤t_target,
9160 TARGET_OBJECT_MEMORY_MAP, NULL);
9164 struct cleanup *back_to = make_cleanup (xfree, text);
9166 result = parse_memory_map (text);
9167 do_cleanups (back_to);
9174 packet_command (char *args, int from_tty)
9176 struct remote_state *rs = get_remote_state ();
9178 if (!rs->remote_desc)
9179 error (_("command can only be used with remote target"));
9182 error (_("remote-packet command requires packet text as argument"));
9184 puts_filtered ("sending: ");
9185 print_packet (args);
9186 puts_filtered ("\n");
9189 getpkt (&rs->buf, &rs->buf_size, 0);
9190 puts_filtered ("received: ");
9191 print_packet (rs->buf);
9192 puts_filtered ("\n");
9196 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9198 static void display_thread_info (struct gdb_ext_thread_info *info);
9200 static void threadset_test_cmd (char *cmd, int tty);
9202 static void threadalive_test (char *cmd, int tty);
9204 static void threadlist_test_cmd (char *cmd, int tty);
9206 int get_and_display_threadinfo (threadref *ref);
9208 static void threadinfo_test_cmd (char *cmd, int tty);
9210 static int thread_display_step (threadref *ref, void *context);
9212 static void threadlist_update_test_cmd (char *cmd, int tty);
9214 static void init_remote_threadtests (void);
9216 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9219 threadset_test_cmd (char *cmd, int tty)
9221 int sample_thread = SAMPLE_THREAD;
9223 printf_filtered (_("Remote threadset test\n"));
9224 set_general_thread (sample_thread);
9229 threadalive_test (char *cmd, int tty)
9231 int sample_thread = SAMPLE_THREAD;
9232 int pid = ptid_get_pid (inferior_ptid);
9233 ptid_t ptid = ptid_build (pid, 0, sample_thread);
9235 if (remote_thread_alive (ptid))
9236 printf_filtered ("PASS: Thread alive test\n");
9238 printf_filtered ("FAIL: Thread alive test\n");
9241 void output_threadid (char *title, threadref *ref);
9244 output_threadid (char *title, threadref *ref)
9248 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9250 printf_filtered ("%s %s\n", title, (&hexid[0]));
9254 threadlist_test_cmd (char *cmd, int tty)
9257 threadref nextthread;
9258 int done, result_count;
9259 threadref threadlist[3];
9261 printf_filtered ("Remote Threadlist test\n");
9262 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9263 &result_count, &threadlist[0]))
9264 printf_filtered ("FAIL: threadlist test\n");
9267 threadref *scan = threadlist;
9268 threadref *limit = scan + result_count;
9270 while (scan < limit)
9271 output_threadid (" thread ", scan++);
9276 display_thread_info (struct gdb_ext_thread_info *info)
9278 output_threadid ("Threadid: ", &info->threadid);
9279 printf_filtered ("Name: %s\n ", info->shortname);
9280 printf_filtered ("State: %s\n", info->display);
9281 printf_filtered ("other: %s\n\n", info->more_display);
9285 get_and_display_threadinfo (threadref *ref)
9289 struct gdb_ext_thread_info threadinfo;
9291 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9292 | TAG_MOREDISPLAY | TAG_DISPLAY;
9293 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9294 display_thread_info (&threadinfo);
9299 threadinfo_test_cmd (char *cmd, int tty)
9301 int athread = SAMPLE_THREAD;
9305 int_to_threadref (&thread, athread);
9306 printf_filtered ("Remote Threadinfo test\n");
9307 if (!get_and_display_threadinfo (&thread))
9308 printf_filtered ("FAIL cannot get thread info\n");
9312 thread_display_step (threadref *ref, void *context)
9314 /* output_threadid(" threadstep ",ref); *//* simple test */
9315 return get_and_display_threadinfo (ref);
9319 threadlist_update_test_cmd (char *cmd, int tty)
9321 printf_filtered ("Remote Threadlist update test\n");
9322 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9326 init_remote_threadtests (void)
9328 add_com ("tlist", class_obscure, threadlist_test_cmd,
9329 _("Fetch and print the remote list of "
9330 "thread identifiers, one pkt only"));
9331 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9332 _("Fetch and display info about one thread"));
9333 add_com ("tset", class_obscure, threadset_test_cmd,
9334 _("Test setting to a different thread"));
9335 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9336 _("Iterate through updating all remote thread info"));
9337 add_com ("talive", class_obscure, threadalive_test,
9338 _(" Remote thread alive test "));
9343 /* Convert a thread ID to a string. Returns the string in a static
9347 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9349 static char buf[64];
9350 struct remote_state *rs = get_remote_state ();
9352 if (ptid_equal (ptid, null_ptid))
9353 return normal_pid_to_str (ptid);
9354 else if (ptid_is_pid (ptid))
9356 /* Printing an inferior target id. */
9358 /* When multi-process extensions are off, there's no way in the
9359 remote protocol to know the remote process id, if there's any
9360 at all. There's one exception --- when we're connected with
9361 target extended-remote, and we manually attached to a process
9362 with "attach PID". We don't record anywhere a flag that
9363 allows us to distinguish that case from the case of
9364 connecting with extended-remote and the stub already being
9365 attached to a process, and reporting yes to qAttached, hence
9366 no smart special casing here. */
9367 if (!remote_multi_process_p (rs))
9369 xsnprintf (buf, sizeof buf, "Remote target");
9373 return normal_pid_to_str (ptid);
9377 if (ptid_equal (magic_null_ptid, ptid))
9378 xsnprintf (buf, sizeof buf, "Thread <main>");
9379 else if (rs->extended && remote_multi_process_p (rs))
9380 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9381 ptid_get_pid (ptid), ptid_get_tid (ptid));
9383 xsnprintf (buf, sizeof buf, "Thread %ld",
9384 ptid_get_tid (ptid));
9389 /* Get the address of the thread local variable in OBJFILE which is
9390 stored at OFFSET within the thread local storage for thread PTID. */
9393 remote_get_thread_local_address (struct target_ops *ops,
9394 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9396 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
9398 struct remote_state *rs = get_remote_state ();
9400 char *endp = rs->buf + get_remote_packet_size ();
9401 enum packet_result result;
9403 strcpy (p, "qGetTLSAddr:");
9405 p = write_ptid (p, endp, ptid);
9407 p += hexnumstr (p, offset);
9409 p += hexnumstr (p, lm);
9413 getpkt (&rs->buf, &rs->buf_size, 0);
9414 result = packet_ok (rs->buf,
9415 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9416 if (result == PACKET_OK)
9420 unpack_varlen_hex (rs->buf, &result);
9423 else if (result == PACKET_UNKNOWN)
9424 throw_error (TLS_GENERIC_ERROR,
9425 _("Remote target doesn't support qGetTLSAddr packet"));
9427 throw_error (TLS_GENERIC_ERROR,
9428 _("Remote target failed to process qGetTLSAddr request"));
9431 throw_error (TLS_GENERIC_ERROR,
9432 _("TLS not supported or disabled on this target"));
9437 /* Provide thread local base, i.e. Thread Information Block address.
9438 Returns 1 if ptid is found and thread_local_base is non zero. */
9441 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
9443 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9445 struct remote_state *rs = get_remote_state ();
9447 char *endp = rs->buf + get_remote_packet_size ();
9448 enum packet_result result;
9450 strcpy (p, "qGetTIBAddr:");
9452 p = write_ptid (p, endp, ptid);
9456 getpkt (&rs->buf, &rs->buf_size, 0);
9457 result = packet_ok (rs->buf,
9458 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9459 if (result == PACKET_OK)
9463 unpack_varlen_hex (rs->buf, &result);
9465 *addr = (CORE_ADDR) result;
9468 else if (result == PACKET_UNKNOWN)
9469 error (_("Remote target doesn't support qGetTIBAddr packet"));
9471 error (_("Remote target failed to process qGetTIBAddr request"));
9474 error (_("qGetTIBAddr not supported or disabled on this target"));
9479 /* Support for inferring a target description based on the current
9480 architecture and the size of a 'g' packet. While the 'g' packet
9481 can have any size (since optional registers can be left off the
9482 end), some sizes are easily recognizable given knowledge of the
9483 approximate architecture. */
9485 struct remote_g_packet_guess
9488 const struct target_desc *tdesc;
9490 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9491 DEF_VEC_O(remote_g_packet_guess_s);
9493 struct remote_g_packet_data
9495 VEC(remote_g_packet_guess_s) *guesses;
9498 static struct gdbarch_data *remote_g_packet_data_handle;
9501 remote_g_packet_data_init (struct obstack *obstack)
9503 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9507 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9508 const struct target_desc *tdesc)
9510 struct remote_g_packet_data *data
9511 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9512 struct remote_g_packet_guess new_guess, *guess;
9515 gdb_assert (tdesc != NULL);
9518 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9520 if (guess->bytes == bytes)
9521 internal_error (__FILE__, __LINE__,
9522 _("Duplicate g packet description added for size %d"),
9525 new_guess.bytes = bytes;
9526 new_guess.tdesc = tdesc;
9527 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9530 /* Return 1 if remote_read_description would do anything on this target
9531 and architecture, 0 otherwise. */
9534 remote_read_description_p (struct target_ops *target)
9536 struct remote_g_packet_data *data
9537 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9539 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9545 static const struct target_desc *
9546 remote_read_description (struct target_ops *target)
9548 struct remote_g_packet_data *data
9549 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9551 /* Do not try this during initial connection, when we do not know
9552 whether there is a running but stopped thread. */
9553 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9556 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9558 struct remote_g_packet_guess *guess;
9560 int bytes = send_g_packet ();
9563 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9565 if (guess->bytes == bytes)
9566 return guess->tdesc;
9568 /* We discard the g packet. A minor optimization would be to
9569 hold on to it, and fill the register cache once we have selected
9570 an architecture, but it's too tricky to do safely. */
9576 /* Remote file transfer support. This is host-initiated I/O, not
9577 target-initiated; for target-initiated, see remote-fileio.c. */
9579 /* If *LEFT is at least the length of STRING, copy STRING to
9580 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9581 decrease *LEFT. Otherwise raise an error. */
9584 remote_buffer_add_string (char **buffer, int *left, char *string)
9586 int len = strlen (string);
9589 error (_("Packet too long for target."));
9591 memcpy (*buffer, string, len);
9595 /* NUL-terminate the buffer as a convenience, if there is
9601 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9602 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9603 decrease *LEFT. Otherwise raise an error. */
9606 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9609 if (2 * len > *left)
9610 error (_("Packet too long for target."));
9612 bin2hex (bytes, *buffer, len);
9616 /* NUL-terminate the buffer as a convenience, if there is
9622 /* If *LEFT is large enough, convert VALUE to hex and add it to
9623 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9624 decrease *LEFT. Otherwise raise an error. */
9627 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9629 int len = hexnumlen (value);
9632 error (_("Packet too long for target."));
9634 hexnumstr (*buffer, value);
9638 /* NUL-terminate the buffer as a convenience, if there is
9644 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9645 value, *REMOTE_ERRNO to the remote error number or zero if none
9646 was included, and *ATTACHMENT to point to the start of the annex
9647 if any. The length of the packet isn't needed here; there may
9648 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9650 Return 0 if the packet could be parsed, -1 if it could not. If
9651 -1 is returned, the other variables may not be initialized. */
9654 remote_hostio_parse_result (char *buffer, int *retcode,
9655 int *remote_errno, char **attachment)
9662 if (buffer[0] != 'F')
9666 *retcode = strtol (&buffer[1], &p, 16);
9667 if (errno != 0 || p == &buffer[1])
9670 /* Check for ",errno". */
9674 *remote_errno = strtol (p + 1, &p2, 16);
9675 if (errno != 0 || p + 1 == p2)
9680 /* Check for ";attachment". If there is no attachment, the
9681 packet should end here. */
9684 *attachment = p + 1;
9687 else if (*p == '\0')
9693 /* Send a prepared I/O packet to the target and read its response.
9694 The prepared packet is in the global RS->BUF before this function
9695 is called, and the answer is there when we return.
9697 COMMAND_BYTES is the length of the request to send, which may include
9698 binary data. WHICH_PACKET is the packet configuration to check
9699 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9700 is set to the error number and -1 is returned. Otherwise the value
9701 returned by the function is returned.
9703 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9704 attachment is expected; an error will be reported if there's a
9705 mismatch. If one is found, *ATTACHMENT will be set to point into
9706 the packet buffer and *ATTACHMENT_LEN will be set to the
9707 attachment's length. */
9710 remote_hostio_send_command (int command_bytes, int which_packet,
9711 int *remote_errno, char **attachment,
9712 int *attachment_len)
9714 struct remote_state *rs = get_remote_state ();
9715 int ret, bytes_read;
9716 char *attachment_tmp;
9718 if (!rs->remote_desc
9719 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
9721 *remote_errno = FILEIO_ENOSYS;
9725 putpkt_binary (rs->buf, command_bytes);
9726 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9728 /* If it timed out, something is wrong. Don't try to parse the
9732 *remote_errno = FILEIO_EINVAL;
9736 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9739 *remote_errno = FILEIO_EINVAL;
9741 case PACKET_UNKNOWN:
9742 *remote_errno = FILEIO_ENOSYS;
9748 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9751 *remote_errno = FILEIO_EINVAL;
9755 /* Make sure we saw an attachment if and only if we expected one. */
9756 if ((attachment_tmp == NULL && attachment != NULL)
9757 || (attachment_tmp != NULL && attachment == NULL))
9759 *remote_errno = FILEIO_EINVAL;
9763 /* If an attachment was found, it must point into the packet buffer;
9764 work out how many bytes there were. */
9765 if (attachment_tmp != NULL)
9767 *attachment = attachment_tmp;
9768 *attachment_len = bytes_read - (*attachment - rs->buf);
9774 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9775 remote file descriptor, or -1 if an error occurs (and set
9779 remote_hostio_open (const char *filename, int flags, int mode,
9782 struct remote_state *rs = get_remote_state ();
9784 int left = get_remote_packet_size () - 1;
9786 remote_buffer_add_string (&p, &left, "vFile:open:");
9788 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9790 remote_buffer_add_string (&p, &left, ",");
9792 remote_buffer_add_int (&p, &left, flags);
9793 remote_buffer_add_string (&p, &left, ",");
9795 remote_buffer_add_int (&p, &left, mode);
9797 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9798 remote_errno, NULL, NULL);
9801 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9802 Return the number of bytes written, or -1 if an error occurs (and
9803 set *REMOTE_ERRNO). */
9806 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9807 ULONGEST offset, int *remote_errno)
9809 struct remote_state *rs = get_remote_state ();
9811 int left = get_remote_packet_size ();
9814 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9816 remote_buffer_add_int (&p, &left, fd);
9817 remote_buffer_add_string (&p, &left, ",");
9819 remote_buffer_add_int (&p, &left, offset);
9820 remote_buffer_add_string (&p, &left, ",");
9822 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9823 get_remote_packet_size () - (p - rs->buf));
9825 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9826 remote_errno, NULL, NULL);
9829 /* Read up to LEN bytes FD on the remote target into READ_BUF
9830 Return the number of bytes read, or -1 if an error occurs (and
9831 set *REMOTE_ERRNO). */
9834 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9835 ULONGEST offset, int *remote_errno)
9837 struct remote_state *rs = get_remote_state ();
9840 int left = get_remote_packet_size ();
9841 int ret, attachment_len;
9844 remote_buffer_add_string (&p, &left, "vFile:pread:");
9846 remote_buffer_add_int (&p, &left, fd);
9847 remote_buffer_add_string (&p, &left, ",");
9849 remote_buffer_add_int (&p, &left, len);
9850 remote_buffer_add_string (&p, &left, ",");
9852 remote_buffer_add_int (&p, &left, offset);
9854 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9855 remote_errno, &attachment,
9861 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9863 if (read_len != ret)
9864 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9869 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9870 (and set *REMOTE_ERRNO). */
9873 remote_hostio_close (int fd, int *remote_errno)
9875 struct remote_state *rs = get_remote_state ();
9877 int left = get_remote_packet_size () - 1;
9879 remote_buffer_add_string (&p, &left, "vFile:close:");
9881 remote_buffer_add_int (&p, &left, fd);
9883 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9884 remote_errno, NULL, NULL);
9887 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9888 occurs (and set *REMOTE_ERRNO). */
9891 remote_hostio_unlink (const char *filename, int *remote_errno)
9893 struct remote_state *rs = get_remote_state ();
9895 int left = get_remote_packet_size () - 1;
9897 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9899 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9902 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9903 remote_errno, NULL, NULL);
9906 /* Read value of symbolic link FILENAME on the remote target. Return
9907 a null-terminated string allocated via xmalloc, or NULL if an error
9908 occurs (and set *REMOTE_ERRNO). */
9911 remote_hostio_readlink (const char *filename, int *remote_errno)
9913 struct remote_state *rs = get_remote_state ();
9916 int left = get_remote_packet_size ();
9917 int len, attachment_len;
9921 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9923 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9926 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9927 remote_errno, &attachment,
9933 ret = xmalloc (len + 1);
9935 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9936 (gdb_byte *) ret, len);
9937 if (read_len != len)
9938 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9945 remote_fileio_errno_to_host (int errnum)
9969 case FILEIO_ENOTDIR:
9989 case FILEIO_ENAMETOOLONG:
9990 return ENAMETOOLONG;
9996 remote_hostio_error (int errnum)
9998 int host_error = remote_fileio_errno_to_host (errnum);
10000 if (host_error == -1)
10001 error (_("Unknown remote I/O error %d"), errnum);
10003 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10007 remote_hostio_close_cleanup (void *opaque)
10009 int fd = *(int *) opaque;
10012 remote_hostio_close (fd, &remote_errno);
10017 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10019 const char *filename = bfd_get_filename (abfd);
10020 int fd, remote_errno;
10023 gdb_assert (remote_filename_p (filename));
10025 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10028 errno = remote_fileio_errno_to_host (remote_errno);
10029 bfd_set_error (bfd_error_system_call);
10033 stream = xmalloc (sizeof (int));
10039 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10041 int fd = *(int *)stream;
10046 /* Ignore errors on close; these may happen if the remote
10047 connection was already torn down. */
10048 remote_hostio_close (fd, &remote_errno);
10050 /* Zero means success. */
10055 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10056 file_ptr nbytes, file_ptr offset)
10058 int fd = *(int *)stream;
10060 file_ptr pos, bytes;
10063 while (nbytes > pos)
10065 bytes = remote_hostio_pread (fd, (gdb_byte *) buf + pos, nbytes - pos,
10066 offset + pos, &remote_errno);
10068 /* Success, but no bytes, means end-of-file. */
10072 errno = remote_fileio_errno_to_host (remote_errno);
10073 bfd_set_error (bfd_error_system_call);
10084 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10086 /* FIXME: We should probably implement remote_hostio_stat. */
10087 sb->st_size = INT_MAX;
10092 remote_filename_p (const char *filename)
10094 return strncmp (filename,
10095 REMOTE_SYSROOT_PREFIX,
10096 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
10100 remote_bfd_open (const char *remote_file, const char *target)
10102 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10103 remote_bfd_iovec_open, NULL,
10104 remote_bfd_iovec_pread,
10105 remote_bfd_iovec_close,
10106 remote_bfd_iovec_stat);
10112 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10114 struct cleanup *back_to, *close_cleanup;
10115 int retcode, fd, remote_errno, bytes, io_size;
10118 int bytes_in_buffer;
10121 struct remote_state *rs = get_remote_state ();
10123 if (!rs->remote_desc)
10124 error (_("command can only be used with remote target"));
10126 file = gdb_fopen_cloexec (local_file, "rb");
10128 perror_with_name (local_file);
10129 back_to = make_cleanup_fclose (file);
10131 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10133 0700, &remote_errno);
10135 remote_hostio_error (remote_errno);
10137 /* Send up to this many bytes at once. They won't all fit in the
10138 remote packet limit, so we'll transfer slightly fewer. */
10139 io_size = get_remote_packet_size ();
10140 buffer = xmalloc (io_size);
10141 make_cleanup (xfree, buffer);
10143 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10145 bytes_in_buffer = 0;
10148 while (bytes_in_buffer || !saw_eof)
10152 bytes = fread (buffer + bytes_in_buffer, 1,
10153 io_size - bytes_in_buffer,
10158 error (_("Error reading %s."), local_file);
10161 /* EOF. Unless there is something still in the
10162 buffer from the last iteration, we are done. */
10164 if (bytes_in_buffer == 0)
10172 bytes += bytes_in_buffer;
10173 bytes_in_buffer = 0;
10175 retcode = remote_hostio_pwrite (fd, buffer, bytes,
10176 offset, &remote_errno);
10179 remote_hostio_error (remote_errno);
10180 else if (retcode == 0)
10181 error (_("Remote write of %d bytes returned 0!"), bytes);
10182 else if (retcode < bytes)
10184 /* Short write. Save the rest of the read data for the next
10186 bytes_in_buffer = bytes - retcode;
10187 memmove (buffer, buffer + retcode, bytes_in_buffer);
10193 discard_cleanups (close_cleanup);
10194 if (remote_hostio_close (fd, &remote_errno))
10195 remote_hostio_error (remote_errno);
10198 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10199 do_cleanups (back_to);
10203 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10205 struct cleanup *back_to, *close_cleanup;
10206 int fd, remote_errno, bytes, io_size;
10210 struct remote_state *rs = get_remote_state ();
10212 if (!rs->remote_desc)
10213 error (_("command can only be used with remote target"));
10215 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10217 remote_hostio_error (remote_errno);
10219 file = gdb_fopen_cloexec (local_file, "wb");
10221 perror_with_name (local_file);
10222 back_to = make_cleanup_fclose (file);
10224 /* Send up to this many bytes at once. They won't all fit in the
10225 remote packet limit, so we'll transfer slightly fewer. */
10226 io_size = get_remote_packet_size ();
10227 buffer = xmalloc (io_size);
10228 make_cleanup (xfree, buffer);
10230 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10235 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
10237 /* Success, but no bytes, means end-of-file. */
10240 remote_hostio_error (remote_errno);
10244 bytes = fwrite (buffer, 1, bytes, file);
10246 perror_with_name (local_file);
10249 discard_cleanups (close_cleanup);
10250 if (remote_hostio_close (fd, &remote_errno))
10251 remote_hostio_error (remote_errno);
10254 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10255 do_cleanups (back_to);
10259 remote_file_delete (const char *remote_file, int from_tty)
10261 int retcode, remote_errno;
10262 struct remote_state *rs = get_remote_state ();
10264 if (!rs->remote_desc)
10265 error (_("command can only be used with remote target"));
10267 retcode = remote_hostio_unlink (remote_file, &remote_errno);
10269 remote_hostio_error (remote_errno);
10272 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10276 remote_put_command (char *args, int from_tty)
10278 struct cleanup *back_to;
10282 error_no_arg (_("file to put"));
10284 argv = gdb_buildargv (args);
10285 back_to = make_cleanup_freeargv (argv);
10286 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10287 error (_("Invalid parameters to remote put"));
10289 remote_file_put (argv[0], argv[1], from_tty);
10291 do_cleanups (back_to);
10295 remote_get_command (char *args, int from_tty)
10297 struct cleanup *back_to;
10301 error_no_arg (_("file to get"));
10303 argv = gdb_buildargv (args);
10304 back_to = make_cleanup_freeargv (argv);
10305 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10306 error (_("Invalid parameters to remote get"));
10308 remote_file_get (argv[0], argv[1], from_tty);
10310 do_cleanups (back_to);
10314 remote_delete_command (char *args, int from_tty)
10316 struct cleanup *back_to;
10320 error_no_arg (_("file to delete"));
10322 argv = gdb_buildargv (args);
10323 back_to = make_cleanup_freeargv (argv);
10324 if (argv[0] == NULL || argv[1] != NULL)
10325 error (_("Invalid parameters to remote delete"));
10327 remote_file_delete (argv[0], from_tty);
10329 do_cleanups (back_to);
10333 remote_command (char *args, int from_tty)
10335 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10339 remote_can_execute_reverse (void)
10341 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10342 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10349 remote_supports_non_stop (void)
10355 remote_supports_disable_randomization (void)
10357 /* Only supported in extended mode. */
10362 remote_supports_multi_process (void)
10364 struct remote_state *rs = get_remote_state ();
10366 /* Only extended-remote handles being attached to multiple
10367 processes, even though plain remote can use the multi-process
10368 thread id extensions, so that GDB knows the target process's
10370 return rs->extended && remote_multi_process_p (rs);
10374 remote_supports_cond_tracepoints (void)
10376 struct remote_state *rs = get_remote_state ();
10378 return rs->cond_tracepoints;
10382 remote_supports_cond_breakpoints (void)
10384 struct remote_state *rs = get_remote_state ();
10386 return rs->cond_breakpoints;
10390 remote_supports_fast_tracepoints (void)
10392 struct remote_state *rs = get_remote_state ();
10394 return rs->fast_tracepoints;
10398 remote_supports_static_tracepoints (void)
10400 struct remote_state *rs = get_remote_state ();
10402 return rs->static_tracepoints;
10406 remote_supports_install_in_trace (void)
10408 struct remote_state *rs = get_remote_state ();
10410 return rs->install_in_trace;
10414 remote_supports_enable_disable_tracepoint (void)
10416 struct remote_state *rs = get_remote_state ();
10418 return rs->enable_disable_tracepoints;
10422 remote_supports_string_tracing (void)
10424 struct remote_state *rs = get_remote_state ();
10426 return rs->string_tracing;
10430 remote_can_run_breakpoint_commands (void)
10432 struct remote_state *rs = get_remote_state ();
10434 return rs->breakpoint_commands;
10438 remote_trace_init (void)
10441 remote_get_noisy_reply (&target_buf, &target_buf_size);
10442 if (strcmp (target_buf, "OK") != 0)
10443 error (_("Target does not support this command."));
10446 static void free_actions_list (char **actions_list);
10447 static void free_actions_list_cleanup_wrapper (void *);
10449 free_actions_list_cleanup_wrapper (void *al)
10451 free_actions_list (al);
10455 free_actions_list (char **actions_list)
10459 if (actions_list == 0)
10462 for (ndx = 0; actions_list[ndx]; ndx++)
10463 xfree (actions_list[ndx]);
10465 xfree (actions_list);
10468 /* Recursive routine to walk through command list including loops, and
10469 download packets for each command. */
10472 remote_download_command_source (int num, ULONGEST addr,
10473 struct command_line *cmds)
10475 struct remote_state *rs = get_remote_state ();
10476 struct command_line *cmd;
10478 for (cmd = cmds; cmd; cmd = cmd->next)
10480 QUIT; /* Allow user to bail out with ^C. */
10481 strcpy (rs->buf, "QTDPsrc:");
10482 encode_source_string (num, addr, "cmd", cmd->line,
10483 rs->buf + strlen (rs->buf),
10484 rs->buf_size - strlen (rs->buf));
10486 remote_get_noisy_reply (&target_buf, &target_buf_size);
10487 if (strcmp (target_buf, "OK"))
10488 warning (_("Target does not support source download."));
10490 if (cmd->control_type == while_control
10491 || cmd->control_type == while_stepping_control)
10493 remote_download_command_source (num, addr, *cmd->body_list);
10495 QUIT; /* Allow user to bail out with ^C. */
10496 strcpy (rs->buf, "QTDPsrc:");
10497 encode_source_string (num, addr, "cmd", "end",
10498 rs->buf + strlen (rs->buf),
10499 rs->buf_size - strlen (rs->buf));
10501 remote_get_noisy_reply (&target_buf, &target_buf_size);
10502 if (strcmp (target_buf, "OK"))
10503 warning (_("Target does not support source download."));
10509 remote_download_tracepoint (struct bp_location *loc)
10511 #define BUF_SIZE 2048
10515 char buf[BUF_SIZE];
10516 char **tdp_actions;
10517 char **stepping_actions;
10519 struct cleanup *old_chain = NULL;
10520 struct agent_expr *aexpr;
10521 struct cleanup *aexpr_chain = NULL;
10523 struct breakpoint *b = loc->owner;
10524 struct tracepoint *t = (struct tracepoint *) b;
10526 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10527 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10529 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10532 tpaddr = loc->address;
10533 sprintf_vma (addrbuf, tpaddr);
10534 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10535 addrbuf, /* address */
10536 (b->enable_state == bp_enabled ? 'E' : 'D'),
10537 t->step_count, t->pass_count);
10538 /* Fast tracepoints are mostly handled by the target, but we can
10539 tell the target how big of an instruction block should be moved
10541 if (b->type == bp_fast_tracepoint)
10543 /* Only test for support at download time; we may not know
10544 target capabilities at definition time. */
10545 if (remote_supports_fast_tracepoints ())
10549 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10550 tpaddr, &isize, NULL))
10551 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10554 /* If it passed validation at definition but fails now,
10555 something is very wrong. */
10556 internal_error (__FILE__, __LINE__,
10557 _("Fast tracepoint not "
10558 "valid during download"));
10561 /* Fast tracepoints are functionally identical to regular
10562 tracepoints, so don't take lack of support as a reason to
10563 give up on the trace run. */
10564 warning (_("Target does not support fast tracepoints, "
10565 "downloading %d as regular tracepoint"), b->number);
10567 else if (b->type == bp_static_tracepoint)
10569 /* Only test for support at download time; we may not know
10570 target capabilities at definition time. */
10571 if (remote_supports_static_tracepoints ())
10573 struct static_tracepoint_marker marker;
10575 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10576 strcat (buf, ":S");
10578 error (_("Static tracepoint not valid during download"));
10581 /* Fast tracepoints are functionally identical to regular
10582 tracepoints, so don't take lack of support as a reason
10583 to give up on the trace run. */
10584 error (_("Target does not support static tracepoints"));
10586 /* If the tracepoint has a conditional, make it into an agent
10587 expression and append to the definition. */
10590 /* Only test support at download time, we may not know target
10591 capabilities at definition time. */
10592 if (remote_supports_cond_tracepoints ())
10594 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10595 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10596 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10598 pkt = buf + strlen (buf);
10599 for (ndx = 0; ndx < aexpr->len; ++ndx)
10600 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10602 do_cleanups (aexpr_chain);
10605 warning (_("Target does not support conditional tracepoints, "
10606 "ignoring tp %d cond"), b->number);
10609 if (b->commands || *default_collect)
10612 remote_get_noisy_reply (&target_buf, &target_buf_size);
10613 if (strcmp (target_buf, "OK"))
10614 error (_("Target does not support tracepoints."));
10616 /* do_single_steps (t); */
10619 for (ndx = 0; tdp_actions[ndx]; ndx++)
10621 QUIT; /* Allow user to bail out with ^C. */
10622 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10623 b->number, addrbuf, /* address */
10625 ((tdp_actions[ndx + 1] || stepping_actions)
10628 remote_get_noisy_reply (&target_buf,
10630 if (strcmp (target_buf, "OK"))
10631 error (_("Error on target while setting tracepoints."));
10634 if (stepping_actions)
10636 for (ndx = 0; stepping_actions[ndx]; ndx++)
10638 QUIT; /* Allow user to bail out with ^C. */
10639 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10640 b->number, addrbuf, /* address */
10641 ((ndx == 0) ? "S" : ""),
10642 stepping_actions[ndx],
10643 (stepping_actions[ndx + 1] ? "-" : ""));
10645 remote_get_noisy_reply (&target_buf,
10647 if (strcmp (target_buf, "OK"))
10648 error (_("Error on target while setting tracepoints."));
10652 if (remote_protocol_packets[PACKET_TracepointSource].support
10655 if (b->addr_string)
10657 strcpy (buf, "QTDPsrc:");
10658 encode_source_string (b->number, loc->address,
10659 "at", b->addr_string, buf + strlen (buf),
10660 2048 - strlen (buf));
10663 remote_get_noisy_reply (&target_buf, &target_buf_size);
10664 if (strcmp (target_buf, "OK"))
10665 warning (_("Target does not support source download."));
10667 if (b->cond_string)
10669 strcpy (buf, "QTDPsrc:");
10670 encode_source_string (b->number, loc->address,
10671 "cond", b->cond_string, buf + strlen (buf),
10672 2048 - strlen (buf));
10674 remote_get_noisy_reply (&target_buf, &target_buf_size);
10675 if (strcmp (target_buf, "OK"))
10676 warning (_("Target does not support source download."));
10678 remote_download_command_source (b->number, loc->address,
10679 breakpoint_commands (b));
10682 do_cleanups (old_chain);
10686 remote_can_download_tracepoint (void)
10688 struct remote_state *rs = get_remote_state ();
10689 struct trace_status *ts;
10692 /* Don't try to install tracepoints until we've relocated our
10693 symbols, and fetched and merged the target's tracepoint list with
10695 if (rs->starting_up)
10698 ts = current_trace_status ();
10699 status = remote_get_trace_status (ts);
10701 if (status == -1 || !ts->running_known || !ts->running)
10704 /* If we are in a tracing experiment, but remote stub doesn't support
10705 installing tracepoint in trace, we have to return. */
10706 if (!remote_supports_install_in_trace ())
10714 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10716 struct remote_state *rs = get_remote_state ();
10719 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10720 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10722 p = rs->buf + strlen (rs->buf);
10723 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10724 error (_("Trace state variable name too long for tsv definition packet"));
10725 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10728 remote_get_noisy_reply (&target_buf, &target_buf_size);
10729 if (*target_buf == '\0')
10730 error (_("Target does not support this command."));
10731 if (strcmp (target_buf, "OK") != 0)
10732 error (_("Error on target while downloading trace state variable."));
10736 remote_enable_tracepoint (struct bp_location *location)
10738 struct remote_state *rs = get_remote_state ();
10741 sprintf_vma (addr_buf, location->address);
10742 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10743 location->owner->number, addr_buf);
10745 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10746 if (*rs->buf == '\0')
10747 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10748 if (strcmp (rs->buf, "OK") != 0)
10749 error (_("Error on target while enabling tracepoint."));
10753 remote_disable_tracepoint (struct bp_location *location)
10755 struct remote_state *rs = get_remote_state ();
10758 sprintf_vma (addr_buf, location->address);
10759 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10760 location->owner->number, addr_buf);
10762 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10763 if (*rs->buf == '\0')
10764 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10765 if (strcmp (rs->buf, "OK") != 0)
10766 error (_("Error on target while disabling tracepoint."));
10770 remote_trace_set_readonly_regions (void)
10774 bfd_size_type size;
10780 return; /* No information to give. */
10782 strcpy (target_buf, "QTro");
10783 offset = strlen (target_buf);
10784 for (s = exec_bfd->sections; s; s = s->next)
10786 char tmp1[40], tmp2[40];
10789 if ((s->flags & SEC_LOAD) == 0 ||
10790 /* (s->flags & SEC_CODE) == 0 || */
10791 (s->flags & SEC_READONLY) == 0)
10795 vma = bfd_get_section_vma (abfd, s);
10796 size = bfd_get_section_size (s);
10797 sprintf_vma (tmp1, vma);
10798 sprintf_vma (tmp2, vma + size);
10799 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10800 if (offset + sec_length + 1 > target_buf_size)
10802 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10805 Too many sections for read-only sections definition packet."));
10808 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10810 offset += sec_length;
10814 putpkt (target_buf);
10815 getpkt (&target_buf, &target_buf_size, 0);
10820 remote_trace_start (void)
10822 putpkt ("QTStart");
10823 remote_get_noisy_reply (&target_buf, &target_buf_size);
10824 if (*target_buf == '\0')
10825 error (_("Target does not support this command."));
10826 if (strcmp (target_buf, "OK") != 0)
10827 error (_("Bogus reply from target: %s"), target_buf);
10831 remote_get_trace_status (struct trace_status *ts)
10833 /* Initialize it just to avoid a GCC false warning. */
10835 /* FIXME we need to get register block size some other way. */
10836 extern int trace_regblock_size;
10837 volatile struct gdb_exception ex;
10838 enum packet_result result;
10840 if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
10843 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10845 putpkt ("qTStatus");
10847 TRY_CATCH (ex, RETURN_MASK_ERROR)
10849 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10853 if (ex.error != TARGET_CLOSE_ERROR)
10855 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10858 throw_exception (ex);
10861 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10863 /* If the remote target doesn't do tracing, flag it. */
10864 if (result == PACKET_UNKNOWN)
10867 /* We're working with a live target. */
10868 ts->filename = NULL;
10871 error (_("Bogus trace status reply from target: %s"), target_buf);
10873 /* Function 'parse_trace_status' sets default value of each field of
10874 'ts' at first, so we don't have to do it here. */
10875 parse_trace_status (p, ts);
10877 return ts->running;
10881 remote_get_tracepoint_status (struct breakpoint *bp,
10882 struct uploaded_tp *utp)
10884 struct remote_state *rs = get_remote_state ();
10886 struct bp_location *loc;
10887 struct tracepoint *tp = (struct tracepoint *) bp;
10888 size_t size = get_remote_packet_size ();
10892 tp->base.hit_count = 0;
10893 tp->traceframe_usage = 0;
10894 for (loc = tp->base.loc; loc; loc = loc->next)
10896 /* If the tracepoint was never downloaded, don't go asking for
10898 if (tp->number_on_target == 0)
10900 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10901 phex_nz (loc->address, 0));
10903 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10904 if (reply && *reply)
10907 parse_tracepoint_status (reply + 1, bp, utp);
10913 utp->hit_count = 0;
10914 utp->traceframe_usage = 0;
10915 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10916 phex_nz (utp->addr, 0));
10918 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10919 if (reply && *reply)
10922 parse_tracepoint_status (reply + 1, bp, utp);
10928 remote_trace_stop (void)
10931 remote_get_noisy_reply (&target_buf, &target_buf_size);
10932 if (*target_buf == '\0')
10933 error (_("Target does not support this command."));
10934 if (strcmp (target_buf, "OK") != 0)
10935 error (_("Bogus reply from target: %s"), target_buf);
10939 remote_trace_find (enum trace_find_type type, int num,
10940 CORE_ADDR addr1, CORE_ADDR addr2,
10943 struct remote_state *rs = get_remote_state ();
10944 char *endbuf = rs->buf + get_remote_packet_size ();
10946 int target_frameno = -1, target_tracept = -1;
10948 /* Lookups other than by absolute frame number depend on the current
10949 trace selected, so make sure it is correct on the remote end
10951 if (type != tfind_number)
10952 set_remote_traceframe ();
10955 strcpy (p, "QTFrame:");
10956 p = strchr (p, '\0');
10960 xsnprintf (p, endbuf - p, "%x", num);
10963 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
10966 xsnprintf (p, endbuf - p, "tdp:%x", num);
10969 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10970 phex_nz (addr2, 0));
10972 case tfind_outside:
10973 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10974 phex_nz (addr2, 0));
10977 error (_("Unknown trace find type %d"), type);
10981 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
10982 if (*reply == '\0')
10983 error (_("Target does not support this command."));
10985 while (reply && *reply)
10990 target_frameno = (int) strtol (p, &reply, 16);
10992 error (_("Unable to parse trace frame number"));
10993 /* Don't update our remote traceframe number cache on failure
10994 to select a remote traceframe. */
10995 if (target_frameno == -1)
11000 target_tracept = (int) strtol (p, &reply, 16);
11002 error (_("Unable to parse tracepoint number"));
11004 case 'O': /* "OK"? */
11005 if (reply[1] == 'K' && reply[2] == '\0')
11008 error (_("Bogus reply from target: %s"), reply);
11011 error (_("Bogus reply from target: %s"), reply);
11014 *tpp = target_tracept;
11016 rs->remote_traceframe_number = target_frameno;
11017 return target_frameno;
11021 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
11023 struct remote_state *rs = get_remote_state ();
11027 set_remote_traceframe ();
11029 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11031 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11032 if (reply && *reply)
11036 unpack_varlen_hex (reply + 1, &uval);
11037 *val = (LONGEST) uval;
11045 remote_save_trace_data (const char *filename)
11047 struct remote_state *rs = get_remote_state ();
11051 strcpy (p, "QTSave:");
11053 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11054 error (_("Remote file name too long for trace save packet"));
11055 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
11058 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11059 if (*reply == '\0')
11060 error (_("Target does not support this command."));
11061 if (strcmp (reply, "OK") != 0)
11062 error (_("Bogus reply from target: %s"), reply);
11066 /* This is basically a memory transfer, but needs to be its own packet
11067 because we don't know how the target actually organizes its trace
11068 memory, plus we want to be able to ask for as much as possible, but
11069 not be unhappy if we don't get as much as we ask for. */
11072 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
11074 struct remote_state *rs = get_remote_state ();
11080 strcpy (p, "qTBuffer:");
11082 p += hexnumstr (p, offset);
11084 p += hexnumstr (p, len);
11088 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11089 if (reply && *reply)
11091 /* 'l' by itself means we're at the end of the buffer and
11092 there is nothing more to get. */
11096 /* Convert the reply into binary. Limit the number of bytes to
11097 convert according to our passed-in buffer size, rather than
11098 what was returned in the packet; if the target is
11099 unexpectedly generous and gives us a bigger reply than we
11100 asked for, we don't want to crash. */
11101 rslt = hex2bin (target_buf, buf, len);
11105 /* Something went wrong, flag as an error. */
11110 remote_set_disconnected_tracing (int val)
11112 struct remote_state *rs = get_remote_state ();
11114 if (rs->disconnected_tracing)
11118 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11120 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11121 if (*reply == '\0')
11122 error (_("Target does not support this command."));
11123 if (strcmp (reply, "OK") != 0)
11124 error (_("Bogus reply from target: %s"), reply);
11127 warning (_("Target does not support disconnected tracing."));
11131 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11133 struct thread_info *info = find_thread_ptid (ptid);
11135 if (info && info->private)
11136 return info->private->core;
11141 remote_set_circular_trace_buffer (int val)
11143 struct remote_state *rs = get_remote_state ();
11146 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11148 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11149 if (*reply == '\0')
11150 error (_("Target does not support this command."));
11151 if (strcmp (reply, "OK") != 0)
11152 error (_("Bogus reply from target: %s"), reply);
11155 static struct traceframe_info *
11156 remote_traceframe_info (void)
11160 /* If current traceframe is not selected, don't bother the remote
11162 if (get_traceframe_number () < 0)
11165 text = target_read_stralloc (¤t_target,
11166 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11169 struct traceframe_info *info;
11170 struct cleanup *back_to = make_cleanup (xfree, text);
11172 info = parse_traceframe_info (text);
11173 do_cleanups (back_to);
11180 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11181 instruction on which a fast tracepoint may be placed. Returns -1
11182 if the packet is not supported, and 0 if the minimum instruction
11183 length is unknown. */
11186 remote_get_min_fast_tracepoint_insn_len (void)
11188 struct remote_state *rs = get_remote_state ();
11191 /* If we're not debugging a process yet, the IPA can't be
11193 if (!target_has_execution)
11196 /* Make sure the remote is pointing at the right process. */
11197 set_general_process ();
11199 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11201 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11202 if (*reply == '\0')
11206 ULONGEST min_insn_len;
11208 unpack_varlen_hex (reply, &min_insn_len);
11210 return (int) min_insn_len;
11215 remote_set_trace_buffer_size (LONGEST val)
11217 if (remote_protocol_packets[PACKET_QTBuffer_size].support
11220 struct remote_state *rs = get_remote_state ();
11221 char *buf = rs->buf;
11222 char *endbuf = rs->buf + get_remote_packet_size ();
11223 enum packet_result result;
11225 gdb_assert (val >= 0 || val == -1);
11226 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11227 /* Send -1 as literal "-1" to avoid host size dependency. */
11231 buf += hexnumstr (buf, (ULONGEST) -val);
11234 buf += hexnumstr (buf, (ULONGEST) val);
11237 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11238 result = packet_ok (rs->buf,
11239 &remote_protocol_packets[PACKET_QTBuffer_size]);
11241 if (result != PACKET_OK)
11242 warning (_("Bogus reply from target: %s"), rs->buf);
11247 remote_set_trace_notes (const char *user, const char *notes,
11248 const char *stop_notes)
11250 struct remote_state *rs = get_remote_state ();
11252 char *buf = rs->buf;
11253 char *endbuf = rs->buf + get_remote_packet_size ();
11256 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11259 buf += xsnprintf (buf, endbuf - buf, "user:");
11260 nbytes = bin2hex ((gdb_byte *) user, buf, 0);
11266 buf += xsnprintf (buf, endbuf - buf, "notes:");
11267 nbytes = bin2hex ((gdb_byte *) notes, buf, 0);
11273 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11274 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, 0);
11278 /* Ensure the buffer is terminated. */
11282 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11283 if (*reply == '\0')
11286 if (strcmp (reply, "OK") != 0)
11287 error (_("Bogus reply from target: %s"), reply);
11293 remote_use_agent (int use)
11295 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11297 struct remote_state *rs = get_remote_state ();
11299 /* If the stub supports QAgent. */
11300 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11302 getpkt (&rs->buf, &rs->buf_size, 0);
11304 if (strcmp (rs->buf, "OK") == 0)
11315 remote_can_use_agent (void)
11317 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11320 struct btrace_target_info
11322 /* The ptid of the traced thread. */
11326 /* Check whether the target supports branch tracing. */
11329 remote_supports_btrace (void)
11331 if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11333 if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11335 if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11341 /* Enable branch tracing. */
11343 static struct btrace_target_info *
11344 remote_enable_btrace (ptid_t ptid)
11346 struct btrace_target_info *tinfo = NULL;
11347 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11348 struct remote_state *rs = get_remote_state ();
11349 char *buf = rs->buf;
11350 char *endbuf = rs->buf + get_remote_packet_size ();
11352 if (packet->support != PACKET_ENABLE)
11353 error (_("Target does not support branch tracing."));
11355 set_general_thread (ptid);
11357 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11359 getpkt (&rs->buf, &rs->buf_size, 0);
11361 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11363 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11364 error (_("Could not enable branch tracing for %s: %s"),
11365 target_pid_to_str (ptid), rs->buf + 2);
11367 error (_("Could not enable branch tracing for %s."),
11368 target_pid_to_str (ptid));
11371 tinfo = xzalloc (sizeof (*tinfo));
11372 tinfo->ptid = ptid;
11377 /* Disable branch tracing. */
11380 remote_disable_btrace (struct btrace_target_info *tinfo)
11382 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11383 struct remote_state *rs = get_remote_state ();
11384 char *buf = rs->buf;
11385 char *endbuf = rs->buf + get_remote_packet_size ();
11387 if (packet->support != PACKET_ENABLE)
11388 error (_("Target does not support branch tracing."));
11390 set_general_thread (tinfo->ptid);
11392 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11394 getpkt (&rs->buf, &rs->buf_size, 0);
11396 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11398 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11399 error (_("Could not disable branch tracing for %s: %s"),
11400 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11402 error (_("Could not disable branch tracing for %s."),
11403 target_pid_to_str (tinfo->ptid));
11409 /* Teardown branch tracing. */
11412 remote_teardown_btrace (struct btrace_target_info *tinfo)
11414 /* We must not talk to the target during teardown. */
11418 /* Read the branch trace. */
11420 static VEC (btrace_block_s) *
11421 remote_read_btrace (struct btrace_target_info *tinfo,
11422 enum btrace_read_type type)
11424 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11425 struct remote_state *rs = get_remote_state ();
11426 VEC (btrace_block_s) *btrace = NULL;
11430 if (packet->support != PACKET_ENABLE)
11431 error (_("Target does not support branch tracing."));
11433 #if !defined(HAVE_LIBEXPAT)
11434 error (_("Cannot process branch tracing result. XML parsing not supported."));
11439 case btrace_read_all:
11442 case btrace_read_new:
11446 internal_error (__FILE__, __LINE__,
11447 _("Bad branch tracing read type: %u."),
11448 (unsigned int) type);
11451 xml = target_read_stralloc (¤t_target,
11452 TARGET_OBJECT_BTRACE, annex);
11455 struct cleanup *cleanup = make_cleanup (xfree, xml);
11457 btrace = parse_xml_btrace (xml);
11458 do_cleanups (cleanup);
11465 remote_augmented_libraries_svr4_read (void)
11467 struct remote_state *rs = get_remote_state ();
11469 return rs->augmented_libraries_svr4_read;
11473 init_remote_ops (void)
11475 remote_ops.to_shortname = "remote";
11476 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11477 remote_ops.to_doc =
11478 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11479 Specify the serial device it is connected to\n\
11480 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11481 remote_ops.to_open = remote_open;
11482 remote_ops.to_close = remote_close;
11483 remote_ops.to_detach = remote_detach;
11484 remote_ops.to_disconnect = remote_disconnect;
11485 remote_ops.to_resume = remote_resume;
11486 remote_ops.to_wait = remote_wait;
11487 remote_ops.to_fetch_registers = remote_fetch_registers;
11488 remote_ops.to_store_registers = remote_store_registers;
11489 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11490 remote_ops.to_files_info = remote_files_info;
11491 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11492 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11493 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11494 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11495 remote_ops.to_watchpoint_addr_within_range =
11496 remote_watchpoint_addr_within_range;
11497 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11498 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11499 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11500 remote_ops.to_region_ok_for_hw_watchpoint
11501 = remote_region_ok_for_hw_watchpoint;
11502 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11503 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11504 remote_ops.to_kill = remote_kill;
11505 remote_ops.to_load = generic_load;
11506 remote_ops.to_mourn_inferior = remote_mourn;
11507 remote_ops.to_pass_signals = remote_pass_signals;
11508 remote_ops.to_program_signals = remote_program_signals;
11509 remote_ops.to_thread_alive = remote_thread_alive;
11510 remote_ops.to_find_new_threads = remote_threads_info;
11511 remote_ops.to_pid_to_str = remote_pid_to_str;
11512 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11513 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11514 remote_ops.to_stop = remote_stop;
11515 remote_ops.to_xfer_partial = remote_xfer_partial;
11516 remote_ops.to_rcmd = remote_rcmd;
11517 remote_ops.to_log_command = serial_log_command;
11518 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11519 remote_ops.to_stratum = process_stratum;
11520 remote_ops.to_has_all_memory = default_child_has_all_memory;
11521 remote_ops.to_has_memory = default_child_has_memory;
11522 remote_ops.to_has_stack = default_child_has_stack;
11523 remote_ops.to_has_registers = default_child_has_registers;
11524 remote_ops.to_has_execution = default_child_has_execution;
11525 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11526 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11527 remote_ops.to_magic = OPS_MAGIC;
11528 remote_ops.to_memory_map = remote_memory_map;
11529 remote_ops.to_flash_erase = remote_flash_erase;
11530 remote_ops.to_flash_done = remote_flash_done;
11531 remote_ops.to_read_description = remote_read_description;
11532 remote_ops.to_search_memory = remote_search_memory;
11533 remote_ops.to_can_async_p = remote_can_async_p;
11534 remote_ops.to_is_async_p = remote_is_async_p;
11535 remote_ops.to_async = remote_async;
11536 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11537 remote_ops.to_terminal_ours = remote_terminal_ours;
11538 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11539 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11540 remote_ops.to_supports_disable_randomization
11541 = remote_supports_disable_randomization;
11542 remote_ops.to_fileio_open = remote_hostio_open;
11543 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11544 remote_ops.to_fileio_pread = remote_hostio_pread;
11545 remote_ops.to_fileio_close = remote_hostio_close;
11546 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11547 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11548 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11549 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11550 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11551 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11552 remote_ops.to_trace_init = remote_trace_init;
11553 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11554 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11555 remote_ops.to_download_trace_state_variable
11556 = remote_download_trace_state_variable;
11557 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11558 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11559 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11560 remote_ops.to_trace_start = remote_trace_start;
11561 remote_ops.to_get_trace_status = remote_get_trace_status;
11562 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11563 remote_ops.to_trace_stop = remote_trace_stop;
11564 remote_ops.to_trace_find = remote_trace_find;
11565 remote_ops.to_get_trace_state_variable_value
11566 = remote_get_trace_state_variable_value;
11567 remote_ops.to_save_trace_data = remote_save_trace_data;
11568 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11569 remote_ops.to_upload_trace_state_variables
11570 = remote_upload_trace_state_variables;
11571 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11572 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11573 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11574 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11575 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11576 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11577 remote_ops.to_core_of_thread = remote_core_of_thread;
11578 remote_ops.to_verify_memory = remote_verify_memory;
11579 remote_ops.to_get_tib_address = remote_get_tib_address;
11580 remote_ops.to_set_permissions = remote_set_permissions;
11581 remote_ops.to_static_tracepoint_marker_at
11582 = remote_static_tracepoint_marker_at;
11583 remote_ops.to_static_tracepoint_markers_by_strid
11584 = remote_static_tracepoint_markers_by_strid;
11585 remote_ops.to_traceframe_info = remote_traceframe_info;
11586 remote_ops.to_use_agent = remote_use_agent;
11587 remote_ops.to_can_use_agent = remote_can_use_agent;
11588 remote_ops.to_supports_btrace = remote_supports_btrace;
11589 remote_ops.to_enable_btrace = remote_enable_btrace;
11590 remote_ops.to_disable_btrace = remote_disable_btrace;
11591 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11592 remote_ops.to_read_btrace = remote_read_btrace;
11593 remote_ops.to_augmented_libraries_svr4_read =
11594 remote_augmented_libraries_svr4_read;
11597 /* Set up the extended remote vector by making a copy of the standard
11598 remote vector and adding to it. */
11601 init_extended_remote_ops (void)
11603 extended_remote_ops = remote_ops;
11605 extended_remote_ops.to_shortname = "extended-remote";
11606 extended_remote_ops.to_longname =
11607 "Extended remote serial target in gdb-specific protocol";
11608 extended_remote_ops.to_doc =
11609 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11610 Specify the serial device it is connected to (e.g. /dev/ttya).";
11611 extended_remote_ops.to_open = extended_remote_open;
11612 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11613 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11614 extended_remote_ops.to_detach = extended_remote_detach;
11615 extended_remote_ops.to_attach = extended_remote_attach;
11616 extended_remote_ops.to_kill = extended_remote_kill;
11617 extended_remote_ops.to_supports_disable_randomization
11618 = extended_remote_supports_disable_randomization;
11622 remote_can_async_p (void)
11624 struct remote_state *rs = get_remote_state ();
11626 if (!target_async_permitted)
11627 /* We only enable async when the user specifically asks for it. */
11630 /* We're async whenever the serial device is. */
11631 return serial_can_async_p (rs->remote_desc);
11635 remote_is_async_p (void)
11637 struct remote_state *rs = get_remote_state ();
11639 if (!target_async_permitted)
11640 /* We only enable async when the user specifically asks for it. */
11643 /* We're async whenever the serial device is. */
11644 return serial_is_async_p (rs->remote_desc);
11647 /* Pass the SERIAL event on and up to the client. One day this code
11648 will be able to delay notifying the client of an event until the
11649 point where an entire packet has been received. */
11651 static serial_event_ftype remote_async_serial_handler;
11654 remote_async_serial_handler (struct serial *scb, void *context)
11656 struct remote_state *rs = context;
11658 /* Don't propogate error information up to the client. Instead let
11659 the client find out about the error by querying the target. */
11660 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
11664 remote_async_inferior_event_handler (gdb_client_data data)
11666 inferior_event_handler (INF_REG_EVENT, NULL);
11670 remote_async (void (*callback) (enum inferior_event_type event_type,
11671 void *context), void *context)
11673 struct remote_state *rs = get_remote_state ();
11675 if (callback != NULL)
11677 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11678 rs->async_client_callback = callback;
11679 rs->async_client_context = context;
11682 serial_async (rs->remote_desc, NULL, NULL);
11686 set_remote_cmd (char *args, int from_tty)
11688 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
11692 show_remote_cmd (char *args, int from_tty)
11694 /* We can't just use cmd_show_list here, because we want to skip
11695 the redundant "show remote Z-packet" and the legacy aliases. */
11696 struct cleanup *showlist_chain;
11697 struct cmd_list_element *list = remote_show_cmdlist;
11698 struct ui_out *uiout = current_uiout;
11700 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11701 for (; list != NULL; list = list->next)
11702 if (strcmp (list->name, "Z-packet") == 0)
11704 else if (list->type == not_set_cmd)
11705 /* Alias commands are exactly like the original, except they
11706 don't have the normal type. */
11710 struct cleanup *option_chain
11711 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11713 ui_out_field_string (uiout, "name", list->name);
11714 ui_out_text (uiout, ": ");
11715 if (list->type == show_cmd)
11716 do_show_command ((char *) NULL, from_tty, list);
11718 cmd_func (list, NULL, from_tty);
11719 /* Close the tuple. */
11720 do_cleanups (option_chain);
11723 /* Close the tuple. */
11724 do_cleanups (showlist_chain);
11728 /* Function to be called whenever a new objfile (shlib) is detected. */
11730 remote_new_objfile (struct objfile *objfile)
11732 struct remote_state *rs = get_remote_state ();
11734 if (rs->remote_desc != 0) /* Have a remote connection. */
11735 remote_check_symbols ();
11738 /* Pull all the tracepoints defined on the target and create local
11739 data structures representing them. We don't want to create real
11740 tracepoints yet, we don't want to mess up the user's existing
11744 remote_upload_tracepoints (struct uploaded_tp **utpp)
11746 struct remote_state *rs = get_remote_state ();
11749 /* Ask for a first packet of tracepoint definition. */
11751 getpkt (&rs->buf, &rs->buf_size, 0);
11753 while (*p && *p != 'l')
11755 parse_tracepoint_definition (p, utpp);
11756 /* Ask for another packet of tracepoint definition. */
11758 getpkt (&rs->buf, &rs->buf_size, 0);
11765 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
11767 struct remote_state *rs = get_remote_state ();
11770 /* Ask for a first packet of variable definition. */
11772 getpkt (&rs->buf, &rs->buf_size, 0);
11774 while (*p && *p != 'l')
11776 parse_tsv_definition (p, utsvp);
11777 /* Ask for another packet of variable definition. */
11779 getpkt (&rs->buf, &rs->buf_size, 0);
11785 /* The "set/show range-stepping" show hook. */
11788 show_range_stepping (struct ui_file *file, int from_tty,
11789 struct cmd_list_element *c,
11792 fprintf_filtered (file,
11793 _("Debugger's willingness to use range stepping "
11794 "is %s.\n"), value);
11797 /* The "set/show range-stepping" set hook. */
11800 set_range_stepping (char *ignore_args, int from_tty,
11801 struct cmd_list_element *c)
11803 struct remote_state *rs = get_remote_state ();
11805 /* Whene enabling, check whether range stepping is actually
11806 supported by the target, and warn if not. */
11807 if (use_range_stepping)
11809 if (rs->remote_desc != NULL)
11811 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
11812 remote_vcont_probe (rs);
11814 if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
11815 && rs->supports_vCont.r)
11819 warning (_("Range stepping is not supported by the current target"));
11824 _initialize_remote (void)
11826 struct remote_state *rs;
11827 struct cmd_list_element *cmd;
11828 const char *cmd_name;
11830 /* architecture specific data */
11831 remote_gdbarch_data_handle =
11832 gdbarch_data_register_post_init (init_remote_state);
11833 remote_g_packet_data_handle =
11834 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11836 /* Initialize the per-target state. At the moment there is only one
11837 of these, not one per target. Only one target is active at a
11839 remote_state = new_remote_state ();
11841 init_remote_ops ();
11842 add_target (&remote_ops);
11844 init_extended_remote_ops ();
11845 add_target (&extended_remote_ops);
11847 /* Hook into new objfile notification. */
11848 observer_attach_new_objfile (remote_new_objfile);
11849 /* We're no longer interested in notification events of an inferior
11851 observer_attach_inferior_exit (discard_pending_stop_replies);
11853 /* Set up signal handlers. */
11854 async_sigint_remote_token =
11855 create_async_signal_handler (async_remote_interrupt, NULL);
11856 async_sigint_remote_twice_token =
11857 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11860 init_remote_threadtests ();
11863 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11864 /* set/show remote ... */
11866 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11867 Remote protocol specific variables\n\
11868 Configure various remote-protocol specific variables such as\n\
11869 the packets being used"),
11870 &remote_set_cmdlist, "set remote ",
11871 0 /* allow-unknown */, &setlist);
11872 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11873 Remote protocol specific variables\n\
11874 Configure various remote-protocol specific variables such as\n\
11875 the packets being used"),
11876 &remote_show_cmdlist, "show remote ",
11877 0 /* allow-unknown */, &showlist);
11879 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11880 Compare section data on target to the exec file.\n\
11881 Argument is a single section name (default: all loaded sections)."),
11884 add_cmd ("packet", class_maintenance, packet_command, _("\
11885 Send an arbitrary packet to a remote target.\n\
11886 maintenance packet TEXT\n\
11887 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11888 this command sends the string TEXT to the inferior, and displays the\n\
11889 response packet. GDB supplies the initial `$' character, and the\n\
11890 terminating `#' character and checksum."),
11893 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11894 Set whether to send break if interrupted."), _("\
11895 Show whether to send break if interrupted."), _("\
11896 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11897 set_remotebreak, show_remotebreak,
11898 &setlist, &showlist);
11899 cmd_name = "remotebreak";
11900 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11901 deprecate_cmd (cmd, "set remote interrupt-sequence");
11902 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11903 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11904 deprecate_cmd (cmd, "show remote interrupt-sequence");
11906 add_setshow_enum_cmd ("interrupt-sequence", class_support,
11907 interrupt_sequence_modes, &interrupt_sequence_mode,
11909 Set interrupt sequence to remote target."), _("\
11910 Show interrupt sequence to remote target."), _("\
11911 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11912 NULL, show_interrupt_sequence,
11913 &remote_set_cmdlist,
11914 &remote_show_cmdlist);
11916 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11917 &interrupt_on_connect, _("\
11918 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11919 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11920 If set, interrupt sequence is sent to remote target."),
11922 &remote_set_cmdlist, &remote_show_cmdlist);
11924 /* Install commands for configuring memory read/write packets. */
11926 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11927 Set the maximum number of bytes per memory write packet (deprecated)."),
11929 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11930 Show the maximum number of bytes per memory write packet (deprecated)."),
11932 add_cmd ("memory-write-packet-size", no_class,
11933 set_memory_write_packet_size, _("\
11934 Set the maximum number of bytes per memory-write packet.\n\
11935 Specify the number of bytes in a packet or 0 (zero) for the\n\
11936 default packet size. The actual limit is further reduced\n\
11937 dependent on the target. Specify ``fixed'' to disable the\n\
11938 further restriction and ``limit'' to enable that restriction."),
11939 &remote_set_cmdlist);
11940 add_cmd ("memory-read-packet-size", no_class,
11941 set_memory_read_packet_size, _("\
11942 Set the maximum number of bytes per memory-read packet.\n\
11943 Specify the number of bytes in a packet or 0 (zero) for the\n\
11944 default packet size. The actual limit is further reduced\n\
11945 dependent on the target. Specify ``fixed'' to disable the\n\
11946 further restriction and ``limit'' to enable that restriction."),
11947 &remote_set_cmdlist);
11948 add_cmd ("memory-write-packet-size", no_class,
11949 show_memory_write_packet_size,
11950 _("Show the maximum number of bytes per memory-write packet."),
11951 &remote_show_cmdlist);
11952 add_cmd ("memory-read-packet-size", no_class,
11953 show_memory_read_packet_size,
11954 _("Show the maximum number of bytes per memory-read packet."),
11955 &remote_show_cmdlist);
11957 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11958 &remote_hw_watchpoint_limit, _("\
11959 Set the maximum number of target hardware watchpoints."), _("\
11960 Show the maximum number of target hardware watchpoints."), _("\
11961 Specify a negative limit for unlimited."),
11962 NULL, NULL, /* FIXME: i18n: The maximum
11963 number of target hardware
11964 watchpoints is %s. */
11965 &remote_set_cmdlist, &remote_show_cmdlist);
11966 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11967 &remote_hw_watchpoint_length_limit, _("\
11968 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11969 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11970 Specify a negative limit for unlimited."),
11971 NULL, NULL, /* FIXME: i18n: The maximum
11972 length (in bytes) of a target
11973 hardware watchpoint is %s. */
11974 &remote_set_cmdlist, &remote_show_cmdlist);
11975 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11976 &remote_hw_breakpoint_limit, _("\
11977 Set the maximum number of target hardware breakpoints."), _("\
11978 Show the maximum number of target hardware breakpoints."), _("\
11979 Specify a negative limit for unlimited."),
11980 NULL, NULL, /* FIXME: i18n: The maximum
11981 number of target hardware
11982 breakpoints is %s. */
11983 &remote_set_cmdlist, &remote_show_cmdlist);
11985 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
11986 &remote_address_size, _("\
11987 Set the maximum size of the address (in bits) in a memory packet."), _("\
11988 Show the maximum size of the address (in bits) in a memory packet."), NULL,
11990 NULL, /* FIXME: i18n: */
11991 &setlist, &showlist);
11993 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
11994 "X", "binary-download", 1);
11996 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
11997 "vCont", "verbose-resume", 0);
11999 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12000 "QPassSignals", "pass-signals", 0);
12002 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12003 "QProgramSignals", "program-signals", 0);
12005 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12006 "qSymbol", "symbol-lookup", 0);
12008 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12009 "P", "set-register", 1);
12011 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12012 "p", "fetch-register", 1);
12014 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12015 "Z0", "software-breakpoint", 0);
12017 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12018 "Z1", "hardware-breakpoint", 0);
12020 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12021 "Z2", "write-watchpoint", 0);
12023 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12024 "Z3", "read-watchpoint", 0);
12026 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12027 "Z4", "access-watchpoint", 0);
12029 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12030 "qXfer:auxv:read", "read-aux-vector", 0);
12032 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12033 "qXfer:features:read", "target-features", 0);
12035 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12036 "qXfer:libraries:read", "library-info", 0);
12038 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12039 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12041 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12042 "qXfer:memory-map:read", "memory-map", 0);
12044 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12045 "qXfer:spu:read", "read-spu-object", 0);
12047 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12048 "qXfer:spu:write", "write-spu-object", 0);
12050 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12051 "qXfer:osdata:read", "osdata", 0);
12053 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12054 "qXfer:threads:read", "threads", 0);
12056 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12057 "qXfer:siginfo:read", "read-siginfo-object", 0);
12059 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12060 "qXfer:siginfo:write", "write-siginfo-object", 0);
12062 add_packet_config_cmd
12063 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12064 "qXfer:traceframe-info:read", "traceframe-info", 0);
12066 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12067 "qXfer:uib:read", "unwind-info-block", 0);
12069 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12070 "qGetTLSAddr", "get-thread-local-storage-address",
12073 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12074 "qGetTIBAddr", "get-thread-information-block-address",
12077 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12078 "bc", "reverse-continue", 0);
12080 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12081 "bs", "reverse-step", 0);
12083 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12084 "qSupported", "supported-packets", 0);
12086 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12087 "qSearch:memory", "search-memory", 0);
12089 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12090 "qTStatus", "trace-status", 0);
12092 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12093 "vFile:open", "hostio-open", 0);
12095 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12096 "vFile:pread", "hostio-pread", 0);
12098 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12099 "vFile:pwrite", "hostio-pwrite", 0);
12101 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12102 "vFile:close", "hostio-close", 0);
12104 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12105 "vFile:unlink", "hostio-unlink", 0);
12107 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12108 "vFile:readlink", "hostio-readlink", 0);
12110 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12111 "vAttach", "attach", 0);
12113 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12116 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12117 "QStartNoAckMode", "noack", 0);
12119 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12120 "vKill", "kill", 0);
12122 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12123 "qAttached", "query-attached", 0);
12125 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12126 "ConditionalTracepoints",
12127 "conditional-tracepoints", 0);
12129 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12130 "ConditionalBreakpoints",
12131 "conditional-breakpoints", 0);
12133 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12134 "BreakpointCommands",
12135 "breakpoint-commands", 0);
12137 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12138 "FastTracepoints", "fast-tracepoints", 0);
12140 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12141 "TracepointSource", "TracepointSource", 0);
12143 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12144 "QAllow", "allow", 0);
12146 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12147 "StaticTracepoints", "static-tracepoints", 0);
12149 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12150 "InstallInTrace", "install-in-trace", 0);
12152 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12153 "qXfer:statictrace:read", "read-sdata-object", 0);
12155 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12156 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12158 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12159 "QDisableRandomization", "disable-randomization", 0);
12161 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12162 "QAgent", "agent", 0);
12164 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12165 "QTBuffer:size", "trace-buffer-size", 0);
12167 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12168 "Qbtrace:off", "disable-btrace", 0);
12170 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12171 "Qbtrace:bts", "enable-btrace", 0);
12173 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12174 "qXfer:btrace", "read-btrace", 0);
12176 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12177 Z sub-packet has its own set and show commands, but users may
12178 have sets to this variable in their .gdbinit files (or in their
12180 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12181 &remote_Z_packet_detect, _("\
12182 Set use of remote protocol `Z' packets"), _("\
12183 Show use of remote protocol `Z' packets "), _("\
12184 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12186 set_remote_protocol_Z_packet_cmd,
12187 show_remote_protocol_Z_packet_cmd,
12188 /* FIXME: i18n: Use of remote protocol
12189 `Z' packets is %s. */
12190 &remote_set_cmdlist, &remote_show_cmdlist);
12192 add_prefix_cmd ("remote", class_files, remote_command, _("\
12193 Manipulate files on the remote system\n\
12194 Transfer files to and from the remote target system."),
12195 &remote_cmdlist, "remote ",
12196 0 /* allow-unknown */, &cmdlist);
12198 add_cmd ("put", class_files, remote_put_command,
12199 _("Copy a local file to the remote system."),
12202 add_cmd ("get", class_files, remote_get_command,
12203 _("Copy a remote file to the local system."),
12206 add_cmd ("delete", class_files, remote_delete_command,
12207 _("Delete a remote file."),
12210 remote_exec_file = xstrdup ("");
12211 add_setshow_string_noescape_cmd ("exec-file", class_files,
12212 &remote_exec_file, _("\
12213 Set the remote pathname for \"run\""), _("\
12214 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12215 &remote_set_cmdlist, &remote_show_cmdlist);
12217 add_setshow_boolean_cmd ("range-stepping", class_run,
12218 &use_range_stepping, _("\
12219 Enable or disable range stepping."), _("\
12220 Show whether target-assisted range stepping is enabled."), _("\
12221 If on, and the target supports it, when stepping a source line, GDB\n\
12222 tells the target to step the corresponding range of addresses itself instead\n\
12223 of issuing multiple single-steps. This speeds up source level\n\
12224 stepping. If off, GDB always issues single-steps, even if range\n\
12225 stepping is supported by the target. The default is on."),
12226 set_range_stepping,
12227 show_range_stepping,
12231 /* Eventually initialize fileio. See fileio.c */
12232 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12234 /* Take advantage of the fact that the LWP field is not used, to tag
12235 special ptids with it set to != 0. */
12236 magic_null_ptid = ptid_build (42000, 1, -1);
12237 not_sent_ptid = ptid_build (42000, 1, -2);
12238 any_thread_ptid = ptid_build (42000, 1, 0);
12240 target_buf_size = 2048;
12241 target_buf = xmalloc (target_buf_size);