1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2016 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
30 /*#include "terminal.h" */
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
36 #include "remote-notif.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
50 #include "gdb_sys_time.h"
52 #include "event-loop.h"
53 #include "event-top.h"
59 #include "gdbcore.h" /* for exec_bfd */
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
74 /* Temp hacks for tracepoint encoding migration. */
75 static char *target_buf;
76 static long target_buf_size;
78 /* Per-program-space data key. */
79 static const struct program_space_data *remote_pspace_data;
81 /* The variable registered as the control variable used by the
82 remote exec-file commands. While the remote exec-file setting is
83 per-program-space, the set/show machinery uses this as the
84 location of the remote exec-file value. */
85 static char *remote_exec_file_var;
87 /* The size to align memory write packets, when practical. The protocol
88 does not guarantee any alignment, and gdb will generate short
89 writes and unaligned writes, but even as a best-effort attempt this
90 can improve bulk transfers. For instance, if a write is misaligned
91 relative to the target's data bus, the stub may need to make an extra
92 round trip fetching data from the target. This doesn't make a
93 huge difference, but it's easy to do, so we try to be helpful.
95 The alignment chosen is arbitrary; usually data bus width is
96 important here, not the possibly larger cache line size. */
97 enum { REMOTE_ALIGN_WRITES = 16 };
99 /* Prototypes for local functions. */
100 static void async_cleanup_sigint_signal_handler (void *dummy);
101 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
102 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
103 int forever, int *is_notif);
105 static void async_handle_remote_sigint (int);
106 static void async_handle_remote_sigint_twice (int);
108 static void remote_files_info (struct target_ops *ignore);
110 static void remote_prepare_to_store (struct target_ops *self,
111 struct regcache *regcache);
113 static void remote_open_1 (const char *, int, struct target_ops *,
116 static void remote_close (struct target_ops *self);
120 static int remote_vkill (int pid, struct remote_state *rs);
122 static void remote_kill_k (void);
124 static void remote_mourn (struct target_ops *ops);
126 static void extended_remote_restart (void);
128 static void remote_send (char **buf, long *sizeof_buf_p);
130 static int readchar (int timeout);
132 static void remote_serial_write (const char *str, int len);
134 static void remote_kill (struct target_ops *ops);
136 static int remote_can_async_p (struct target_ops *);
138 static int remote_is_async_p (struct target_ops *);
140 static void remote_async (struct target_ops *ops, int enable);
142 static void remote_thread_events (struct target_ops *ops, int enable);
144 static void sync_remote_interrupt_twice (int signo);
146 static void interrupt_query (void);
148 static void set_general_thread (struct ptid ptid);
149 static void set_continue_thread (struct ptid ptid);
151 static void get_offsets (void);
153 static void skip_frame (void);
155 static long read_frame (char **buf_p, long *sizeof_buf);
157 static int hexnumlen (ULONGEST num);
159 static void init_remote_ops (void);
161 static void init_extended_remote_ops (void);
163 static void remote_stop (struct target_ops *self, ptid_t);
165 static int stubhex (int ch);
167 static int hexnumstr (char *, ULONGEST);
169 static int hexnumnstr (char *, ULONGEST, int);
171 static CORE_ADDR remote_address_masked (CORE_ADDR);
173 static void print_packet (const char *);
175 static void compare_sections_command (char *, int);
177 static void packet_command (char *, int);
179 static int stub_unpack_int (char *buff, int fieldlength);
181 static ptid_t remote_current_thread (ptid_t oldptid);
183 static int putpkt_binary (const 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 show_remote_protocol_packet_cmd (struct ui_file *file,
193 struct cmd_list_element *c,
196 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197 static ptid_t read_ptid (char *buf, char **obuf);
199 static void remote_set_permissions (struct target_ops *self);
201 static int remote_get_trace_status (struct target_ops *self,
202 struct trace_status *ts);
204 static int remote_upload_tracepoints (struct target_ops *self,
205 struct uploaded_tp **utpp);
207 static int remote_upload_trace_state_variables (struct target_ops *self,
208 struct uploaded_tsv **utsvp);
210 static void remote_query_supported (void);
212 static void remote_check_symbols (void);
214 void _initialize_remote (void);
217 static void stop_reply_xfree (struct stop_reply *);
218 static void remote_parse_stop_reply (char *, struct stop_reply *);
219 static void push_stop_reply (struct stop_reply *);
220 static void discard_pending_stop_replies_in_queue (struct remote_state *);
221 static int peek_stop_reply (ptid_t ptid);
223 struct threads_listing_context;
224 static void remove_new_fork_children (struct threads_listing_context *);
226 static void remote_async_inferior_event_handler (gdb_client_data);
228 static void remote_terminal_ours (struct target_ops *self);
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 (struct target_ops *self);
236 static int remote_can_run_breakpoint_commands (struct target_ops *self);
238 static void remote_btrace_reset (void);
240 static int stop_reply_queue_length (void);
242 static void readahead_cache_invalidate (void);
246 static struct cmd_list_element *remote_cmdlist;
248 /* For "set remote" and "show remote". */
250 static struct cmd_list_element *remote_set_cmdlist;
251 static struct cmd_list_element *remote_show_cmdlist;
253 /* Stub vCont actions support.
255 Each field is a boolean flag indicating whether the stub reports
256 support for the corresponding action. */
258 struct vCont_action_support
273 /* Controls whether GDB is willing to use range stepping. */
275 static int use_range_stepping = 1;
277 #define OPAQUETHREADBYTES 8
279 /* a 64 bit opaque identifier */
280 typedef unsigned char threadref[OPAQUETHREADBYTES];
282 /* About this many threadisds fit in a packet. */
284 #define MAXTHREADLISTRESULTS 32
286 /* Data for the vFile:pread readahead cache. */
288 struct readahead_cache
290 /* The file descriptor for the file that is being cached. -1 if the
294 /* The offset into the file that the cache buffer corresponds
298 /* The buffer holding the cache contents. */
300 /* The buffer's size. We try to read as much as fits into a packet
304 /* Cache hit and miss counters. */
309 /* Description of the remote protocol state for the currently
310 connected target. This is per-target state, and independent of the
311 selected architecture. */
315 /* A buffer to use for incoming packets, and its current size. The
316 buffer is grown dynamically for larger incoming packets.
317 Outgoing packets may also be constructed in this buffer.
318 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
324 /* True if we're going through initial connection setup (finding out
325 about the remote side's threads, relocating symbols, etc.). */
328 /* If we negotiated packet size explicitly (and thus can bypass
329 heuristics for the largest packet size that will not overflow
330 a buffer in the stub), this will be set to that packet size.
331 Otherwise zero, meaning to use the guessed size. */
332 long explicit_packet_size;
334 /* remote_wait is normally called when the target is running and
335 waits for a stop reply packet. But sometimes we need to call it
336 when the target is already stopped. We can send a "?" packet
337 and have remote_wait read the response. Or, if we already have
338 the response, we can stash it in BUF and tell remote_wait to
339 skip calling getpkt. This flag is set when BUF contains a
340 stop reply packet and the target is not waiting. */
341 int cached_wait_status;
343 /* True, if in no ack mode. That is, neither GDB nor the stub will
344 expect acks from each other. The connection is assumed to be
348 /* True if we're connected in extended remote mode. */
351 /* True if we resumed the target and we're waiting for the target to
352 stop. In the mean time, we can't start another command/query.
353 The remote server wouldn't be ready to process it, so we'd
354 timeout waiting for a reply that would never come and eventually
355 we'd close the connection. This can happen in asynchronous mode
356 because we allow GDB commands while the target is running. */
357 int waiting_for_stop_reply;
359 /* The status of the stub support for the various vCont actions. */
360 struct vCont_action_support supports_vCont;
362 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363 responded to that. */
366 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
367 remote_open knows that we don't have a file open when the program
369 struct serial *remote_desc;
371 /* These are the threads which we last sent to the remote system. The
372 TID member will be -1 for all or -2 for not sent yet. */
373 ptid_t general_thread;
374 ptid_t continue_thread;
376 /* This is the traceframe which we last selected on the remote system.
377 It will be -1 if no traceframe is selected. */
378 int remote_traceframe_number;
380 char *last_pass_packet;
382 /* The last QProgramSignals packet sent to the target. We bypass
383 sending a new program signals list down to the target if the new
384 packet is exactly the same as the last we sent. IOW, we only let
385 the target know about program signals list changes. */
386 char *last_program_signals_packet;
388 enum gdb_signal last_sent_signal;
392 char *finished_object;
393 char *finished_annex;
394 ULONGEST finished_offset;
396 /* Should we try the 'ThreadInfo' query packet?
398 This variable (NOT available to the user: auto-detect only!)
399 determines whether GDB will use the new, simpler "ThreadInfo"
400 query or the older, more complex syntax for thread queries.
401 This is an auto-detect variable (set to true at each connect,
402 and set to false when the target fails to recognize it). */
403 int use_threadinfo_query;
404 int use_threadextra_query;
406 threadref echo_nextthread;
407 threadref nextthread;
408 threadref resultthreadlist[MAXTHREADLISTRESULTS];
410 /* The state of remote notification. */
411 struct remote_notif_state *notif_state;
413 /* The branch trace configuration. */
414 struct btrace_config btrace_config;
416 /* The argument to the last "vFile:setfs:" packet we sent, used
417 to avoid sending repeated unnecessary "vFile:setfs:" packets.
418 Initialized to -1 to indicate that no "vFile:setfs:" packet
419 has yet been sent. */
422 /* A readahead cache for vFile:pread. Often, reading a binary
423 involves a sequence of small reads. E.g., when parsing an ELF
424 file. A readahead cache helps mostly the case of remote
425 debugging on a connection with higher latency, due to the
426 request/reply nature of the RSP. We only cache data for a single
427 file descriptor at a time. */
428 struct readahead_cache readahead_cache;
430 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
431 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
432 as a reply to known packet. For packet "vFile:setfs:" it is an
433 invalid reply and GDB would return error in
434 remote_hostio_set_filesystem, making remote files access impossible.
435 If this variable is non-zero it means the remote gdbserver is buggy
436 and any not yet detected packets are assumed as unsupported. */
437 int unknown_v_replies_ok;
440 /* Private data that we'll store in (struct thread_info)->private. */
441 struct private_thread_info
447 /* Whether the target stopped for a breakpoint/watchpoint. */
448 enum target_stop_reason stop_reason;
450 /* This is set to the data address of the access causing the target
451 to stop for a watchpoint. */
452 CORE_ADDR watch_data_address;
456 free_private_thread_info (struct private_thread_info *info)
463 /* This data could be associated with a target, but we do not always
464 have access to the current target when we need it, so for now it is
465 static. This will be fine for as long as only one target is in use
467 static struct remote_state *remote_state;
469 static struct remote_state *
470 get_remote_state_raw (void)
475 /* Allocate a new struct remote_state with xmalloc, initialize it, and
478 static struct remote_state *
479 new_remote_state (void)
481 struct remote_state *result = XCNEW (struct remote_state);
483 /* The default buffer size is unimportant; it will be expanded
484 whenever a larger buffer is needed. */
485 result->buf_size = 400;
486 result->buf = (char *) xmalloc (result->buf_size);
487 result->remote_traceframe_number = -1;
488 result->last_sent_signal = GDB_SIGNAL_0;
494 /* Description of the remote protocol for a given architecture. */
498 long offset; /* Offset into G packet. */
499 long regnum; /* GDB's internal register number. */
500 LONGEST pnum; /* Remote protocol register number. */
501 int in_g_packet; /* Always part of G packet. */
502 /* long size in bytes; == register_size (target_gdbarch (), regnum);
504 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
508 struct remote_arch_state
510 /* Description of the remote protocol registers. */
511 long sizeof_g_packet;
513 /* Description of the remote protocol registers indexed by REGNUM
514 (making an array gdbarch_num_regs in size). */
515 struct packet_reg *regs;
517 /* This is the size (in chars) of the first response to the ``g''
518 packet. It is used as a heuristic when determining the maximum
519 size of memory-read and memory-write packets. A target will
520 typically only reserve a buffer large enough to hold the ``g''
521 packet. The size does not include packet overhead (headers and
523 long actual_register_packet_size;
525 /* This is the maximum size (in chars) of a non read/write packet.
526 It is also used as a cap on the size of read/write packets. */
527 long remote_packet_size;
530 /* Utility: generate error from an incoming stub packet. */
532 trace_error (char *buf)
535 return; /* not an error msg */
538 case '1': /* malformed packet error */
539 if (*++buf == '0') /* general case: */
540 error (_("remote.c: error in outgoing packet."));
542 error (_("remote.c: error in outgoing packet at field #%ld."),
543 strtol (buf, NULL, 16));
545 error (_("Target returns error code '%s'."), buf);
549 /* Utility: wait for reply from stub, while accepting "O" packets. */
551 remote_get_noisy_reply (char **buf_p,
554 do /* Loop on reply from remote stub. */
558 QUIT; /* Allow user to bail out with ^C. */
559 getpkt (buf_p, sizeof_buf, 0);
563 else if (startswith (buf, "qRelocInsn:"))
566 CORE_ADDR from, to, org_to;
568 int adjusted_size = 0;
571 p = buf + strlen ("qRelocInsn:");
572 pp = unpack_varlen_hex (p, &ul);
574 error (_("invalid qRelocInsn packet: %s"), buf);
578 unpack_varlen_hex (p, &ul);
585 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
588 CATCH (ex, RETURN_MASK_ALL)
590 if (ex.error == MEMORY_ERROR)
592 /* Propagate memory errors silently back to the
593 target. The stub may have limited the range of
594 addresses we can write to, for example. */
598 /* Something unexpectedly bad happened. Be verbose
599 so we can tell what, and propagate the error back
600 to the stub, so it doesn't get stuck waiting for
602 exception_fprintf (gdb_stderr, ex,
603 _("warning: relocating instruction: "));
611 adjusted_size = to - org_to;
613 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
617 else if (buf[0] == 'O' && buf[1] != 'K')
618 remote_console_output (buf + 1); /* 'O' message from stub */
620 return buf; /* Here's the actual reply. */
625 /* Handle for retreving the remote protocol data from gdbarch. */
626 static struct gdbarch_data *remote_gdbarch_data_handle;
628 static struct remote_arch_state *
629 get_remote_arch_state (void)
631 gdb_assert (target_gdbarch () != NULL);
632 return ((struct remote_arch_state *)
633 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
636 /* Fetch the global remote target state. */
638 static struct remote_state *
639 get_remote_state (void)
641 /* Make sure that the remote architecture state has been
642 initialized, because doing so might reallocate rs->buf. Any
643 function which calls getpkt also needs to be mindful of changes
644 to rs->buf, but this call limits the number of places which run
646 get_remote_arch_state ();
648 return get_remote_state_raw ();
651 /* Cleanup routine for the remote module's pspace data. */
654 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
656 char *remote_exec_file = (char *) arg;
658 xfree (remote_exec_file);
661 /* Fetch the remote exec-file from the current program space. */
664 get_remote_exec_file (void)
666 char *remote_exec_file;
669 = (char *) program_space_data (current_program_space,
671 if (remote_exec_file == NULL)
674 return remote_exec_file;
677 /* Set the remote exec file for PSPACE. */
680 set_pspace_remote_exec_file (struct program_space *pspace,
681 char *remote_exec_file)
683 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
686 set_program_space_data (pspace, remote_pspace_data,
687 xstrdup (remote_exec_file));
690 /* The "set/show remote exec-file" set command hook. */
693 set_remote_exec_file (char *ignored, int from_tty,
694 struct cmd_list_element *c)
696 gdb_assert (remote_exec_file_var != NULL);
697 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
700 /* The "set/show remote exec-file" show command hook. */
703 show_remote_exec_file (struct ui_file *file, int from_tty,
704 struct cmd_list_element *cmd, const char *value)
706 fprintf_filtered (file, "%s\n", remote_exec_file_var);
710 compare_pnums (const void *lhs_, const void *rhs_)
712 const struct packet_reg * const *lhs
713 = (const struct packet_reg * const *) lhs_;
714 const struct packet_reg * const *rhs
715 = (const struct packet_reg * const *) rhs_;
717 if ((*lhs)->pnum < (*rhs)->pnum)
719 else if ((*lhs)->pnum == (*rhs)->pnum)
726 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
728 int regnum, num_remote_regs, offset;
729 struct packet_reg **remote_regs;
731 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
733 struct packet_reg *r = ®s[regnum];
735 if (register_size (gdbarch, regnum) == 0)
736 /* Do not try to fetch zero-sized (placeholder) registers. */
739 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
744 /* Define the g/G packet format as the contents of each register
745 with a remote protocol number, in order of ascending protocol
748 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
749 for (num_remote_regs = 0, regnum = 0;
750 regnum < gdbarch_num_regs (gdbarch);
752 if (regs[regnum].pnum != -1)
753 remote_regs[num_remote_regs++] = ®s[regnum];
755 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
758 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
760 remote_regs[regnum]->in_g_packet = 1;
761 remote_regs[regnum]->offset = offset;
762 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
768 /* Given the architecture described by GDBARCH, return the remote
769 protocol register's number and the register's offset in the g/G
770 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
771 If the target does not have a mapping for REGNUM, return false,
772 otherwise, return true. */
775 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
776 int *pnum, int *poffset)
778 struct packet_reg *regs;
779 struct cleanup *old_chain;
781 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
783 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
784 old_chain = make_cleanup (xfree, regs);
786 map_regcache_remote_table (gdbarch, regs);
788 *pnum = regs[regnum].pnum;
789 *poffset = regs[regnum].offset;
791 do_cleanups (old_chain);
797 init_remote_state (struct gdbarch *gdbarch)
799 struct remote_state *rs = get_remote_state_raw ();
800 struct remote_arch_state *rsa;
802 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
804 /* Use the architecture to build a regnum<->pnum table, which will be
805 1:1 unless a feature set specifies otherwise. */
806 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
807 gdbarch_num_regs (gdbarch),
810 /* Record the maximum possible size of the g packet - it may turn out
812 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
814 /* Default maximum number of characters in a packet body. Many
815 remote stubs have a hardwired buffer size of 400 bytes
816 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
817 as the maximum packet-size to ensure that the packet and an extra
818 NUL character can always fit in the buffer. This stops GDB
819 trashing stubs that try to squeeze an extra NUL into what is
820 already a full buffer (As of 1999-12-04 that was most stubs). */
821 rsa->remote_packet_size = 400 - 1;
823 /* This one is filled in when a ``g'' packet is received. */
824 rsa->actual_register_packet_size = 0;
826 /* Should rsa->sizeof_g_packet needs more space than the
827 default, adjust the size accordingly. Remember that each byte is
828 encoded as two characters. 32 is the overhead for the packet
829 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
830 (``$NN:G...#NN'') is a better guess, the below has been padded a
832 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
833 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
835 /* Make sure that the packet buffer is plenty big enough for
836 this architecture. */
837 if (rs->buf_size < rsa->remote_packet_size)
839 rs->buf_size = 2 * rsa->remote_packet_size;
840 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
846 /* Return the current allowed size of a remote packet. This is
847 inferred from the current architecture, and should be used to
848 limit the length of outgoing packets. */
850 get_remote_packet_size (void)
852 struct remote_state *rs = get_remote_state ();
853 struct remote_arch_state *rsa = get_remote_arch_state ();
855 if (rs->explicit_packet_size)
856 return rs->explicit_packet_size;
858 return rsa->remote_packet_size;
861 static struct packet_reg *
862 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
864 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
868 struct packet_reg *r = &rsa->regs[regnum];
870 gdb_assert (r->regnum == regnum);
875 static struct packet_reg *
876 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
880 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
882 struct packet_reg *r = &rsa->regs[i];
890 static struct target_ops remote_ops;
892 static struct target_ops extended_remote_ops;
894 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
895 ``forever'' still use the normal timeout mechanism. This is
896 currently used by the ASYNC code to guarentee that target reads
897 during the initial connect always time-out. Once getpkt has been
898 modified to return a timeout indication and, in turn
899 remote_wait()/wait_for_inferior() have gained a timeout parameter
901 static int wait_forever_enabled_p = 1;
903 /* Allow the user to specify what sequence to send to the remote
904 when he requests a program interruption: Although ^C is usually
905 what remote systems expect (this is the default, here), it is
906 sometimes preferable to send a break. On other systems such
907 as the Linux kernel, a break followed by g, which is Magic SysRq g
908 is required in order to interrupt the execution. */
909 const char interrupt_sequence_control_c[] = "Ctrl-C";
910 const char interrupt_sequence_break[] = "BREAK";
911 const char interrupt_sequence_break_g[] = "BREAK-g";
912 static const char *const interrupt_sequence_modes[] =
914 interrupt_sequence_control_c,
915 interrupt_sequence_break,
916 interrupt_sequence_break_g,
919 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
922 show_interrupt_sequence (struct ui_file *file, int from_tty,
923 struct cmd_list_element *c,
926 if (interrupt_sequence_mode == interrupt_sequence_control_c)
927 fprintf_filtered (file,
928 _("Send the ASCII ETX character (Ctrl-c) "
929 "to the remote target to interrupt the "
930 "execution of the program.\n"));
931 else if (interrupt_sequence_mode == interrupt_sequence_break)
932 fprintf_filtered (file,
933 _("send a break signal to the remote target "
934 "to interrupt the execution of the program.\n"));
935 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
936 fprintf_filtered (file,
937 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
938 "the remote target to interrupt the execution "
939 "of Linux kernel.\n"));
941 internal_error (__FILE__, __LINE__,
942 _("Invalid value for interrupt_sequence_mode: %s."),
943 interrupt_sequence_mode);
946 /* This boolean variable specifies whether interrupt_sequence is sent
947 to the remote target when gdb connects to it.
948 This is mostly needed when you debug the Linux kernel: The Linux kernel
949 expects BREAK g which is Magic SysRq g for connecting gdb. */
950 static int interrupt_on_connect = 0;
952 /* This variable is used to implement the "set/show remotebreak" commands.
953 Since these commands are now deprecated in favor of "set/show remote
954 interrupt-sequence", it no longer has any effect on the code. */
955 static int remote_break;
958 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
961 interrupt_sequence_mode = interrupt_sequence_break;
963 interrupt_sequence_mode = interrupt_sequence_control_c;
967 show_remotebreak (struct ui_file *file, int from_tty,
968 struct cmd_list_element *c,
973 /* This variable sets the number of bits in an address that are to be
974 sent in a memory ("M" or "m") packet. Normally, after stripping
975 leading zeros, the entire address would be sent. This variable
976 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
977 initial implementation of remote.c restricted the address sent in
978 memory packets to ``host::sizeof long'' bytes - (typically 32
979 bits). Consequently, for 64 bit targets, the upper 32 bits of an
980 address was never sent. Since fixing this bug may cause a break in
981 some remote targets this variable is principly provided to
982 facilitate backward compatibility. */
984 static unsigned int remote_address_size;
986 /* Temporary to track who currently owns the terminal. See
987 remote_terminal_* for more details. */
989 static int remote_async_terminal_ours_p;
992 /* User configurable variables for the number of characters in a
993 memory read/write packet. MIN (rsa->remote_packet_size,
994 rsa->sizeof_g_packet) is the default. Some targets need smaller
995 values (fifo overruns, et.al.) and some users need larger values
996 (speed up transfers). The variables ``preferred_*'' (the user
997 request), ``current_*'' (what was actually set) and ``forced_*''
998 (Positive - a soft limit, negative - a hard limit). */
1000 struct memory_packet_config
1007 /* The default max memory-write-packet-size. The 16k is historical.
1008 (It came from older GDB's using alloca for buffers and the
1009 knowledge (folklore?) that some hosts don't cope very well with
1010 large alloca calls.) */
1011 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1013 /* The minimum remote packet size for memory transfers. Ensures we
1014 can write at least one byte. */
1015 #define MIN_MEMORY_PACKET_SIZE 20
1017 /* Compute the current size of a read/write packet. Since this makes
1018 use of ``actual_register_packet_size'' the computation is dynamic. */
1021 get_memory_packet_size (struct memory_packet_config *config)
1023 struct remote_state *rs = get_remote_state ();
1024 struct remote_arch_state *rsa = get_remote_arch_state ();
1027 if (config->fixed_p)
1029 if (config->size <= 0)
1030 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1032 what_they_get = config->size;
1036 what_they_get = get_remote_packet_size ();
1037 /* Limit the packet to the size specified by the user. */
1038 if (config->size > 0
1039 && what_they_get > config->size)
1040 what_they_get = config->size;
1042 /* Limit it to the size of the targets ``g'' response unless we have
1043 permission from the stub to use a larger packet size. */
1044 if (rs->explicit_packet_size == 0
1045 && rsa->actual_register_packet_size > 0
1046 && what_they_get > rsa->actual_register_packet_size)
1047 what_they_get = rsa->actual_register_packet_size;
1049 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1050 what_they_get = MIN_MEMORY_PACKET_SIZE;
1052 /* Make sure there is room in the global buffer for this packet
1053 (including its trailing NUL byte). */
1054 if (rs->buf_size < what_they_get + 1)
1056 rs->buf_size = 2 * what_they_get;
1057 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1060 return what_they_get;
1063 /* Update the size of a read/write packet. If they user wants
1064 something really big then do a sanity check. */
1067 set_memory_packet_size (char *args, struct memory_packet_config *config)
1069 int fixed_p = config->fixed_p;
1070 long size = config->size;
1073 error (_("Argument required (integer, `fixed' or `limited')."));
1074 else if (strcmp (args, "hard") == 0
1075 || strcmp (args, "fixed") == 0)
1077 else if (strcmp (args, "soft") == 0
1078 || strcmp (args, "limit") == 0)
1084 size = strtoul (args, &end, 0);
1086 error (_("Invalid %s (bad syntax)."), config->name);
1088 /* Instead of explicitly capping the size of a packet to or
1089 disallowing it, the user is allowed to set the size to
1090 something arbitrarily large. */
1093 /* So that the query shows the correct value. */
1095 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1098 if (fixed_p && !config->fixed_p)
1100 if (! query (_("The target may not be able to correctly handle a %s\n"
1101 "of %ld bytes. Change the packet size? "),
1102 config->name, size))
1103 error (_("Packet size not changed."));
1105 /* Update the config. */
1106 config->fixed_p = fixed_p;
1107 config->size = size;
1111 show_memory_packet_size (struct memory_packet_config *config)
1113 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1114 if (config->fixed_p)
1115 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1116 get_memory_packet_size (config));
1118 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1119 get_memory_packet_size (config));
1122 static struct memory_packet_config memory_write_packet_config =
1124 "memory-write-packet-size",
1128 set_memory_write_packet_size (char *args, int from_tty)
1130 set_memory_packet_size (args, &memory_write_packet_config);
1134 show_memory_write_packet_size (char *args, int from_tty)
1136 show_memory_packet_size (&memory_write_packet_config);
1140 get_memory_write_packet_size (void)
1142 return get_memory_packet_size (&memory_write_packet_config);
1145 static struct memory_packet_config memory_read_packet_config =
1147 "memory-read-packet-size",
1151 set_memory_read_packet_size (char *args, int from_tty)
1153 set_memory_packet_size (args, &memory_read_packet_config);
1157 show_memory_read_packet_size (char *args, int from_tty)
1159 show_memory_packet_size (&memory_read_packet_config);
1163 get_memory_read_packet_size (void)
1165 long size = get_memory_packet_size (&memory_read_packet_config);
1167 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1168 extra buffer size argument before the memory read size can be
1169 increased beyond this. */
1170 if (size > get_remote_packet_size ())
1171 size = get_remote_packet_size ();
1176 /* Generic configuration support for packets the stub optionally
1177 supports. Allows the user to specify the use of the packet as well
1178 as allowing GDB to auto-detect support in the remote stub. */
1182 PACKET_SUPPORT_UNKNOWN = 0,
1187 struct packet_config
1192 /* If auto, GDB auto-detects support for this packet or feature,
1193 either through qSupported, or by trying the packet and looking
1194 at the response. If true, GDB assumes the target supports this
1195 packet. If false, the packet is disabled. Configs that don't
1196 have an associated command always have this set to auto. */
1197 enum auto_boolean detect;
1199 /* Does the target support this packet? */
1200 enum packet_support support;
1203 /* Analyze a packet's return value and update the packet config
1213 static enum packet_support packet_config_support (struct packet_config *config);
1214 static enum packet_support packet_support (int packet);
1217 show_packet_config_cmd (struct packet_config *config)
1219 char *support = "internal-error";
1221 switch (packet_config_support (config))
1224 support = "enabled";
1226 case PACKET_DISABLE:
1227 support = "disabled";
1229 case PACKET_SUPPORT_UNKNOWN:
1230 support = "unknown";
1233 switch (config->detect)
1235 case AUTO_BOOLEAN_AUTO:
1236 printf_filtered (_("Support for the `%s' packet "
1237 "is auto-detected, currently %s.\n"),
1238 config->name, support);
1240 case AUTO_BOOLEAN_TRUE:
1241 case AUTO_BOOLEAN_FALSE:
1242 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1243 config->name, support);
1249 add_packet_config_cmd (struct packet_config *config, const char *name,
1250 const char *title, int legacy)
1256 config->name = name;
1257 config->title = title;
1258 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1260 show_doc = xstrprintf ("Show current use of remote "
1261 "protocol `%s' (%s) packet",
1263 /* set/show TITLE-packet {auto,on,off} */
1264 cmd_name = xstrprintf ("%s-packet", title);
1265 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1266 &config->detect, set_doc,
1267 show_doc, NULL, /* help_doc */
1269 show_remote_protocol_packet_cmd,
1270 &remote_set_cmdlist, &remote_show_cmdlist);
1271 /* The command code copies the documentation strings. */
1274 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1279 legacy_name = xstrprintf ("%s-packet", name);
1280 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1281 &remote_set_cmdlist);
1282 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1283 &remote_show_cmdlist);
1287 static enum packet_result
1288 packet_check_result (const char *buf)
1292 /* The stub recognized the packet request. Check that the
1293 operation succeeded. */
1295 && isxdigit (buf[1]) && isxdigit (buf[2])
1297 /* "Enn" - definitly an error. */
1298 return PACKET_ERROR;
1300 /* Always treat "E." as an error. This will be used for
1301 more verbose error messages, such as E.memtypes. */
1302 if (buf[0] == 'E' && buf[1] == '.')
1303 return PACKET_ERROR;
1305 /* The packet may or may not be OK. Just assume it is. */
1309 /* The stub does not support the packet. */
1310 return PACKET_UNKNOWN;
1313 static enum packet_result
1314 packet_ok (const char *buf, struct packet_config *config)
1316 enum packet_result result;
1318 if (config->detect != AUTO_BOOLEAN_TRUE
1319 && config->support == PACKET_DISABLE)
1320 internal_error (__FILE__, __LINE__,
1321 _("packet_ok: attempt to use a disabled packet"));
1323 result = packet_check_result (buf);
1328 /* The stub recognized the packet request. */
1329 if (config->support == PACKET_SUPPORT_UNKNOWN)
1332 fprintf_unfiltered (gdb_stdlog,
1333 "Packet %s (%s) is supported\n",
1334 config->name, config->title);
1335 config->support = PACKET_ENABLE;
1338 case PACKET_UNKNOWN:
1339 /* The stub does not support the packet. */
1340 if (config->detect == AUTO_BOOLEAN_AUTO
1341 && config->support == PACKET_ENABLE)
1343 /* If the stub previously indicated that the packet was
1344 supported then there is a protocol error. */
1345 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1346 config->name, config->title);
1348 else if (config->detect == AUTO_BOOLEAN_TRUE)
1350 /* The user set it wrong. */
1351 error (_("Enabled packet %s (%s) not recognized by stub"),
1352 config->name, config->title);
1356 fprintf_unfiltered (gdb_stdlog,
1357 "Packet %s (%s) is NOT supported\n",
1358 config->name, config->title);
1359 config->support = PACKET_DISABLE;
1380 PACKET_vFile_pwrite,
1382 PACKET_vFile_unlink,
1383 PACKET_vFile_readlink,
1386 PACKET_qXfer_features,
1387 PACKET_qXfer_exec_file,
1388 PACKET_qXfer_libraries,
1389 PACKET_qXfer_libraries_svr4,
1390 PACKET_qXfer_memory_map,
1391 PACKET_qXfer_spu_read,
1392 PACKET_qXfer_spu_write,
1393 PACKET_qXfer_osdata,
1394 PACKET_qXfer_threads,
1395 PACKET_qXfer_statictrace_read,
1396 PACKET_qXfer_traceframe_info,
1402 PACKET_QPassSignals,
1403 PACKET_QCatchSyscalls,
1404 PACKET_QProgramSignals,
1406 PACKET_qSearch_memory,
1409 PACKET_QStartNoAckMode,
1411 PACKET_qXfer_siginfo_read,
1412 PACKET_qXfer_siginfo_write,
1415 /* Support for conditional tracepoints. */
1416 PACKET_ConditionalTracepoints,
1418 /* Support for target-side breakpoint conditions. */
1419 PACKET_ConditionalBreakpoints,
1421 /* Support for target-side breakpoint commands. */
1422 PACKET_BreakpointCommands,
1424 /* Support for fast tracepoints. */
1425 PACKET_FastTracepoints,
1427 /* Support for static tracepoints. */
1428 PACKET_StaticTracepoints,
1430 /* Support for installing tracepoints while a trace experiment is
1432 PACKET_InstallInTrace,
1436 PACKET_TracepointSource,
1439 PACKET_QDisableRandomization,
1441 PACKET_QTBuffer_size,
1445 PACKET_qXfer_btrace,
1447 /* Support for the QNonStop packet. */
1450 /* Support for the QThreadEvents packet. */
1451 PACKET_QThreadEvents,
1453 /* Support for multi-process extensions. */
1454 PACKET_multiprocess_feature,
1456 /* Support for enabling and disabling tracepoints while a trace
1457 experiment is running. */
1458 PACKET_EnableDisableTracepoints_feature,
1460 /* Support for collecting strings using the tracenz bytecode. */
1461 PACKET_tracenz_feature,
1463 /* Support for continuing to run a trace experiment while GDB is
1465 PACKET_DisconnectedTracing_feature,
1467 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1468 PACKET_augmented_libraries_svr4_read_feature,
1470 /* Support for the qXfer:btrace-conf:read packet. */
1471 PACKET_qXfer_btrace_conf,
1473 /* Support for the Qbtrace-conf:bts:size packet. */
1474 PACKET_Qbtrace_conf_bts_size,
1476 /* Support for swbreak+ feature. */
1477 PACKET_swbreak_feature,
1479 /* Support for hwbreak+ feature. */
1480 PACKET_hwbreak_feature,
1482 /* Support for fork events. */
1483 PACKET_fork_event_feature,
1485 /* Support for vfork events. */
1486 PACKET_vfork_event_feature,
1488 /* Support for the Qbtrace-conf:pt:size packet. */
1489 PACKET_Qbtrace_conf_pt_size,
1491 /* Support for exec events. */
1492 PACKET_exec_event_feature,
1494 /* Support for query supported vCont actions. */
1495 PACKET_vContSupported,
1497 /* Support remote CTRL-C. */
1500 /* Support TARGET_WAITKIND_NO_RESUMED. */
1506 static struct packet_config remote_protocol_packets[PACKET_MAX];
1508 /* Returns the packet's corresponding "set remote foo-packet" command
1509 state. See struct packet_config for more details. */
1511 static enum auto_boolean
1512 packet_set_cmd_state (int packet)
1514 return remote_protocol_packets[packet].detect;
1517 /* Returns whether a given packet or feature is supported. This takes
1518 into account the state of the corresponding "set remote foo-packet"
1519 command, which may be used to bypass auto-detection. */
1521 static enum packet_support
1522 packet_config_support (struct packet_config *config)
1524 switch (config->detect)
1526 case AUTO_BOOLEAN_TRUE:
1527 return PACKET_ENABLE;
1528 case AUTO_BOOLEAN_FALSE:
1529 return PACKET_DISABLE;
1530 case AUTO_BOOLEAN_AUTO:
1532 struct remote_state *rs = get_remote_state ();
1534 if (rs->unknown_v_replies_ok && config->name != NULL
1535 && config->name[0] == 'v')
1536 return PACKET_DISABLE;
1538 return config->support;
1540 gdb_assert_not_reached (_("bad switch"));
1544 /* Same as packet_config_support, but takes the packet's enum value as
1547 static enum packet_support
1548 packet_support (int packet)
1550 struct packet_config *config = &remote_protocol_packets[packet];
1552 return packet_config_support (config);
1556 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1557 struct cmd_list_element *c,
1560 struct packet_config *packet;
1562 for (packet = remote_protocol_packets;
1563 packet < &remote_protocol_packets[PACKET_MAX];
1566 if (&packet->detect == c->var)
1568 show_packet_config_cmd (packet);
1572 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1576 /* Should we try one of the 'Z' requests? */
1580 Z_PACKET_SOFTWARE_BP,
1581 Z_PACKET_HARDWARE_BP,
1588 /* For compatibility with older distributions. Provide a ``set remote
1589 Z-packet ...'' command that updates all the Z packet types. */
1591 static enum auto_boolean remote_Z_packet_detect;
1594 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1595 struct cmd_list_element *c)
1599 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1600 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1604 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1605 struct cmd_list_element *c,
1610 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1612 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1616 /* Returns true if the multi-process extensions are in effect. */
1619 remote_multi_process_p (struct remote_state *rs)
1621 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1624 /* Returns true if fork events are supported. */
1627 remote_fork_event_p (struct remote_state *rs)
1629 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1632 /* Returns true if vfork events are supported. */
1635 remote_vfork_event_p (struct remote_state *rs)
1637 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1640 /* Returns true if exec events are supported. */
1643 remote_exec_event_p (struct remote_state *rs)
1645 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1648 /* Insert fork catchpoint target routine. If fork events are enabled
1649 then return success, nothing more to do. */
1652 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1654 struct remote_state *rs = get_remote_state ();
1656 return !remote_fork_event_p (rs);
1659 /* Remove fork catchpoint target routine. Nothing to do, just
1663 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1668 /* Insert vfork catchpoint target routine. If vfork events are enabled
1669 then return success, nothing more to do. */
1672 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1674 struct remote_state *rs = get_remote_state ();
1676 return !remote_vfork_event_p (rs);
1679 /* Remove vfork catchpoint target routine. Nothing to do, just
1683 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1688 /* Insert exec catchpoint target routine. If exec events are
1689 enabled, just return success. */
1692 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1694 struct remote_state *rs = get_remote_state ();
1696 return !remote_exec_event_p (rs);
1699 /* Remove exec catchpoint target routine. Nothing to do, just
1703 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1708 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1709 static struct async_signal_handler *async_sigint_remote_twice_token;
1710 static struct async_signal_handler *async_sigint_remote_token;
1713 /* Asynchronous signal handle registered as event loop source for
1714 when we have pending events ready to be passed to the core. */
1716 static struct async_event_handler *remote_async_inferior_event_token;
1720 static ptid_t magic_null_ptid;
1721 static ptid_t not_sent_ptid;
1722 static ptid_t any_thread_ptid;
1724 /* Find out if the stub attached to PID (and hence GDB should offer to
1725 detach instead of killing it when bailing out). */
1728 remote_query_attached (int pid)
1730 struct remote_state *rs = get_remote_state ();
1731 size_t size = get_remote_packet_size ();
1733 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1736 if (remote_multi_process_p (rs))
1737 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1739 xsnprintf (rs->buf, size, "qAttached");
1742 getpkt (&rs->buf, &rs->buf_size, 0);
1744 switch (packet_ok (rs->buf,
1745 &remote_protocol_packets[PACKET_qAttached]))
1748 if (strcmp (rs->buf, "1") == 0)
1752 warning (_("Remote failure reply: %s"), rs->buf);
1754 case PACKET_UNKNOWN:
1761 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1762 has been invented by GDB, instead of reported by the target. Since
1763 we can be connected to a remote system before before knowing about
1764 any inferior, mark the target with execution when we find the first
1765 inferior. If ATTACHED is 1, then we had just attached to this
1766 inferior. If it is 0, then we just created this inferior. If it
1767 is -1, then try querying the remote stub to find out if it had
1768 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1769 attempt to open this inferior's executable as the main executable
1770 if no main executable is open already. */
1772 static struct inferior *
1773 remote_add_inferior (int fake_pid_p, int pid, int attached,
1776 struct inferior *inf;
1778 /* Check whether this process we're learning about is to be
1779 considered attached, or if is to be considered to have been
1780 spawned by the stub. */
1782 attached = remote_query_attached (pid);
1784 if (gdbarch_has_global_solist (target_gdbarch ()))
1786 /* If the target shares code across all inferiors, then every
1787 attach adds a new inferior. */
1788 inf = add_inferior (pid);
1790 /* ... and every inferior is bound to the same program space.
1791 However, each inferior may still have its own address
1793 inf->aspace = maybe_new_address_space ();
1794 inf->pspace = current_program_space;
1798 /* In the traditional debugging scenario, there's a 1-1 match
1799 between program/address spaces. We simply bind the inferior
1800 to the program space's address space. */
1801 inf = current_inferior ();
1802 inferior_appeared (inf, pid);
1805 inf->attach_flag = attached;
1806 inf->fake_pid_p = fake_pid_p;
1808 /* If no main executable is currently open then attempt to
1809 open the file that was executed to create this inferior. */
1810 if (try_open_exec && get_exec_file (0) == NULL)
1811 exec_file_locate_attach (pid, 1);
1816 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1817 according to RUNNING. */
1820 remote_add_thread (ptid_t ptid, int running, int executing)
1822 struct remote_state *rs = get_remote_state ();
1824 /* GDB historically didn't pull threads in the initial connection
1825 setup. If the remote target doesn't even have a concept of
1826 threads (e.g., a bare-metal target), even if internally we
1827 consider that a single-threaded target, mentioning a new thread
1828 might be confusing to the user. Be silent then, preserving the
1829 age old behavior. */
1830 if (rs->starting_up)
1831 add_thread_silent (ptid);
1835 set_executing (ptid, executing);
1836 set_running (ptid, running);
1839 /* Come here when we learn about a thread id from the remote target.
1840 It may be the first time we hear about such thread, so take the
1841 opportunity to add it to GDB's thread list. In case this is the
1842 first time we're noticing its corresponding inferior, add it to
1843 GDB's inferior list as well. EXECUTING indicates whether the
1844 thread is (internally) executing or stopped. */
1847 remote_notice_new_inferior (ptid_t currthread, int executing)
1849 /* In non-stop mode, we assume new found threads are (externally)
1850 running until proven otherwise with a stop reply. In all-stop,
1851 we can only get here if all threads are stopped. */
1852 int running = target_is_non_stop_p () ? 1 : 0;
1854 /* If this is a new thread, add it to GDB's thread list.
1855 If we leave it up to WFI to do this, bad things will happen. */
1857 if (in_thread_list (currthread) && is_exited (currthread))
1859 /* We're seeing an event on a thread id we knew had exited.
1860 This has to be a new thread reusing the old id. Add it. */
1861 remote_add_thread (currthread, running, executing);
1865 if (!in_thread_list (currthread))
1867 struct inferior *inf = NULL;
1868 int pid = ptid_get_pid (currthread);
1870 if (ptid_is_pid (inferior_ptid)
1871 && pid == ptid_get_pid (inferior_ptid))
1873 /* inferior_ptid has no thread member yet. This can happen
1874 with the vAttach -> remote_wait,"TAAthread:" path if the
1875 stub doesn't support qC. This is the first stop reported
1876 after an attach, so this is the main thread. Update the
1877 ptid in the thread list. */
1878 if (in_thread_list (pid_to_ptid (pid)))
1879 thread_change_ptid (inferior_ptid, currthread);
1882 remote_add_thread (currthread, running, executing);
1883 inferior_ptid = currthread;
1888 if (ptid_equal (magic_null_ptid, inferior_ptid))
1890 /* inferior_ptid is not set yet. This can happen with the
1891 vRun -> remote_wait,"TAAthread:" path if the stub
1892 doesn't support qC. This is the first stop reported
1893 after an attach, so this is the main thread. Update the
1894 ptid in the thread list. */
1895 thread_change_ptid (inferior_ptid, currthread);
1899 /* When connecting to a target remote, or to a target
1900 extended-remote which already was debugging an inferior, we
1901 may not know about it yet. Add it before adding its child
1902 thread, so notifications are emitted in a sensible order. */
1903 if (!in_inferior_list (ptid_get_pid (currthread)))
1905 struct remote_state *rs = get_remote_state ();
1906 int fake_pid_p = !remote_multi_process_p (rs);
1908 inf = remote_add_inferior (fake_pid_p,
1909 ptid_get_pid (currthread), -1, 1);
1912 /* This is really a new thread. Add it. */
1913 remote_add_thread (currthread, running, executing);
1915 /* If we found a new inferior, let the common code do whatever
1916 it needs to with it (e.g., read shared libraries, insert
1917 breakpoints), unless we're just setting up an all-stop
1921 struct remote_state *rs = get_remote_state ();
1923 if (!rs->starting_up)
1924 notice_new_inferior (currthread, executing, 0);
1929 /* Return the private thread data, creating it if necessary. */
1931 static struct private_thread_info *
1932 demand_private_info (ptid_t ptid)
1934 struct thread_info *info = find_thread_ptid (ptid);
1940 info->priv = XNEW (struct private_thread_info);
1941 info->private_dtor = free_private_thread_info;
1942 info->priv->core = -1;
1943 info->priv->extra = NULL;
1944 info->priv->name = NULL;
1950 /* Call this function as a result of
1951 1) A halt indication (T packet) containing a thread id
1952 2) A direct query of currthread
1953 3) Successful execution of set thread */
1956 record_currthread (struct remote_state *rs, ptid_t currthread)
1958 rs->general_thread = currthread;
1961 /* If 'QPassSignals' is supported, tell the remote stub what signals
1962 it can simply pass through to the inferior without reporting. */
1965 remote_pass_signals (struct target_ops *self,
1966 int numsigs, unsigned char *pass_signals)
1968 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1970 char *pass_packet, *p;
1972 struct remote_state *rs = get_remote_state ();
1974 gdb_assert (numsigs < 256);
1975 for (i = 0; i < numsigs; i++)
1977 if (pass_signals[i])
1980 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1981 strcpy (pass_packet, "QPassSignals:");
1982 p = pass_packet + strlen (pass_packet);
1983 for (i = 0; i < numsigs; i++)
1985 if (pass_signals[i])
1988 *p++ = tohex (i >> 4);
1989 *p++ = tohex (i & 15);
1998 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2000 putpkt (pass_packet);
2001 getpkt (&rs->buf, &rs->buf_size, 0);
2002 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2003 if (rs->last_pass_packet)
2004 xfree (rs->last_pass_packet);
2005 rs->last_pass_packet = pass_packet;
2008 xfree (pass_packet);
2012 /* If 'QCatchSyscalls' is supported, tell the remote stub
2013 to report syscalls to GDB. */
2016 remote_set_syscall_catchpoint (struct target_ops *self,
2017 int pid, int needed, int any_count,
2018 int table_size, int *table)
2021 enum packet_result result;
2024 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2026 /* Not supported. */
2030 if (needed && !any_count)
2034 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2035 for (i = 0; i < table_size; i++)
2044 fprintf_unfiltered (gdb_stdlog,
2045 "remote_set_syscall_catchpoint "
2046 "pid %d needed %d any_count %d n_sysno %d\n",
2047 pid, needed, any_count, n_sysno);
2052 /* Prepare a packet with the sysno list, assuming max 8+1
2053 characters for a sysno. If the resulting packet size is too
2054 big, fallback on the non-selective packet. */
2055 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2057 catch_packet = (char *) xmalloc (maxpktsz);
2058 strcpy (catch_packet, "QCatchSyscalls:1");
2067 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2068 for (i = 0; i < table_size; i++)
2071 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2074 if (strlen (catch_packet) > get_remote_packet_size ())
2076 /* catch_packet too big. Fallback to less efficient
2077 non selective mode, with GDB doing the filtering. */
2078 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2082 catch_packet = xstrdup ("QCatchSyscalls:0");
2085 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2086 struct remote_state *rs = get_remote_state ();
2088 putpkt (catch_packet);
2089 getpkt (&rs->buf, &rs->buf_size, 0);
2090 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2091 do_cleanups (old_chain);
2092 if (result == PACKET_OK)
2099 /* If 'QProgramSignals' is supported, tell the remote stub what
2100 signals it should pass through to the inferior when detaching. */
2103 remote_program_signals (struct target_ops *self,
2104 int numsigs, unsigned char *signals)
2106 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2110 struct remote_state *rs = get_remote_state ();
2112 gdb_assert (numsigs < 256);
2113 for (i = 0; i < numsigs; i++)
2118 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2119 strcpy (packet, "QProgramSignals:");
2120 p = packet + strlen (packet);
2121 for (i = 0; i < numsigs; i++)
2123 if (signal_pass_state (i))
2126 *p++ = tohex (i >> 4);
2127 *p++ = tohex (i & 15);
2136 if (!rs->last_program_signals_packet
2137 || strcmp (rs->last_program_signals_packet, packet) != 0)
2140 getpkt (&rs->buf, &rs->buf_size, 0);
2141 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2142 xfree (rs->last_program_signals_packet);
2143 rs->last_program_signals_packet = packet;
2150 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2151 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2152 thread. If GEN is set, set the general thread, if not, then set
2153 the step/continue thread. */
2155 set_thread (struct ptid ptid, int gen)
2157 struct remote_state *rs = get_remote_state ();
2158 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2159 char *buf = rs->buf;
2160 char *endbuf = rs->buf + get_remote_packet_size ();
2162 if (ptid_equal (state, ptid))
2166 *buf++ = gen ? 'g' : 'c';
2167 if (ptid_equal (ptid, magic_null_ptid))
2168 xsnprintf (buf, endbuf - buf, "0");
2169 else if (ptid_equal (ptid, any_thread_ptid))
2170 xsnprintf (buf, endbuf - buf, "0");
2171 else if (ptid_equal (ptid, minus_one_ptid))
2172 xsnprintf (buf, endbuf - buf, "-1");
2174 write_ptid (buf, endbuf, ptid);
2176 getpkt (&rs->buf, &rs->buf_size, 0);
2178 rs->general_thread = ptid;
2180 rs->continue_thread = ptid;
2184 set_general_thread (struct ptid ptid)
2186 set_thread (ptid, 1);
2190 set_continue_thread (struct ptid ptid)
2192 set_thread (ptid, 0);
2195 /* Change the remote current process. Which thread within the process
2196 ends up selected isn't important, as long as it is the same process
2197 as what INFERIOR_PTID points to.
2199 This comes from that fact that there is no explicit notion of
2200 "selected process" in the protocol. The selected process for
2201 general operations is the process the selected general thread
2205 set_general_process (void)
2207 struct remote_state *rs = get_remote_state ();
2209 /* If the remote can't handle multiple processes, don't bother. */
2210 if (!remote_multi_process_p (rs))
2213 /* We only need to change the remote current thread if it's pointing
2214 at some other process. */
2215 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2216 set_general_thread (inferior_ptid);
2220 /* Return nonzero if this is the main thread that we made up ourselves
2221 to model non-threaded targets as single-threaded. */
2224 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2226 if (ptid_equal (ptid, magic_null_ptid))
2227 /* The main thread is always alive. */
2230 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2231 /* The main thread is always alive. This can happen after a
2232 vAttach, if the remote side doesn't support
2239 /* Return nonzero if the thread PTID is still alive on the remote
2243 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2245 struct remote_state *rs = get_remote_state ();
2248 /* Check if this is a thread that we made up ourselves to model
2249 non-threaded targets as single-threaded. */
2250 if (remote_thread_always_alive (ops, ptid))
2254 endp = rs->buf + get_remote_packet_size ();
2257 write_ptid (p, endp, ptid);
2260 getpkt (&rs->buf, &rs->buf_size, 0);
2261 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2264 /* Return a pointer to a thread name if we know it and NULL otherwise.
2265 The thread_info object owns the memory for the name. */
2268 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2270 if (info->priv != NULL)
2271 return info->priv->name;
2276 /* About these extended threadlist and threadinfo packets. They are
2277 variable length packets but, the fields within them are often fixed
2278 length. They are redundent enough to send over UDP as is the
2279 remote protocol in general. There is a matching unit test module
2282 /* WARNING: This threadref data structure comes from the remote O.S.,
2283 libstub protocol encoding, and remote.c. It is not particularly
2286 /* Right now, the internal structure is int. We want it to be bigger.
2287 Plan to fix this. */
2289 typedef int gdb_threadref; /* Internal GDB thread reference. */
2291 /* gdb_ext_thread_info is an internal GDB data structure which is
2292 equivalent to the reply of the remote threadinfo packet. */
2294 struct gdb_ext_thread_info
2296 threadref threadid; /* External form of thread reference. */
2297 int active; /* Has state interesting to GDB?
2299 char display[256]; /* Brief state display, name,
2300 blocked/suspended. */
2301 char shortname[32]; /* To be used to name threads. */
2302 char more_display[256]; /* Long info, statistics, queue depth,
2306 /* The volume of remote transfers can be limited by submitting
2307 a mask containing bits specifying the desired information.
2308 Use a union of these values as the 'selection' parameter to
2309 get_thread_info. FIXME: Make these TAG names more thread specific. */
2311 #define TAG_THREADID 1
2312 #define TAG_EXISTS 2
2313 #define TAG_DISPLAY 4
2314 #define TAG_THREADNAME 8
2315 #define TAG_MOREDISPLAY 16
2317 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2319 static char *unpack_nibble (char *buf, int *val);
2321 static char *unpack_byte (char *buf, int *value);
2323 static char *pack_int (char *buf, int value);
2325 static char *unpack_int (char *buf, int *value);
2327 static char *unpack_string (char *src, char *dest, int length);
2329 static char *pack_threadid (char *pkt, threadref *id);
2331 static char *unpack_threadid (char *inbuf, threadref *id);
2333 void int_to_threadref (threadref *id, int value);
2335 static int threadref_to_int (threadref *ref);
2337 static void copy_threadref (threadref *dest, threadref *src);
2339 static int threadmatch (threadref *dest, threadref *src);
2341 static char *pack_threadinfo_request (char *pkt, int mode,
2344 static int remote_unpack_thread_info_response (char *pkt,
2345 threadref *expectedref,
2346 struct gdb_ext_thread_info
2350 static int remote_get_threadinfo (threadref *threadid,
2351 int fieldset, /*TAG mask */
2352 struct gdb_ext_thread_info *info);
2354 static char *pack_threadlist_request (char *pkt, int startflag,
2356 threadref *nextthread);
2358 static int parse_threadlist_response (char *pkt,
2360 threadref *original_echo,
2361 threadref *resultlist,
2364 static int remote_get_threadlist (int startflag,
2365 threadref *nextthread,
2369 threadref *threadlist);
2371 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2373 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2374 void *context, int looplimit);
2376 static int remote_newthread_step (threadref *ref, void *context);
2379 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2380 buffer we're allowed to write to. Returns
2381 BUF+CHARACTERS_WRITTEN. */
2384 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2387 struct remote_state *rs = get_remote_state ();
2389 if (remote_multi_process_p (rs))
2391 pid = ptid_get_pid (ptid);
2393 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2395 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2397 tid = ptid_get_lwp (ptid);
2399 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2401 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2406 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2407 passed the last parsed char. Returns null_ptid on error. */
2410 read_ptid (char *buf, char **obuf)
2414 ULONGEST pid = 0, tid = 0;
2418 /* Multi-process ptid. */
2419 pp = unpack_varlen_hex (p + 1, &pid);
2421 error (_("invalid remote ptid: %s"), p);
2424 pp = unpack_varlen_hex (p + 1, &tid);
2427 return ptid_build (pid, tid, 0);
2430 /* No multi-process. Just a tid. */
2431 pp = unpack_varlen_hex (p, &tid);
2433 /* Return null_ptid when no thread id is found. */
2441 /* Since the stub is not sending a process id, then default to
2442 what's in inferior_ptid, unless it's null at this point. If so,
2443 then since there's no way to know the pid of the reported
2444 threads, use the magic number. */
2445 if (ptid_equal (inferior_ptid, null_ptid))
2446 pid = ptid_get_pid (magic_null_ptid);
2448 pid = ptid_get_pid (inferior_ptid);
2452 return ptid_build (pid, tid, 0);
2458 if (ch >= 'a' && ch <= 'f')
2459 return ch - 'a' + 10;
2460 if (ch >= '0' && ch <= '9')
2462 if (ch >= 'A' && ch <= 'F')
2463 return ch - 'A' + 10;
2468 stub_unpack_int (char *buff, int fieldlength)
2475 nibble = stubhex (*buff++);
2479 retval = retval << 4;
2485 unpack_nibble (char *buf, int *val)
2487 *val = fromhex (*buf++);
2492 unpack_byte (char *buf, int *value)
2494 *value = stub_unpack_int (buf, 2);
2499 pack_int (char *buf, int value)
2501 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2502 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2503 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2504 buf = pack_hex_byte (buf, (value & 0xff));
2509 unpack_int (char *buf, int *value)
2511 *value = stub_unpack_int (buf, 8);
2515 #if 0 /* Currently unused, uncomment when needed. */
2516 static char *pack_string (char *pkt, char *string);
2519 pack_string (char *pkt, char *string)
2524 len = strlen (string);
2526 len = 200; /* Bigger than most GDB packets, junk??? */
2527 pkt = pack_hex_byte (pkt, len);
2531 if ((ch == '\0') || (ch == '#'))
2532 ch = '*'; /* Protect encapsulation. */
2537 #endif /* 0 (unused) */
2540 unpack_string (char *src, char *dest, int length)
2549 pack_threadid (char *pkt, threadref *id)
2552 unsigned char *altid;
2554 altid = (unsigned char *) id;
2555 limit = pkt + BUF_THREAD_ID_SIZE;
2557 pkt = pack_hex_byte (pkt, *altid++);
2563 unpack_threadid (char *inbuf, threadref *id)
2566 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2569 altref = (char *) id;
2571 while (inbuf < limit)
2573 x = stubhex (*inbuf++);
2574 y = stubhex (*inbuf++);
2575 *altref++ = (x << 4) | y;
2580 /* Externally, threadrefs are 64 bits but internally, they are still
2581 ints. This is due to a mismatch of specifications. We would like
2582 to use 64bit thread references internally. This is an adapter
2586 int_to_threadref (threadref *id, int value)
2588 unsigned char *scan;
2590 scan = (unsigned char *) id;
2596 *scan++ = (value >> 24) & 0xff;
2597 *scan++ = (value >> 16) & 0xff;
2598 *scan++ = (value >> 8) & 0xff;
2599 *scan++ = (value & 0xff);
2603 threadref_to_int (threadref *ref)
2606 unsigned char *scan;
2612 value = (value << 8) | ((*scan++) & 0xff);
2617 copy_threadref (threadref *dest, threadref *src)
2620 unsigned char *csrc, *cdest;
2622 csrc = (unsigned char *) src;
2623 cdest = (unsigned char *) dest;
2630 threadmatch (threadref *dest, threadref *src)
2632 /* Things are broken right now, so just assume we got a match. */
2634 unsigned char *srcp, *destp;
2636 srcp = (char *) src;
2637 destp = (char *) dest;
2641 result &= (*srcp++ == *destp++) ? 1 : 0;
2648 threadid:1, # always request threadid
2655 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2658 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2660 *pkt++ = 'q'; /* Info Query */
2661 *pkt++ = 'P'; /* process or thread info */
2662 pkt = pack_int (pkt, mode); /* mode */
2663 pkt = pack_threadid (pkt, id); /* threadid */
2664 *pkt = '\0'; /* terminate */
2668 /* These values tag the fields in a thread info response packet. */
2669 /* Tagging the fields allows us to request specific fields and to
2670 add more fields as time goes by. */
2672 #define TAG_THREADID 1 /* Echo the thread identifier. */
2673 #define TAG_EXISTS 2 /* Is this process defined enough to
2674 fetch registers and its stack? */
2675 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2676 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2677 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2681 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2682 struct gdb_ext_thread_info *info)
2684 struct remote_state *rs = get_remote_state ();
2688 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2691 /* info->threadid = 0; FIXME: implement zero_threadref. */
2693 info->display[0] = '\0';
2694 info->shortname[0] = '\0';
2695 info->more_display[0] = '\0';
2697 /* Assume the characters indicating the packet type have been
2699 pkt = unpack_int (pkt, &mask); /* arg mask */
2700 pkt = unpack_threadid (pkt, &ref);
2703 warning (_("Incomplete response to threadinfo request."));
2704 if (!threadmatch (&ref, expectedref))
2705 { /* This is an answer to a different request. */
2706 warning (_("ERROR RMT Thread info mismatch."));
2709 copy_threadref (&info->threadid, &ref);
2711 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2713 /* Packets are terminated with nulls. */
2714 while ((pkt < limit) && mask && *pkt)
2716 pkt = unpack_int (pkt, &tag); /* tag */
2717 pkt = unpack_byte (pkt, &length); /* length */
2718 if (!(tag & mask)) /* Tags out of synch with mask. */
2720 warning (_("ERROR RMT: threadinfo tag mismatch."));
2724 if (tag == TAG_THREADID)
2728 warning (_("ERROR RMT: length of threadid is not 16."));
2732 pkt = unpack_threadid (pkt, &ref);
2733 mask = mask & ~TAG_THREADID;
2736 if (tag == TAG_EXISTS)
2738 info->active = stub_unpack_int (pkt, length);
2740 mask = mask & ~(TAG_EXISTS);
2743 warning (_("ERROR RMT: 'exists' length too long."));
2749 if (tag == TAG_THREADNAME)
2751 pkt = unpack_string (pkt, &info->shortname[0], length);
2752 mask = mask & ~TAG_THREADNAME;
2755 if (tag == TAG_DISPLAY)
2757 pkt = unpack_string (pkt, &info->display[0], length);
2758 mask = mask & ~TAG_DISPLAY;
2761 if (tag == TAG_MOREDISPLAY)
2763 pkt = unpack_string (pkt, &info->more_display[0], length);
2764 mask = mask & ~TAG_MOREDISPLAY;
2767 warning (_("ERROR RMT: unknown thread info tag."));
2768 break; /* Not a tag we know about. */
2774 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2775 struct gdb_ext_thread_info *info)
2777 struct remote_state *rs = get_remote_state ();
2780 pack_threadinfo_request (rs->buf, fieldset, threadid);
2782 getpkt (&rs->buf, &rs->buf_size, 0);
2784 if (rs->buf[0] == '\0')
2787 result = remote_unpack_thread_info_response (rs->buf + 2,
2792 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2795 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2796 threadref *nextthread)
2798 *pkt++ = 'q'; /* info query packet */
2799 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2800 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2801 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2802 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2807 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2810 parse_threadlist_response (char *pkt, int result_limit,
2811 threadref *original_echo, threadref *resultlist,
2814 struct remote_state *rs = get_remote_state ();
2816 int count, resultcount, done;
2819 /* Assume the 'q' and 'M chars have been stripped. */
2820 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2821 /* done parse past here */
2822 pkt = unpack_byte (pkt, &count); /* count field */
2823 pkt = unpack_nibble (pkt, &done);
2824 /* The first threadid is the argument threadid. */
2825 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2826 while ((count-- > 0) && (pkt < limit))
2828 pkt = unpack_threadid (pkt, resultlist++);
2829 if (resultcount++ >= result_limit)
2837 /* Fetch the next batch of threads from the remote. Returns -1 if the
2838 qL packet is not supported, 0 on error and 1 on success. */
2841 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2842 int *done, int *result_count, threadref *threadlist)
2844 struct remote_state *rs = get_remote_state ();
2847 /* Trancate result limit to be smaller than the packet size. */
2848 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2849 >= get_remote_packet_size ())
2850 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2852 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2854 getpkt (&rs->buf, &rs->buf_size, 0);
2855 if (*rs->buf == '\0')
2857 /* Packet not supported. */
2862 parse_threadlist_response (rs->buf + 2, result_limit,
2863 &rs->echo_nextthread, threadlist, done);
2865 if (!threadmatch (&rs->echo_nextthread, nextthread))
2867 /* FIXME: This is a good reason to drop the packet. */
2868 /* Possably, there is a duplicate response. */
2870 retransmit immediatly - race conditions
2871 retransmit after timeout - yes
2873 wait for packet, then exit
2875 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2876 return 0; /* I choose simply exiting. */
2878 if (*result_count <= 0)
2882 warning (_("RMT ERROR : failed to get remote thread list."));
2885 return result; /* break; */
2887 if (*result_count > result_limit)
2890 warning (_("RMT ERROR: threadlist response longer than requested."));
2896 /* Fetch the list of remote threads, with the qL packet, and call
2897 STEPFUNCTION for each thread found. Stops iterating and returns 1
2898 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2899 STEPFUNCTION returns false. If the packet is not supported,
2903 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2906 struct remote_state *rs = get_remote_state ();
2907 int done, i, result_count;
2915 if (loopcount++ > looplimit)
2918 warning (_("Remote fetch threadlist -infinite loop-."));
2921 result = remote_get_threadlist (startflag, &rs->nextthread,
2922 MAXTHREADLISTRESULTS,
2923 &done, &result_count,
2924 rs->resultthreadlist);
2927 /* Clear for later iterations. */
2929 /* Setup to resume next batch of thread references, set nextthread. */
2930 if (result_count >= 1)
2931 copy_threadref (&rs->nextthread,
2932 &rs->resultthreadlist[result_count - 1]);
2934 while (result_count--)
2936 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2946 /* A thread found on the remote target. */
2948 typedef struct thread_item
2950 /* The thread's PTID. */
2953 /* The thread's extra info. May be NULL. */
2956 /* The thread's name. May be NULL. */
2959 /* The core the thread was running on. -1 if not known. */
2962 DEF_VEC_O(thread_item_t);
2964 /* Context passed around to the various methods listing remote
2965 threads. As new threads are found, they're added to the ITEMS
2968 struct threads_listing_context
2970 /* The threads found on the remote target. */
2971 VEC (thread_item_t) *items;
2974 /* Discard the contents of the constructed thread listing context. */
2977 clear_threads_listing_context (void *p)
2979 struct threads_listing_context *context
2980 = (struct threads_listing_context *) p;
2982 struct thread_item *item;
2984 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2986 xfree (item->extra);
2990 VEC_free (thread_item_t, context->items);
2993 /* Remove the thread specified as the related_pid field of WS
2994 from the CONTEXT list. */
2997 threads_listing_context_remove (struct target_waitstatus *ws,
2998 struct threads_listing_context *context)
3000 struct thread_item *item;
3002 ptid_t child_ptid = ws->value.related_pid;
3004 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3006 if (ptid_equal (item->ptid, child_ptid))
3008 VEC_ordered_remove (thread_item_t, context->items, i);
3015 remote_newthread_step (threadref *ref, void *data)
3017 struct threads_listing_context *context
3018 = (struct threads_listing_context *) data;
3019 struct thread_item item;
3020 int pid = ptid_get_pid (inferior_ptid);
3022 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3027 VEC_safe_push (thread_item_t, context->items, &item);
3029 return 1; /* continue iterator */
3032 #define CRAZY_MAX_THREADS 1000
3035 remote_current_thread (ptid_t oldpid)
3037 struct remote_state *rs = get_remote_state ();
3040 getpkt (&rs->buf, &rs->buf_size, 0);
3041 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3046 result = read_ptid (&rs->buf[2], &obuf);
3047 if (*obuf != '\0' && remote_debug)
3048 fprintf_unfiltered (gdb_stdlog,
3049 "warning: garbage in qC reply\n");
3057 /* List remote threads using the deprecated qL packet. */
3060 remote_get_threads_with_ql (struct target_ops *ops,
3061 struct threads_listing_context *context)
3063 if (remote_threadlist_iterator (remote_newthread_step, context,
3064 CRAZY_MAX_THREADS) >= 0)
3070 #if defined(HAVE_LIBEXPAT)
3073 start_thread (struct gdb_xml_parser *parser,
3074 const struct gdb_xml_element *element,
3075 void *user_data, VEC(gdb_xml_value_s) *attributes)
3077 struct threads_listing_context *data
3078 = (struct threads_listing_context *) user_data;
3080 struct thread_item item;
3082 struct gdb_xml_value *attr;
3084 id = (char *) xml_find_attribute (attributes, "id")->value;
3085 item.ptid = read_ptid (id, NULL);
3087 attr = xml_find_attribute (attributes, "core");
3089 item.core = *(ULONGEST *) attr->value;
3093 attr = xml_find_attribute (attributes, "name");
3094 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3098 VEC_safe_push (thread_item_t, data->items, &item);
3102 end_thread (struct gdb_xml_parser *parser,
3103 const struct gdb_xml_element *element,
3104 void *user_data, const char *body_text)
3106 struct threads_listing_context *data
3107 = (struct threads_listing_context *) user_data;
3109 if (body_text && *body_text)
3110 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3113 const struct gdb_xml_attribute thread_attributes[] = {
3114 { "id", GDB_XML_AF_NONE, NULL, NULL },
3115 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3116 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3117 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3120 const struct gdb_xml_element thread_children[] = {
3121 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3124 const struct gdb_xml_element threads_children[] = {
3125 { "thread", thread_attributes, thread_children,
3126 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3127 start_thread, end_thread },
3128 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3131 const struct gdb_xml_element threads_elements[] = {
3132 { "threads", NULL, threads_children,
3133 GDB_XML_EF_NONE, NULL, NULL },
3134 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3139 /* List remote threads using qXfer:threads:read. */
3142 remote_get_threads_with_qxfer (struct target_ops *ops,
3143 struct threads_listing_context *context)
3145 #if defined(HAVE_LIBEXPAT)
3146 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3148 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3149 struct cleanup *back_to = make_cleanup (xfree, xml);
3151 if (xml != NULL && *xml != '\0')
3153 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3154 threads_elements, xml, context);
3157 do_cleanups (back_to);
3165 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3168 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3169 struct threads_listing_context *context)
3171 struct remote_state *rs = get_remote_state ();
3173 if (rs->use_threadinfo_query)
3177 putpkt ("qfThreadInfo");
3178 getpkt (&rs->buf, &rs->buf_size, 0);
3180 if (bufp[0] != '\0') /* q packet recognized */
3182 while (*bufp++ == 'm') /* reply contains one or more TID */
3186 struct thread_item item;
3188 item.ptid = read_ptid (bufp, &bufp);
3193 VEC_safe_push (thread_item_t, context->items, &item);
3195 while (*bufp++ == ','); /* comma-separated list */
3196 putpkt ("qsThreadInfo");
3197 getpkt (&rs->buf, &rs->buf_size, 0);
3204 /* Packet not recognized. */
3205 rs->use_threadinfo_query = 0;
3212 /* Implement the to_update_thread_list function for the remote
3216 remote_update_thread_list (struct target_ops *ops)
3218 struct threads_listing_context context;
3219 struct cleanup *old_chain;
3222 context.items = NULL;
3223 old_chain = make_cleanup (clear_threads_listing_context, &context);
3225 /* We have a few different mechanisms to fetch the thread list. Try
3226 them all, starting with the most preferred one first, falling
3227 back to older methods. */
3228 if (remote_get_threads_with_qxfer (ops, &context)
3229 || remote_get_threads_with_qthreadinfo (ops, &context)
3230 || remote_get_threads_with_ql (ops, &context))
3233 struct thread_item *item;
3234 struct thread_info *tp, *tmp;
3238 if (VEC_empty (thread_item_t, context.items)
3239 && remote_thread_always_alive (ops, inferior_ptid))
3241 /* Some targets don't really support threads, but still
3242 reply an (empty) thread list in response to the thread
3243 listing packets, instead of replying "packet not
3244 supported". Exit early so we don't delete the main
3246 do_cleanups (old_chain);
3250 /* CONTEXT now holds the current thread list on the remote
3251 target end. Delete GDB-side threads no longer found on the
3253 ALL_THREADS_SAFE (tp, tmp)
3256 VEC_iterate (thread_item_t, context.items, i, item);
3259 if (ptid_equal (item->ptid, tp->ptid))
3263 if (i == VEC_length (thread_item_t, context.items))
3266 delete_thread (tp->ptid);
3270 /* Remove any unreported fork child threads from CONTEXT so
3271 that we don't interfere with follow fork, which is where
3272 creation of such threads is handled. */
3273 remove_new_fork_children (&context);
3275 /* And now add threads we don't know about yet to our list. */
3277 VEC_iterate (thread_item_t, context.items, i, item);
3280 if (!ptid_equal (item->ptid, null_ptid))
3282 struct private_thread_info *info;
3283 /* In non-stop mode, we assume new found threads are
3284 executing until proven otherwise with a stop reply.
3285 In all-stop, we can only get here if all threads are
3287 int executing = target_is_non_stop_p () ? 1 : 0;
3289 remote_notice_new_inferior (item->ptid, executing);
3291 info = demand_private_info (item->ptid);
3292 info->core = item->core;
3293 info->extra = item->extra;
3295 info->name = item->name;
3303 /* If no thread listing method is supported, then query whether
3304 each known thread is alive, one by one, with the T packet.
3305 If the target doesn't support threads at all, then this is a
3306 no-op. See remote_thread_alive. */
3310 do_cleanups (old_chain);
3314 * Collect a descriptive string about the given thread.
3315 * The target may say anything it wants to about the thread
3316 * (typically info about its blocked / runnable state, name, etc.).
3317 * This string will appear in the info threads display.
3319 * Optional: targets are not required to implement this function.
3323 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3325 struct remote_state *rs = get_remote_state ();
3329 struct gdb_ext_thread_info threadinfo;
3330 static char display_buf[100]; /* arbitrary... */
3331 int n = 0; /* position in display_buf */
3333 if (rs->remote_desc == 0) /* paranoia */
3334 internal_error (__FILE__, __LINE__,
3335 _("remote_threads_extra_info"));
3337 if (ptid_equal (tp->ptid, magic_null_ptid)
3338 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3339 /* This is the main thread which was added by GDB. The remote
3340 server doesn't know about it. */
3343 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3345 struct thread_info *info = find_thread_ptid (tp->ptid);
3347 if (info && info->priv)
3348 return info->priv->extra;
3353 if (rs->use_threadextra_query)
3356 char *endb = rs->buf + get_remote_packet_size ();
3358 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3360 write_ptid (b, endb, tp->ptid);
3363 getpkt (&rs->buf, &rs->buf_size, 0);
3364 if (rs->buf[0] != 0)
3366 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3367 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3368 display_buf [result] = '\0';
3373 /* If the above query fails, fall back to the old method. */
3374 rs->use_threadextra_query = 0;
3375 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3376 | TAG_MOREDISPLAY | TAG_DISPLAY;
3377 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3378 if (remote_get_threadinfo (&id, set, &threadinfo))
3379 if (threadinfo.active)
3381 if (*threadinfo.shortname)
3382 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3383 " Name: %s,", threadinfo.shortname);
3384 if (*threadinfo.display)
3385 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3386 " State: %s,", threadinfo.display);
3387 if (*threadinfo.more_display)
3388 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3389 " Priority: %s", threadinfo.more_display);
3393 /* For purely cosmetic reasons, clear up trailing commas. */
3394 if (',' == display_buf[n-1])
3395 display_buf[n-1] = ' ';
3404 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3405 struct static_tracepoint_marker *marker)
3407 struct remote_state *rs = get_remote_state ();
3410 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3412 p += hexnumstr (p, addr);
3414 getpkt (&rs->buf, &rs->buf_size, 0);
3418 error (_("Remote failure reply: %s"), p);
3422 parse_static_tracepoint_marker_definition (p, &p, marker);
3429 static VEC(static_tracepoint_marker_p) *
3430 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3433 struct remote_state *rs = get_remote_state ();
3434 VEC(static_tracepoint_marker_p) *markers = NULL;
3435 struct static_tracepoint_marker *marker = NULL;
3436 struct cleanup *old_chain;
3439 /* Ask for a first packet of static tracepoint marker
3442 getpkt (&rs->buf, &rs->buf_size, 0);
3445 error (_("Remote failure reply: %s"), p);
3447 old_chain = make_cleanup (free_current_marker, &marker);
3452 marker = XCNEW (struct static_tracepoint_marker);
3456 parse_static_tracepoint_marker_definition (p, &p, marker);
3458 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3460 VEC_safe_push (static_tracepoint_marker_p,
3466 release_static_tracepoint_marker (marker);
3467 memset (marker, 0, sizeof (*marker));
3470 while (*p++ == ','); /* comma-separated list */
3471 /* Ask for another packet of static tracepoint definition. */
3473 getpkt (&rs->buf, &rs->buf_size, 0);
3477 do_cleanups (old_chain);
3482 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3485 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3487 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3491 /* Restart the remote side; this is an extended protocol operation. */
3494 extended_remote_restart (void)
3496 struct remote_state *rs = get_remote_state ();
3498 /* Send the restart command; for reasons I don't understand the
3499 remote side really expects a number after the "R". */
3500 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3503 remote_fileio_reset ();
3506 /* Clean up connection to a remote debugger. */
3509 remote_close (struct target_ops *self)
3511 struct remote_state *rs = get_remote_state ();
3513 if (rs->remote_desc == NULL)
3514 return; /* already closed */
3516 /* Make sure we leave stdin registered in the event loop, and we
3517 don't leave the async SIGINT signal handler installed. */
3518 remote_terminal_ours (self);
3520 serial_close (rs->remote_desc);
3521 rs->remote_desc = NULL;
3523 /* We don't have a connection to the remote stub anymore. Get rid
3524 of all the inferiors and their threads we were controlling.
3525 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3526 will be unable to find the thread corresponding to (pid, 0, 0). */
3527 inferior_ptid = null_ptid;
3528 discard_all_inferiors ();
3530 /* We are closing the remote target, so we should discard
3531 everything of this target. */
3532 discard_pending_stop_replies_in_queue (rs);
3534 if (remote_async_inferior_event_token)
3535 delete_async_event_handler (&remote_async_inferior_event_token);
3537 remote_notif_state_xfree (rs->notif_state);
3539 trace_reset_local_state ();
3542 /* Query the remote side for the text, data and bss offsets. */
3547 struct remote_state *rs = get_remote_state ();
3550 int lose, num_segments = 0, do_sections, do_segments;
3551 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3552 struct section_offsets *offs;
3553 struct symfile_segment_data *data;
3555 if (symfile_objfile == NULL)
3558 putpkt ("qOffsets");
3559 getpkt (&rs->buf, &rs->buf_size, 0);
3562 if (buf[0] == '\000')
3563 return; /* Return silently. Stub doesn't support
3567 warning (_("Remote failure reply: %s"), buf);
3571 /* Pick up each field in turn. This used to be done with scanf, but
3572 scanf will make trouble if CORE_ADDR size doesn't match
3573 conversion directives correctly. The following code will work
3574 with any size of CORE_ADDR. */
3575 text_addr = data_addr = bss_addr = 0;
3579 if (startswith (ptr, "Text="))
3582 /* Don't use strtol, could lose on big values. */
3583 while (*ptr && *ptr != ';')
3584 text_addr = (text_addr << 4) + fromhex (*ptr++);
3586 if (startswith (ptr, ";Data="))
3589 while (*ptr && *ptr != ';')
3590 data_addr = (data_addr << 4) + fromhex (*ptr++);
3595 if (!lose && startswith (ptr, ";Bss="))
3598 while (*ptr && *ptr != ';')
3599 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3601 if (bss_addr != data_addr)
3602 warning (_("Target reported unsupported offsets: %s"), buf);
3607 else if (startswith (ptr, "TextSeg="))
3610 /* Don't use strtol, could lose on big values. */
3611 while (*ptr && *ptr != ';')
3612 text_addr = (text_addr << 4) + fromhex (*ptr++);
3615 if (startswith (ptr, ";DataSeg="))
3618 while (*ptr && *ptr != ';')
3619 data_addr = (data_addr << 4) + fromhex (*ptr++);
3627 error (_("Malformed response to offset query, %s"), buf);
3628 else if (*ptr != '\0')
3629 warning (_("Target reported unsupported offsets: %s"), buf);
3631 offs = ((struct section_offsets *)
3632 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3633 memcpy (offs, symfile_objfile->section_offsets,
3634 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3636 data = get_symfile_segment_data (symfile_objfile->obfd);
3637 do_segments = (data != NULL);
3638 do_sections = num_segments == 0;
3640 if (num_segments > 0)
3642 segments[0] = text_addr;
3643 segments[1] = data_addr;
3645 /* If we have two segments, we can still try to relocate everything
3646 by assuming that the .text and .data offsets apply to the whole
3647 text and data segments. Convert the offsets given in the packet
3648 to base addresses for symfile_map_offsets_to_segments. */
3649 else if (data && data->num_segments == 2)
3651 segments[0] = data->segment_bases[0] + text_addr;
3652 segments[1] = data->segment_bases[1] + data_addr;
3655 /* If the object file has only one segment, assume that it is text
3656 rather than data; main programs with no writable data are rare,
3657 but programs with no code are useless. Of course the code might
3658 have ended up in the data segment... to detect that we would need
3659 the permissions here. */
3660 else if (data && data->num_segments == 1)
3662 segments[0] = data->segment_bases[0] + text_addr;
3665 /* There's no way to relocate by segment. */
3671 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3672 offs, num_segments, segments);
3674 if (ret == 0 && !do_sections)
3675 error (_("Can not handle qOffsets TextSeg "
3676 "response with this symbol file"));
3683 free_symfile_segment_data (data);
3687 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3689 /* This is a temporary kludge to force data and bss to use the
3690 same offsets because that's what nlmconv does now. The real
3691 solution requires changes to the stub and remote.c that I
3692 don't have time to do right now. */
3694 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3695 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3698 objfile_relocate (symfile_objfile, offs);
3701 /* Send interrupt_sequence to remote target. */
3703 send_interrupt_sequence (void)
3705 struct remote_state *rs = get_remote_state ();
3707 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3708 remote_serial_write ("\x03", 1);
3709 else if (interrupt_sequence_mode == interrupt_sequence_break)
3710 serial_send_break (rs->remote_desc);
3711 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3713 serial_send_break (rs->remote_desc);
3714 remote_serial_write ("g", 1);
3717 internal_error (__FILE__, __LINE__,
3718 _("Invalid value for interrupt_sequence_mode: %s."),
3719 interrupt_sequence_mode);
3723 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3724 and extract the PTID. Returns NULL_PTID if not found. */
3727 stop_reply_extract_thread (char *stop_reply)
3729 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3733 /* Txx r:val ; r:val (...) */
3736 /* Look for "register" named "thread". */
3741 p1 = strchr (p, ':');
3745 if (strncmp (p, "thread", p1 - p) == 0)
3746 return read_ptid (++p1, &p);
3748 p1 = strchr (p, ';');
3760 /* Determine the remote side's current thread. If we have a stop
3761 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3762 "thread" register we can extract the current thread from. If not,
3763 ask the remote which is the current thread with qC. The former
3764 method avoids a roundtrip. */
3767 get_current_thread (char *wait_status)
3769 ptid_t ptid = null_ptid;
3771 /* Note we don't use remote_parse_stop_reply as that makes use of
3772 the target architecture, which we haven't yet fully determined at
3774 if (wait_status != NULL)
3775 ptid = stop_reply_extract_thread (wait_status);
3776 if (ptid_equal (ptid, null_ptid))
3777 ptid = remote_current_thread (inferior_ptid);
3782 /* Query the remote target for which is the current thread/process,
3783 add it to our tables, and update INFERIOR_PTID. The caller is
3784 responsible for setting the state such that the remote end is ready
3785 to return the current thread.
3787 This function is called after handling the '?' or 'vRun' packets,
3788 whose response is a stop reply from which we can also try
3789 extracting the thread. If the target doesn't support the explicit
3790 qC query, we infer the current thread from that stop reply, passed
3791 in in WAIT_STATUS, which may be NULL. */
3794 add_current_inferior_and_thread (char *wait_status)
3796 struct remote_state *rs = get_remote_state ();
3800 inferior_ptid = null_ptid;
3802 /* Now, if we have thread information, update inferior_ptid. */
3803 ptid = get_current_thread (wait_status);
3805 if (!ptid_equal (ptid, null_ptid))
3807 if (!remote_multi_process_p (rs))
3810 inferior_ptid = ptid;
3814 /* Without this, some commands which require an active target
3815 (such as kill) won't work. This variable serves (at least)
3816 double duty as both the pid of the target process (if it has
3817 such), and as a flag indicating that a target is active. */
3818 inferior_ptid = magic_null_ptid;
3822 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3824 /* Add the main thread. */
3825 add_thread_silent (inferior_ptid);
3828 /* Print info about a thread that was found already stopped on
3832 print_one_stopped_thread (struct thread_info *thread)
3834 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3836 switch_to_thread (thread->ptid);
3837 stop_pc = get_frame_pc (get_current_frame ());
3838 set_current_sal_from_frame (get_current_frame ());
3840 thread->suspend.waitstatus_pending_p = 0;
3842 if (ws->kind == TARGET_WAITKIND_STOPPED)
3844 enum gdb_signal sig = ws->value.sig;
3846 if (signal_print_state (sig))
3847 observer_notify_signal_received (sig);
3849 observer_notify_normal_stop (NULL, 1);
3852 /* Process all initial stop replies the remote side sent in response
3853 to the ? packet. These indicate threads that were already stopped
3854 on initial connection. We mark these threads as stopped and print
3855 their current frame before giving the user the prompt. */
3858 process_initial_stop_replies (int from_tty)
3860 int pending_stop_replies = stop_reply_queue_length ();
3861 struct inferior *inf;
3862 struct thread_info *thread;
3863 struct thread_info *selected = NULL;
3864 struct thread_info *lowest_stopped = NULL;
3865 struct thread_info *first = NULL;
3867 /* Consume the initial pending events. */
3868 while (pending_stop_replies-- > 0)
3870 ptid_t waiton_ptid = minus_one_ptid;
3872 struct target_waitstatus ws;
3873 int ignore_event = 0;
3874 struct thread_info *thread;
3876 memset (&ws, 0, sizeof (ws));
3877 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3879 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3883 case TARGET_WAITKIND_IGNORE:
3884 case TARGET_WAITKIND_NO_RESUMED:
3885 case TARGET_WAITKIND_SIGNALLED:
3886 case TARGET_WAITKIND_EXITED:
3887 /* We shouldn't see these, but if we do, just ignore. */
3889 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3893 case TARGET_WAITKIND_EXECD:
3894 xfree (ws.value.execd_pathname);
3903 thread = find_thread_ptid (event_ptid);
3905 if (ws.kind == TARGET_WAITKIND_STOPPED)
3907 enum gdb_signal sig = ws.value.sig;
3909 /* Stubs traditionally report SIGTRAP as initial signal,
3910 instead of signal 0. Suppress it. */
3911 if (sig == GDB_SIGNAL_TRAP)
3913 thread->suspend.stop_signal = sig;
3917 thread->suspend.waitstatus = ws;
3919 if (ws.kind != TARGET_WAITKIND_STOPPED
3920 || ws.value.sig != GDB_SIGNAL_0)
3921 thread->suspend.waitstatus_pending_p = 1;
3923 set_executing (event_ptid, 0);
3924 set_running (event_ptid, 0);
3927 /* "Notice" the new inferiors before anything related to
3928 registers/memory. */
3934 inf->needs_setup = 1;
3938 thread = any_live_thread_of_process (inf->pid);
3939 notice_new_inferior (thread->ptid,
3940 thread->state == THREAD_RUNNING,
3945 /* If all-stop on top of non-stop, pause all threads. Note this
3946 records the threads' stop pc, so must be done after "noticing"
3950 stop_all_threads ();
3952 /* If all threads of an inferior were already stopped, we
3953 haven't setup the inferior yet. */
3959 if (inf->needs_setup)
3961 thread = any_live_thread_of_process (inf->pid);
3962 switch_to_thread_no_regs (thread);
3968 /* Now go over all threads that are stopped, and print their current
3969 frame. If all-stop, then if there's a signalled thread, pick
3971 ALL_NON_EXITED_THREADS (thread)
3977 set_running (thread->ptid, 0);
3978 else if (thread->state != THREAD_STOPPED)
3981 if (selected == NULL
3982 && thread->suspend.waitstatus_pending_p)
3985 if (lowest_stopped == NULL
3986 || thread->inf->num < lowest_stopped->inf->num
3987 || thread->per_inf_num < lowest_stopped->per_inf_num)
3988 lowest_stopped = thread;
3991 print_one_stopped_thread (thread);
3994 /* In all-stop, we only print the status of one thread, and leave
3995 others with their status pending. */
4000 thread = lowest_stopped;
4004 print_one_stopped_thread (thread);
4007 /* For "info program". */
4008 thread = inferior_thread ();
4009 if (thread->state == THREAD_STOPPED)
4010 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4014 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4016 struct remote_state *rs = get_remote_state ();
4017 struct packet_config *noack_config;
4018 char *wait_status = NULL;
4020 immediate_quit++; /* Allow user to interrupt it. */
4023 if (interrupt_on_connect)
4024 send_interrupt_sequence ();
4026 /* Ack any packet which the remote side has already sent. */
4027 serial_write (rs->remote_desc, "+", 1);
4029 /* Signal other parts that we're going through the initial setup,
4030 and so things may not be stable yet. */
4031 rs->starting_up = 1;
4033 /* The first packet we send to the target is the optional "supported
4034 packets" request. If the target can answer this, it will tell us
4035 which later probes to skip. */
4036 remote_query_supported ();
4038 /* If the stub wants to get a QAllow, compose one and send it. */
4039 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4040 remote_set_permissions (target);
4042 /* See unknown_v_replies_ok description. */
4044 const char v_mustreplyempty[] = "vMustReplyEmpty";
4046 putpkt (v_mustreplyempty);
4047 getpkt (&rs->buf, &rs->buf_size, 0);
4048 if (strcmp (rs->buf, "OK") == 0)
4049 rs->unknown_v_replies_ok = 1;
4050 else if (strcmp (rs->buf, "") == 0)
4051 rs->unknown_v_replies_ok = 0;
4053 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4057 /* Next, we possibly activate noack mode.
4059 If the QStartNoAckMode packet configuration is set to AUTO,
4060 enable noack mode if the stub reported a wish for it with
4063 If set to TRUE, then enable noack mode even if the stub didn't
4064 report it in qSupported. If the stub doesn't reply OK, the
4065 session ends with an error.
4067 If FALSE, then don't activate noack mode, regardless of what the
4068 stub claimed should be the default with qSupported. */
4070 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4071 if (packet_config_support (noack_config) != PACKET_DISABLE)
4073 putpkt ("QStartNoAckMode");
4074 getpkt (&rs->buf, &rs->buf_size, 0);
4075 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4081 /* Tell the remote that we are using the extended protocol. */
4083 getpkt (&rs->buf, &rs->buf_size, 0);
4086 /* Let the target know which signals it is allowed to pass down to
4088 update_signals_program_target ();
4090 /* Next, if the target can specify a description, read it. We do
4091 this before anything involving memory or registers. */
4092 target_find_description ();
4094 /* Next, now that we know something about the target, update the
4095 address spaces in the program spaces. */
4096 update_address_spaces ();
4098 /* On OSs where the list of libraries is global to all
4099 processes, we fetch them early. */
4100 if (gdbarch_has_global_solist (target_gdbarch ()))
4101 solib_add (NULL, from_tty, target, auto_solib_add);
4103 if (target_is_non_stop_p ())
4105 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4106 error (_("Non-stop mode requested, but remote "
4107 "does not support non-stop"));
4109 putpkt ("QNonStop:1");
4110 getpkt (&rs->buf, &rs->buf_size, 0);
4112 if (strcmp (rs->buf, "OK") != 0)
4113 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4115 /* Find about threads and processes the stub is already
4116 controlling. We default to adding them in the running state.
4117 The '?' query below will then tell us about which threads are
4119 remote_update_thread_list (target);
4121 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4123 /* Don't assume that the stub can operate in all-stop mode.
4124 Request it explicitly. */
4125 putpkt ("QNonStop:0");
4126 getpkt (&rs->buf, &rs->buf_size, 0);
4128 if (strcmp (rs->buf, "OK") != 0)
4129 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4132 /* Upload TSVs regardless of whether the target is running or not. The
4133 remote stub, such as GDBserver, may have some predefined or builtin
4134 TSVs, even if the target is not running. */
4135 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4137 struct uploaded_tsv *uploaded_tsvs = NULL;
4139 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4140 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4143 /* Check whether the target is running now. */
4145 getpkt (&rs->buf, &rs->buf_size, 0);
4147 if (!target_is_non_stop_p ())
4149 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4152 error (_("The target is not running (try extended-remote?)"));
4154 /* We're connected, but not running. Drop out before we
4155 call start_remote. */
4156 rs->starting_up = 0;
4161 /* Save the reply for later. */
4162 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4163 strcpy (wait_status, rs->buf);
4166 /* Fetch thread list. */
4167 target_update_thread_list ();
4169 /* Let the stub know that we want it to return the thread. */
4170 set_continue_thread (minus_one_ptid);
4172 if (thread_count () == 0)
4174 /* Target has no concept of threads at all. GDB treats
4175 non-threaded target as single-threaded; add a main
4177 add_current_inferior_and_thread (wait_status);
4181 /* We have thread information; select the thread the target
4182 says should be current. If we're reconnecting to a
4183 multi-threaded program, this will ideally be the thread
4184 that last reported an event before GDB disconnected. */
4185 inferior_ptid = get_current_thread (wait_status);
4186 if (ptid_equal (inferior_ptid, null_ptid))
4188 /* Odd... The target was able to list threads, but not
4189 tell us which thread was current (no "thread"
4190 register in T stop reply?). Just pick the first
4191 thread in the thread list then. */
4194 fprintf_unfiltered (gdb_stdlog,
4195 "warning: couldn't determine remote "
4196 "current thread; picking first in list.\n");
4198 inferior_ptid = thread_list->ptid;
4202 /* init_wait_for_inferior should be called before get_offsets in order
4203 to manage `inserted' flag in bp loc in a correct state.
4204 breakpoint_init_inferior, called from init_wait_for_inferior, set
4205 `inserted' flag to 0, while before breakpoint_re_set, called from
4206 start_remote, set `inserted' flag to 1. In the initialization of
4207 inferior, breakpoint_init_inferior should be called first, and then
4208 breakpoint_re_set can be called. If this order is broken, state of
4209 `inserted' flag is wrong, and cause some problems on breakpoint
4211 init_wait_for_inferior ();
4213 get_offsets (); /* Get text, data & bss offsets. */
4215 /* If we could not find a description using qXfer, and we know
4216 how to do it some other way, try again. This is not
4217 supported for non-stop; it could be, but it is tricky if
4218 there are no stopped threads when we connect. */
4219 if (remote_read_description_p (target)
4220 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4222 target_clear_description ();
4223 target_find_description ();
4226 /* Use the previously fetched status. */
4227 gdb_assert (wait_status != NULL);
4228 strcpy (rs->buf, wait_status);
4229 rs->cached_wait_status = 1;
4232 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4236 /* Clear WFI global state. Do this before finding about new
4237 threads and inferiors, and setting the current inferior.
4238 Otherwise we would clear the proceed status of the current
4239 inferior when we want its stop_soon state to be preserved
4240 (see notice_new_inferior). */
4241 init_wait_for_inferior ();
4243 /* In non-stop, we will either get an "OK", meaning that there
4244 are no stopped threads at this time; or, a regular stop
4245 reply. In the latter case, there may be more than one thread
4246 stopped --- we pull them all out using the vStopped
4248 if (strcmp (rs->buf, "OK") != 0)
4250 struct notif_client *notif = ¬if_client_stop;
4252 /* remote_notif_get_pending_replies acks this one, and gets
4254 rs->notif_state->pending_event[notif_client_stop.id]
4255 = remote_notif_parse (notif, rs->buf);
4256 remote_notif_get_pending_events (notif);
4259 if (thread_count () == 0)
4262 error (_("The target is not running (try extended-remote?)"));
4264 /* We're connected, but not running. Drop out before we
4265 call start_remote. */
4266 rs->starting_up = 0;
4270 /* In non-stop mode, any cached wait status will be stored in
4271 the stop reply queue. */
4272 gdb_assert (wait_status == NULL);
4274 /* Report all signals during attach/startup. */
4275 remote_pass_signals (target, 0, NULL);
4277 /* If there are already stopped threads, mark them stopped and
4278 report their stops before giving the prompt to the user. */
4279 process_initial_stop_replies (from_tty);
4281 if (target_can_async_p ())
4285 /* If we connected to a live target, do some additional setup. */
4286 if (target_has_execution)
4288 if (symfile_objfile) /* No use without a symbol-file. */
4289 remote_check_symbols ();
4292 /* Possibly the target has been engaged in a trace run started
4293 previously; find out where things are at. */
4294 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4296 struct uploaded_tp *uploaded_tps = NULL;
4298 if (current_trace_status ()->running)
4299 printf_filtered (_("Trace is already running on the target.\n"));
4301 remote_upload_tracepoints (target, &uploaded_tps);
4303 merge_uploaded_tracepoints (&uploaded_tps);
4306 /* The thread and inferior lists are now synchronized with the
4307 target, our symbols have been relocated, and we're merged the
4308 target's tracepoints with ours. We're done with basic start
4310 rs->starting_up = 0;
4312 /* Maybe breakpoints are global and need to be inserted now. */
4313 if (breakpoints_should_be_inserted_now ())
4314 insert_breakpoints ();
4317 /* Open a connection to a remote debugger.
4318 NAME is the filename used for communication. */
4321 remote_open (const char *name, int from_tty)
4323 remote_open_1 (name, from_tty, &remote_ops, 0);
4326 /* Open a connection to a remote debugger using the extended
4327 remote gdb protocol. NAME is the filename used for communication. */
4330 extended_remote_open (const char *name, int from_tty)
4332 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4335 /* Reset all packets back to "unknown support". Called when opening a
4336 new connection to a remote target. */
4339 reset_all_packet_configs_support (void)
4343 for (i = 0; i < PACKET_MAX; i++)
4344 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4347 /* Initialize all packet configs. */
4350 init_all_packet_configs (void)
4354 for (i = 0; i < PACKET_MAX; i++)
4356 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4357 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4361 /* Symbol look-up. */
4364 remote_check_symbols (void)
4366 struct remote_state *rs = get_remote_state ();
4367 char *msg, *reply, *tmp;
4370 struct cleanup *old_chain;
4372 /* The remote side has no concept of inferiors that aren't running
4373 yet, it only knows about running processes. If we're connected
4374 but our current inferior is not running, we should not invite the
4375 remote target to request symbol lookups related to its
4376 (unrelated) current process. */
4377 if (!target_has_execution)
4380 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4383 /* Make sure the remote is pointing at the right process. Note
4384 there's no way to select "no process". */
4385 set_general_process ();
4387 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4388 because we need both at the same time. */
4389 msg = (char *) xmalloc (get_remote_packet_size ());
4390 old_chain = make_cleanup (xfree, msg);
4391 reply = (char *) xmalloc (get_remote_packet_size ());
4392 make_cleanup (free_current_contents, &reply);
4393 reply_size = get_remote_packet_size ();
4395 /* Invite target to request symbol lookups. */
4397 putpkt ("qSymbol::");
4398 getpkt (&reply, &reply_size, 0);
4399 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4401 while (startswith (reply, "qSymbol:"))
4403 struct bound_minimal_symbol sym;
4406 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4408 sym = lookup_minimal_symbol (msg, NULL, NULL);
4409 if (sym.minsym == NULL)
4410 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4413 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4414 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4416 /* If this is a function address, return the start of code
4417 instead of any data function descriptor. */
4418 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4422 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4423 phex_nz (sym_addr, addr_size), &reply[8]);
4427 getpkt (&reply, &reply_size, 0);
4430 do_cleanups (old_chain);
4433 static struct serial *
4434 remote_serial_open (const char *name)
4436 static int udp_warning = 0;
4438 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4439 of in ser-tcp.c, because it is the remote protocol assuming that the
4440 serial connection is reliable and not the serial connection promising
4442 if (!udp_warning && startswith (name, "udp:"))
4444 warning (_("The remote protocol may be unreliable over UDP.\n"
4445 "Some events may be lost, rendering further debugging "
4450 return serial_open (name);
4453 /* Inform the target of our permission settings. The permission flags
4454 work without this, but if the target knows the settings, it can do
4455 a couple things. First, it can add its own check, to catch cases
4456 that somehow manage to get by the permissions checks in target
4457 methods. Second, if the target is wired to disallow particular
4458 settings (for instance, a system in the field that is not set up to
4459 be able to stop at a breakpoint), it can object to any unavailable
4463 remote_set_permissions (struct target_ops *self)
4465 struct remote_state *rs = get_remote_state ();
4467 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4468 "WriteReg:%x;WriteMem:%x;"
4469 "InsertBreak:%x;InsertTrace:%x;"
4470 "InsertFastTrace:%x;Stop:%x",
4471 may_write_registers, may_write_memory,
4472 may_insert_breakpoints, may_insert_tracepoints,
4473 may_insert_fast_tracepoints, may_stop);
4475 getpkt (&rs->buf, &rs->buf_size, 0);
4477 /* If the target didn't like the packet, warn the user. Do not try
4478 to undo the user's settings, that would just be maddening. */
4479 if (strcmp (rs->buf, "OK") != 0)
4480 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4483 /* This type describes each known response to the qSupported
4485 struct protocol_feature
4487 /* The name of this protocol feature. */
4490 /* The default for this protocol feature. */
4491 enum packet_support default_support;
4493 /* The function to call when this feature is reported, or after
4494 qSupported processing if the feature is not supported.
4495 The first argument points to this structure. The second
4496 argument indicates whether the packet requested support be
4497 enabled, disabled, or probed (or the default, if this function
4498 is being called at the end of processing and this feature was
4499 not reported). The third argument may be NULL; if not NULL, it
4500 is a NUL-terminated string taken from the packet following
4501 this feature's name and an equals sign. */
4502 void (*func) (const struct protocol_feature *, enum packet_support,
4505 /* The corresponding packet for this feature. Only used if
4506 FUNC is remote_supported_packet. */
4511 remote_supported_packet (const struct protocol_feature *feature,
4512 enum packet_support support,
4513 const char *argument)
4517 warning (_("Remote qSupported response supplied an unexpected value for"
4518 " \"%s\"."), feature->name);
4522 remote_protocol_packets[feature->packet].support = support;
4526 remote_packet_size (const struct protocol_feature *feature,
4527 enum packet_support support, const char *value)
4529 struct remote_state *rs = get_remote_state ();
4534 if (support != PACKET_ENABLE)
4537 if (value == NULL || *value == '\0')
4539 warning (_("Remote target reported \"%s\" without a size."),
4545 packet_size = strtol (value, &value_end, 16);
4546 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4548 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4549 feature->name, value);
4553 /* Record the new maximum packet size. */
4554 rs->explicit_packet_size = packet_size;
4557 static const struct protocol_feature remote_protocol_features[] = {
4558 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4559 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4560 PACKET_qXfer_auxv },
4561 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4562 PACKET_qXfer_exec_file },
4563 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4564 PACKET_qXfer_features },
4565 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4566 PACKET_qXfer_libraries },
4567 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4568 PACKET_qXfer_libraries_svr4 },
4569 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4570 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4571 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4572 PACKET_qXfer_memory_map },
4573 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4574 PACKET_qXfer_spu_read },
4575 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4576 PACKET_qXfer_spu_write },
4577 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4578 PACKET_qXfer_osdata },
4579 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4580 PACKET_qXfer_threads },
4581 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4582 PACKET_qXfer_traceframe_info },
4583 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4584 PACKET_QPassSignals },
4585 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4586 PACKET_QCatchSyscalls },
4587 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4588 PACKET_QProgramSignals },
4589 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4590 PACKET_QStartNoAckMode },
4591 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4592 PACKET_multiprocess_feature },
4593 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4594 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4595 PACKET_qXfer_siginfo_read },
4596 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4597 PACKET_qXfer_siginfo_write },
4598 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4599 PACKET_ConditionalTracepoints },
4600 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4601 PACKET_ConditionalBreakpoints },
4602 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4603 PACKET_BreakpointCommands },
4604 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4605 PACKET_FastTracepoints },
4606 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4607 PACKET_StaticTracepoints },
4608 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4609 PACKET_InstallInTrace},
4610 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4611 PACKET_DisconnectedTracing_feature },
4612 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4614 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4616 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4617 PACKET_TracepointSource },
4618 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4620 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4621 PACKET_EnableDisableTracepoints_feature },
4622 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4623 PACKET_qXfer_fdpic },
4624 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4626 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4627 PACKET_QDisableRandomization },
4628 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4629 { "QTBuffer:size", PACKET_DISABLE,
4630 remote_supported_packet, PACKET_QTBuffer_size},
4631 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4632 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4633 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4634 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4635 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4636 PACKET_qXfer_btrace },
4637 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4638 PACKET_qXfer_btrace_conf },
4639 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4640 PACKET_Qbtrace_conf_bts_size },
4641 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4642 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4643 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4644 PACKET_fork_event_feature },
4645 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4646 PACKET_vfork_event_feature },
4647 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4648 PACKET_exec_event_feature },
4649 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4650 PACKET_Qbtrace_conf_pt_size },
4651 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4652 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4653 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4656 static char *remote_support_xml;
4658 /* Register string appended to "xmlRegisters=" in qSupported query. */
4661 register_remote_support_xml (const char *xml)
4663 #if defined(HAVE_LIBEXPAT)
4664 if (remote_support_xml == NULL)
4665 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4668 char *copy = xstrdup (remote_support_xml + 13);
4669 char *p = strtok (copy, ",");
4673 if (strcmp (p, xml) == 0)
4680 while ((p = strtok (NULL, ",")) != NULL);
4683 remote_support_xml = reconcat (remote_support_xml,
4684 remote_support_xml, ",", xml,
4691 remote_query_supported_append (char *msg, const char *append)
4694 return reconcat (msg, msg, ";", append, (char *) NULL);
4696 return xstrdup (append);
4700 remote_query_supported (void)
4702 struct remote_state *rs = get_remote_state ();
4705 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4707 /* The packet support flags are handled differently for this packet
4708 than for most others. We treat an error, a disabled packet, and
4709 an empty response identically: any features which must be reported
4710 to be used will be automatically disabled. An empty buffer
4711 accomplishes this, since that is also the representation for a list
4712 containing no features. */
4715 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4718 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4720 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4721 q = remote_query_supported_append (q, "multiprocess+");
4723 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4724 q = remote_query_supported_append (q, "swbreak+");
4725 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4726 q = remote_query_supported_append (q, "hwbreak+");
4728 q = remote_query_supported_append (q, "qRelocInsn+");
4730 if (packet_set_cmd_state (PACKET_fork_event_feature)
4731 != AUTO_BOOLEAN_FALSE)
4732 q = remote_query_supported_append (q, "fork-events+");
4733 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4734 != AUTO_BOOLEAN_FALSE)
4735 q = remote_query_supported_append (q, "vfork-events+");
4736 if (packet_set_cmd_state (PACKET_exec_event_feature)
4737 != AUTO_BOOLEAN_FALSE)
4738 q = remote_query_supported_append (q, "exec-events+");
4740 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4741 q = remote_query_supported_append (q, "vContSupported+");
4743 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4744 q = remote_query_supported_append (q, "QThreadEvents+");
4746 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4747 q = remote_query_supported_append (q, "no-resumed+");
4749 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4750 the qSupported:xmlRegisters=i386 handling. */
4751 if (remote_support_xml != NULL)
4752 q = remote_query_supported_append (q, remote_support_xml);
4754 q = reconcat (q, "qSupported:", q, (char *) NULL);
4757 do_cleanups (old_chain);
4759 getpkt (&rs->buf, &rs->buf_size, 0);
4761 /* If an error occured, warn, but do not return - just reset the
4762 buffer to empty and go on to disable features. */
4763 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4766 warning (_("Remote failure reply: %s"), rs->buf);
4771 memset (seen, 0, sizeof (seen));
4776 enum packet_support is_supported;
4777 char *p, *end, *name_end, *value;
4779 /* First separate out this item from the rest of the packet. If
4780 there's another item after this, we overwrite the separator
4781 (terminated strings are much easier to work with). */
4783 end = strchr (p, ';');
4786 end = p + strlen (p);
4796 warning (_("empty item in \"qSupported\" response"));
4801 name_end = strchr (p, '=');
4804 /* This is a name=value entry. */
4805 is_supported = PACKET_ENABLE;
4806 value = name_end + 1;
4815 is_supported = PACKET_ENABLE;
4819 is_supported = PACKET_DISABLE;
4823 is_supported = PACKET_SUPPORT_UNKNOWN;
4827 warning (_("unrecognized item \"%s\" "
4828 "in \"qSupported\" response"), p);
4834 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4835 if (strcmp (remote_protocol_features[i].name, p) == 0)
4837 const struct protocol_feature *feature;
4840 feature = &remote_protocol_features[i];
4841 feature->func (feature, is_supported, value);
4846 /* If we increased the packet size, make sure to increase the global
4847 buffer size also. We delay this until after parsing the entire
4848 qSupported packet, because this is the same buffer we were
4850 if (rs->buf_size < rs->explicit_packet_size)
4852 rs->buf_size = rs->explicit_packet_size;
4853 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4856 /* Handle the defaults for unmentioned features. */
4857 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4860 const struct protocol_feature *feature;
4862 feature = &remote_protocol_features[i];
4863 feature->func (feature, feature->default_support, NULL);
4867 /* Remove any of the remote.c targets from target stack. Upper targets depend
4868 on it so remove them first. */
4871 remote_unpush_target (void)
4873 pop_all_targets_at_and_above (process_stratum);
4877 remote_open_1 (const char *name, int from_tty,
4878 struct target_ops *target, int extended_p)
4880 struct remote_state *rs = get_remote_state ();
4883 error (_("To open a remote debug connection, you need to specify what\n"
4884 "serial device is attached to the remote system\n"
4885 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4887 /* See FIXME above. */
4888 if (!target_async_permitted)
4889 wait_forever_enabled_p = 1;
4891 /* If we're connected to a running target, target_preopen will kill it.
4892 Ask this question first, before target_preopen has a chance to kill
4894 if (rs->remote_desc != NULL && !have_inferiors ())
4897 && !query (_("Already connected to a remote target. Disconnect? ")))
4898 error (_("Still connected."));
4901 /* Here the possibly existing remote target gets unpushed. */
4902 target_preopen (from_tty);
4904 /* Make sure we send the passed signals list the next time we resume. */
4905 xfree (rs->last_pass_packet);
4906 rs->last_pass_packet = NULL;
4908 /* Make sure we send the program signals list the next time we
4910 xfree (rs->last_program_signals_packet);
4911 rs->last_program_signals_packet = NULL;
4913 remote_fileio_reset ();
4914 reopen_exec_file ();
4917 rs->remote_desc = remote_serial_open (name);
4918 if (!rs->remote_desc)
4919 perror_with_name (name);
4921 if (baud_rate != -1)
4923 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4925 /* The requested speed could not be set. Error out to
4926 top level after closing remote_desc. Take care to
4927 set remote_desc to NULL to avoid closing remote_desc
4929 serial_close (rs->remote_desc);
4930 rs->remote_desc = NULL;
4931 perror_with_name (name);
4935 serial_setparity (rs->remote_desc, serial_parity);
4936 serial_raw (rs->remote_desc);
4938 /* If there is something sitting in the buffer we might take it as a
4939 response to a command, which would be bad. */
4940 serial_flush_input (rs->remote_desc);
4944 puts_filtered ("Remote debugging using ");
4945 puts_filtered (name);
4946 puts_filtered ("\n");
4948 push_target (target); /* Switch to using remote target now. */
4950 /* Register extra event sources in the event loop. */
4951 remote_async_inferior_event_token
4952 = create_async_event_handler (remote_async_inferior_event_handler,
4954 rs->notif_state = remote_notif_state_allocate ();
4956 /* Reset the target state; these things will be queried either by
4957 remote_query_supported or as they are needed. */
4958 reset_all_packet_configs_support ();
4959 rs->cached_wait_status = 0;
4960 rs->explicit_packet_size = 0;
4962 rs->extended = extended_p;
4963 rs->waiting_for_stop_reply = 0;
4964 rs->ctrlc_pending_p = 0;
4966 rs->general_thread = not_sent_ptid;
4967 rs->continue_thread = not_sent_ptid;
4968 rs->remote_traceframe_number = -1;
4970 /* Probe for ability to use "ThreadInfo" query, as required. */
4971 rs->use_threadinfo_query = 1;
4972 rs->use_threadextra_query = 1;
4974 readahead_cache_invalidate ();
4976 if (target_async_permitted)
4978 /* With this target we start out by owning the terminal. */
4979 remote_async_terminal_ours_p = 1;
4981 /* FIXME: cagney/1999-09-23: During the initial connection it is
4982 assumed that the target is already ready and able to respond to
4983 requests. Unfortunately remote_start_remote() eventually calls
4984 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4985 around this. Eventually a mechanism that allows
4986 wait_for_inferior() to expect/get timeouts will be
4988 wait_forever_enabled_p = 0;
4991 /* First delete any symbols previously loaded from shared libraries. */
4992 no_shared_libraries (NULL, 0);
4995 init_thread_list ();
4997 /* Start the remote connection. If error() or QUIT, discard this
4998 target (we'd otherwise be in an inconsistent state) and then
4999 propogate the error on up the exception chain. This ensures that
5000 the caller doesn't stumble along blindly assuming that the
5001 function succeeded. The CLI doesn't have this problem but other
5002 UI's, such as MI do.
5004 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5005 this function should return an error indication letting the
5006 caller restore the previous state. Unfortunately the command
5007 ``target remote'' is directly wired to this function making that
5008 impossible. On a positive note, the CLI side of this problem has
5009 been fixed - the function set_cmd_context() makes it possible for
5010 all the ``target ....'' commands to share a common callback
5011 function. See cli-dump.c. */
5016 remote_start_remote (from_tty, target, extended_p);
5018 CATCH (ex, RETURN_MASK_ALL)
5020 /* Pop the partially set up target - unless something else did
5021 already before throwing the exception. */
5022 if (rs->remote_desc != NULL)
5023 remote_unpush_target ();
5024 if (target_async_permitted)
5025 wait_forever_enabled_p = 1;
5026 throw_exception (ex);
5031 remote_btrace_reset ();
5033 if (target_async_permitted)
5034 wait_forever_enabled_p = 1;
5037 /* Detach the specified process. */
5040 remote_detach_pid (int pid)
5042 struct remote_state *rs = get_remote_state ();
5044 if (remote_multi_process_p (rs))
5045 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5047 strcpy (rs->buf, "D");
5050 getpkt (&rs->buf, &rs->buf_size, 0);
5052 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5054 else if (rs->buf[0] == '\0')
5055 error (_("Remote doesn't know how to detach"));
5057 error (_("Can't detach process."));
5060 /* This detaches a program to which we previously attached, using
5061 inferior_ptid to identify the process. After this is done, GDB
5062 can be used to debug some other program. We better not have left
5063 any breakpoints in the target program or it'll die when it hits
5067 remote_detach_1 (const char *args, int from_tty)
5069 int pid = ptid_get_pid (inferior_ptid);
5070 struct remote_state *rs = get_remote_state ();
5071 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5075 error (_("Argument given to \"detach\" when remotely debugging."));
5077 if (!target_has_execution)
5078 error (_("No process to detach from."));
5082 char *exec_file = get_exec_file (0);
5083 if (exec_file == NULL)
5085 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5086 target_pid_to_str (pid_to_ptid (pid)));
5087 gdb_flush (gdb_stdout);
5090 /* Tell the remote target to detach. */
5091 remote_detach_pid (pid);
5093 /* Exit only if this is the only active inferior. */
5094 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5095 puts_filtered (_("Ending remote debugging.\n"));
5097 /* Check to see if we are detaching a fork parent. Note that if we
5098 are detaching a fork child, tp == NULL. */
5099 is_fork_parent = (tp != NULL
5100 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5102 /* If doing detach-on-fork, we don't mourn, because that will delete
5103 breakpoints that should be available for the followed inferior. */
5104 if (!is_fork_parent)
5105 target_mourn_inferior ();
5108 inferior_ptid = null_ptid;
5109 detach_inferior (pid);
5114 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5116 remote_detach_1 (args, from_tty);
5120 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5122 remote_detach_1 (args, from_tty);
5125 /* Target follow-fork function for remote targets. On entry, and
5126 at return, the current inferior is the fork parent.
5128 Note that although this is currently only used for extended-remote,
5129 it is named remote_follow_fork in anticipation of using it for the
5130 remote target as well. */
5133 remote_follow_fork (struct target_ops *ops, int follow_child,
5136 struct remote_state *rs = get_remote_state ();
5137 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5139 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5140 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5142 /* When following the parent and detaching the child, we detach
5143 the child here. For the case of following the child and
5144 detaching the parent, the detach is done in the target-
5145 independent follow fork code in infrun.c. We can't use
5146 target_detach when detaching an unfollowed child because
5147 the client side doesn't know anything about the child. */
5148 if (detach_fork && !follow_child)
5150 /* Detach the fork child. */
5154 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5155 child_pid = ptid_get_pid (child_ptid);
5157 remote_detach_pid (child_pid);
5158 detach_inferior (child_pid);
5164 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5165 in the program space of the new inferior. On entry and at return the
5166 current inferior is the exec'ing inferior. INF is the new exec'd
5167 inferior, which may be the same as the exec'ing inferior unless
5168 follow-exec-mode is "new". */
5171 remote_follow_exec (struct target_ops *ops,
5172 struct inferior *inf, char *execd_pathname)
5174 /* We know that this is a target file name, so if it has the "target:"
5175 prefix we strip it off before saving it in the program space. */
5176 if (is_target_filename (execd_pathname))
5177 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5179 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5182 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5185 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5188 error (_("Argument given to \"disconnect\" when remotely debugging."));
5190 /* Make sure we unpush even the extended remote targets. Calling
5191 target_mourn_inferior won't unpush, and remote_mourn won't
5192 unpush if there is more than one inferior left. */
5193 unpush_target (target);
5194 generic_mourn_inferior ();
5197 puts_filtered ("Ending remote debugging.\n");
5200 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5201 be chatty about it. */
5204 extended_remote_attach (struct target_ops *target, const char *args,
5207 struct remote_state *rs = get_remote_state ();
5209 char *wait_status = NULL;
5211 pid = parse_pid_to_attach (args);
5213 /* Remote PID can be freely equal to getpid, do not check it here the same
5214 way as in other targets. */
5216 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5217 error (_("This target does not support attaching to a process"));
5221 char *exec_file = get_exec_file (0);
5224 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5225 target_pid_to_str (pid_to_ptid (pid)));
5227 printf_unfiltered (_("Attaching to %s\n"),
5228 target_pid_to_str (pid_to_ptid (pid)));
5230 gdb_flush (gdb_stdout);
5233 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5235 getpkt (&rs->buf, &rs->buf_size, 0);
5237 switch (packet_ok (rs->buf,
5238 &remote_protocol_packets[PACKET_vAttach]))
5241 if (!target_is_non_stop_p ())
5243 /* Save the reply for later. */
5244 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5245 strcpy (wait_status, rs->buf);
5247 else if (strcmp (rs->buf, "OK") != 0)
5248 error (_("Attaching to %s failed with: %s"),
5249 target_pid_to_str (pid_to_ptid (pid)),
5252 case PACKET_UNKNOWN:
5253 error (_("This target does not support attaching to a process"));
5255 error (_("Attaching to %s failed"),
5256 target_pid_to_str (pid_to_ptid (pid)));
5259 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5261 inferior_ptid = pid_to_ptid (pid);
5263 if (target_is_non_stop_p ())
5265 struct thread_info *thread;
5267 /* Get list of threads. */
5268 remote_update_thread_list (target);
5270 thread = first_thread_of_process (pid);
5272 inferior_ptid = thread->ptid;
5274 inferior_ptid = pid_to_ptid (pid);
5276 /* Invalidate our notion of the remote current thread. */
5277 record_currthread (rs, minus_one_ptid);
5281 /* Now, if we have thread information, update inferior_ptid. */
5282 inferior_ptid = remote_current_thread (inferior_ptid);
5284 /* Add the main thread to the thread list. */
5285 add_thread_silent (inferior_ptid);
5288 /* Next, if the target can specify a description, read it. We do
5289 this before anything involving memory or registers. */
5290 target_find_description ();
5292 if (!target_is_non_stop_p ())
5294 /* Use the previously fetched status. */
5295 gdb_assert (wait_status != NULL);
5297 if (target_can_async_p ())
5299 struct notif_event *reply
5300 = remote_notif_parse (¬if_client_stop, wait_status);
5302 push_stop_reply ((struct stop_reply *) reply);
5308 gdb_assert (wait_status != NULL);
5309 strcpy (rs->buf, wait_status);
5310 rs->cached_wait_status = 1;
5314 gdb_assert (wait_status == NULL);
5317 /* Implementation of the to_post_attach method. */
5320 extended_remote_post_attach (struct target_ops *ops, int pid)
5322 /* Get text, data & bss offsets. */
5325 /* In certain cases GDB might not have had the chance to start
5326 symbol lookup up until now. This could happen if the debugged
5327 binary is not using shared libraries, the vsyscall page is not
5328 present (on Linux) and the binary itself hadn't changed since the
5329 debugging process was started. */
5330 if (symfile_objfile != NULL)
5331 remote_check_symbols();
5335 /* Check for the availability of vCont. This function should also check
5339 remote_vcont_probe (struct remote_state *rs)
5343 strcpy (rs->buf, "vCont?");
5345 getpkt (&rs->buf, &rs->buf_size, 0);
5348 /* Make sure that the features we assume are supported. */
5349 if (startswith (buf, "vCont"))
5352 int support_c, support_C;
5354 rs->supports_vCont.s = 0;
5355 rs->supports_vCont.S = 0;
5358 rs->supports_vCont.t = 0;
5359 rs->supports_vCont.r = 0;
5360 while (p && *p == ';')
5363 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5364 rs->supports_vCont.s = 1;
5365 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5366 rs->supports_vCont.S = 1;
5367 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5369 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5371 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5372 rs->supports_vCont.t = 1;
5373 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5374 rs->supports_vCont.r = 1;
5376 p = strchr (p, ';');
5379 /* If c, and C are not all supported, we can't use vCont. Clearing
5380 BUF will make packet_ok disable the packet. */
5381 if (!support_c || !support_C)
5385 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5388 /* Helper function for building "vCont" resumptions. Write a
5389 resumption to P. ENDP points to one-passed-the-end of the buffer
5390 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5391 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5392 resumed thread should be single-stepped and/or signalled. If PTID
5393 equals minus_one_ptid, then all threads are resumed; if PTID
5394 represents a process, then all threads of the process are resumed;
5395 the thread to be stepped and/or signalled is given in the global
5399 append_resumption (char *p, char *endp,
5400 ptid_t ptid, int step, enum gdb_signal siggnal)
5402 struct remote_state *rs = get_remote_state ();
5404 if (step && siggnal != GDB_SIGNAL_0)
5405 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5407 /* GDB is willing to range step. */
5408 && use_range_stepping
5409 /* Target supports range stepping. */
5410 && rs->supports_vCont.r
5411 /* We don't currently support range stepping multiple
5412 threads with a wildcard (though the protocol allows it,
5413 so stubs shouldn't make an active effort to forbid
5415 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5417 struct thread_info *tp;
5419 if (ptid_equal (ptid, minus_one_ptid))
5421 /* If we don't know about the target thread's tid, then
5422 we're resuming magic_null_ptid (see caller). */
5423 tp = find_thread_ptid (magic_null_ptid);
5426 tp = find_thread_ptid (ptid);
5427 gdb_assert (tp != NULL);
5429 if (tp->control.may_range_step)
5431 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5433 p += xsnprintf (p, endp - p, ";r%s,%s",
5434 phex_nz (tp->control.step_range_start,
5436 phex_nz (tp->control.step_range_end,
5440 p += xsnprintf (p, endp - p, ";s");
5443 p += xsnprintf (p, endp - p, ";s");
5444 else if (siggnal != GDB_SIGNAL_0)
5445 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5447 p += xsnprintf (p, endp - p, ";c");
5449 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5453 /* All (-1) threads of process. */
5454 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5456 p += xsnprintf (p, endp - p, ":");
5457 p = write_ptid (p, endp, nptid);
5459 else if (!ptid_equal (ptid, minus_one_ptid))
5461 p += xsnprintf (p, endp - p, ":");
5462 p = write_ptid (p, endp, ptid);
5468 /* Clear the thread's private info on resume. */
5471 resume_clear_thread_private_info (struct thread_info *thread)
5473 if (thread->priv != NULL)
5475 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5476 thread->priv->watch_data_address = 0;
5480 /* Append a vCont continue-with-signal action for threads that have a
5481 non-zero stop signal. */
5484 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5486 struct thread_info *thread;
5488 ALL_NON_EXITED_THREADS (thread)
5489 if (ptid_match (thread->ptid, ptid)
5490 && !ptid_equal (inferior_ptid, thread->ptid)
5491 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5493 p = append_resumption (p, endp, thread->ptid,
5494 0, thread->suspend.stop_signal);
5495 thread->suspend.stop_signal = GDB_SIGNAL_0;
5496 resume_clear_thread_private_info (thread);
5502 /* Resume the remote inferior by using a "vCont" packet. The thread
5503 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5504 resumed thread should be single-stepped and/or signalled. If PTID
5505 equals minus_one_ptid, then all threads are resumed; the thread to
5506 be stepped and/or signalled is given in the global INFERIOR_PTID.
5507 This function returns non-zero iff it resumes the inferior.
5509 This function issues a strict subset of all possible vCont commands at the
5513 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5515 struct remote_state *rs = get_remote_state ();
5519 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5520 remote_vcont_probe (rs);
5522 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5526 endp = rs->buf + get_remote_packet_size ();
5528 /* If we could generate a wider range of packets, we'd have to worry
5529 about overflowing BUF. Should there be a generic
5530 "multi-part-packet" packet? */
5532 p += xsnprintf (p, endp - p, "vCont");
5534 if (ptid_equal (ptid, magic_null_ptid))
5536 /* MAGIC_NULL_PTID means that we don't have any active threads,
5537 so we don't have any TID numbers the inferior will
5538 understand. Make sure to only send forms that do not specify
5540 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5542 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5544 /* Resume all threads (of all processes, or of a single
5545 process), with preference for INFERIOR_PTID. This assumes
5546 inferior_ptid belongs to the set of all threads we are about
5548 if (step || siggnal != GDB_SIGNAL_0)
5550 /* Step inferior_ptid, with or without signal. */
5551 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5554 /* Also pass down any pending signaled resumption for other
5555 threads not the current. */
5556 p = append_pending_thread_resumptions (p, endp, ptid);
5558 /* And continue others without a signal. */
5559 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5563 /* Scheduler locking; resume only PTID. */
5564 append_resumption (p, endp, ptid, step, siggnal);
5567 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5570 if (target_is_non_stop_p ())
5572 /* In non-stop, the stub replies to vCont with "OK". The stop
5573 reply will be reported asynchronously by means of a `%Stop'
5575 getpkt (&rs->buf, &rs->buf_size, 0);
5576 if (strcmp (rs->buf, "OK") != 0)
5577 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5583 /* Tell the remote machine to resume. */
5586 remote_resume (struct target_ops *ops,
5587 ptid_t ptid, int step, enum gdb_signal siggnal)
5589 struct remote_state *rs = get_remote_state ();
5591 struct thread_info *thread;
5593 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5594 (explained in remote-notif.c:handle_notification) so
5595 remote_notif_process is not called. We need find a place where
5596 it is safe to start a 'vNotif' sequence. It is good to do it
5597 before resuming inferior, because inferior was stopped and no RSP
5598 traffic at that moment. */
5599 if (!target_is_non_stop_p ())
5600 remote_notif_process (rs->notif_state, ¬if_client_stop);
5602 rs->last_sent_signal = siggnal;
5603 rs->last_sent_step = step;
5605 /* The vCont packet doesn't need to specify threads via Hc. */
5606 /* No reverse support (yet) for vCont. */
5607 if (execution_direction != EXEC_REVERSE)
5608 if (remote_vcont_resume (ptid, step, siggnal))
5611 /* All other supported resume packets do use Hc, so set the continue
5613 if (ptid_equal (ptid, minus_one_ptid))
5614 set_continue_thread (any_thread_ptid);
5616 set_continue_thread (ptid);
5618 ALL_NON_EXITED_THREADS (thread)
5619 resume_clear_thread_private_info (thread);
5622 if (execution_direction == EXEC_REVERSE)
5624 /* We don't pass signals to the target in reverse exec mode. */
5625 if (info_verbose && siggnal != GDB_SIGNAL_0)
5626 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5629 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5630 error (_("Remote reverse-step not supported."));
5631 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5632 error (_("Remote reverse-continue not supported."));
5634 strcpy (buf, step ? "bs" : "bc");
5636 else if (siggnal != GDB_SIGNAL_0)
5638 buf[0] = step ? 'S' : 'C';
5639 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5640 buf[2] = tohex (((int) siggnal) & 0xf);
5644 strcpy (buf, step ? "s" : "c");
5649 /* We are about to start executing the inferior, let's register it
5650 with the event loop. NOTE: this is the one place where all the
5651 execution commands end up. We could alternatively do this in each
5652 of the execution commands in infcmd.c. */
5653 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5654 into infcmd.c in order to allow inferior function calls to work
5655 NOT asynchronously. */
5656 if (target_can_async_p ())
5659 /* We've just told the target to resume. The remote server will
5660 wait for the inferior to stop, and then send a stop reply. In
5661 the mean time, we can't start another command/query ourselves
5662 because the stub wouldn't be ready to process it. This applies
5663 only to the base all-stop protocol, however. In non-stop (which
5664 only supports vCont), the stub replies with an "OK", and is
5665 immediate able to process further serial input. */
5666 if (!target_is_non_stop_p ())
5667 rs->waiting_for_stop_reply = 1;
5671 /* Set up the signal handler for SIGINT, while the target is
5672 executing, ovewriting the 'regular' SIGINT signal handler. */
5674 async_initialize_sigint_signal_handler (void)
5676 signal (SIGINT, async_handle_remote_sigint);
5679 /* Signal handler for SIGINT, while the target is executing. */
5681 async_handle_remote_sigint (int sig)
5683 signal (sig, async_handle_remote_sigint_twice);
5684 /* Note we need to go through gdb_call_async_signal_handler in order
5685 to wake up the event loop on Windows. */
5686 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5689 /* Signal handler for SIGINT, installed after SIGINT has already been
5690 sent once. It will take effect the second time that the user sends
5693 async_handle_remote_sigint_twice (int sig)
5695 signal (sig, async_handle_remote_sigint);
5696 /* See note in async_handle_remote_sigint. */
5697 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5700 /* Implementation of to_check_pending_interrupt. */
5703 remote_check_pending_interrupt (struct target_ops *self)
5705 struct async_signal_handler *token = async_sigint_remote_twice_token;
5707 if (async_signal_handler_is_marked (token))
5709 clear_async_signal_handler (token);
5710 call_async_signal_handler (token);
5714 /* Perform the real interruption of the target execution, in response
5717 async_remote_interrupt (gdb_client_data arg)
5720 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5722 target_interrupt (inferior_ptid);
5725 /* Perform interrupt, if the first attempt did not succeed. Just give
5726 up on the target alltogether. */
5728 async_remote_interrupt_twice (gdb_client_data arg)
5731 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5736 /* Reinstall the usual SIGINT handlers, after the target has
5739 async_cleanup_sigint_signal_handler (void *dummy)
5741 signal (SIGINT, handle_sigint);
5744 /* Send ^C to target to halt it. Target will respond, and send us a
5746 static void (*ofunc) (int);
5748 /* The command line interface's interrupt routine. This function is installed
5749 as a signal handler for SIGINT. The first time a user requests an
5750 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5751 response from the target (it didn't stop when the user requested it),
5752 we ask the user if he'd like to detach from the target. */
5755 sync_remote_interrupt (int signo)
5757 /* If this doesn't work, try more severe steps. */
5758 signal (signo, sync_remote_interrupt_twice);
5760 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5763 /* The user typed ^C twice. */
5766 sync_remote_interrupt_twice (int signo)
5768 signal (signo, ofunc);
5769 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5770 signal (signo, sync_remote_interrupt);
5773 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5774 thread, all threads of a remote process, or all threads of all
5778 remote_stop_ns (ptid_t ptid)
5780 struct remote_state *rs = get_remote_state ();
5782 char *endp = rs->buf + get_remote_packet_size ();
5784 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5785 remote_vcont_probe (rs);
5787 if (!rs->supports_vCont.t)
5788 error (_("Remote server does not support stopping threads"));
5790 if (ptid_equal (ptid, minus_one_ptid)
5791 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5792 p += xsnprintf (p, endp - p, "vCont;t");
5797 p += xsnprintf (p, endp - p, "vCont;t:");
5799 if (ptid_is_pid (ptid))
5800 /* All (-1) threads of process. */
5801 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5804 /* Small optimization: if we already have a stop reply for
5805 this thread, no use in telling the stub we want this
5807 if (peek_stop_reply (ptid))
5813 write_ptid (p, endp, nptid);
5816 /* In non-stop, we get an immediate OK reply. The stop reply will
5817 come in asynchronously by notification. */
5819 getpkt (&rs->buf, &rs->buf_size, 0);
5820 if (strcmp (rs->buf, "OK") != 0)
5821 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5824 /* All-stop version of target_interrupt. Sends a break or a ^C to
5825 interrupt the remote target. It is undefined which thread of which
5826 process reports the interrupt. */
5829 remote_interrupt_as (void)
5831 struct remote_state *rs = get_remote_state ();
5833 rs->ctrlc_pending_p = 1;
5835 /* If the inferior is stopped already, but the core didn't know
5836 about it yet, just ignore the request. The cached wait status
5837 will be collected in remote_wait. */
5838 if (rs->cached_wait_status)
5841 /* Send interrupt_sequence to remote target. */
5842 send_interrupt_sequence ();
5845 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5846 the remote target. It is undefined which thread of which process
5847 reports the interrupt. Returns true if the packet is supported by
5848 the server, false otherwise. */
5851 remote_interrupt_ns (void)
5853 struct remote_state *rs = get_remote_state ();
5855 char *endp = rs->buf + get_remote_packet_size ();
5857 xsnprintf (p, endp - p, "vCtrlC");
5859 /* In non-stop, we get an immediate OK reply. The stop reply will
5860 come in asynchronously by notification. */
5862 getpkt (&rs->buf, &rs->buf_size, 0);
5864 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5868 case PACKET_UNKNOWN:
5871 error (_("Interrupting target failed: %s"), rs->buf);
5877 /* Implement the to_stop function for the remote targets. */
5880 remote_stop (struct target_ops *self, ptid_t ptid)
5883 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5885 if (target_is_non_stop_p ())
5886 remote_stop_ns (ptid);
5889 /* We don't currently have a way to transparently pause the
5890 remote target in all-stop mode. Interrupt it instead. */
5891 remote_interrupt_as ();
5895 /* Implement the to_interrupt function for the remote targets. */
5898 remote_interrupt (struct target_ops *self, ptid_t ptid)
5901 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5905 /* In non-stop mode, we always stop with no signal instead. */
5906 remote_stop_ns (ptid);
5910 /* In all-stop, we emulate ^C-ing the remote target's
5912 if (target_is_non_stop_p ())
5914 if (!remote_interrupt_ns ())
5916 /* No support for ^C-ing the remote target. Stop it
5917 (with no signal) instead. */
5918 remote_stop_ns (ptid);
5922 remote_interrupt_as ();
5926 /* Ask the user what to do when an interrupt is received. */
5929 interrupt_query (void)
5931 struct remote_state *rs = get_remote_state ();
5932 struct cleanup *old_chain;
5934 old_chain = make_cleanup_restore_target_terminal ();
5935 target_terminal_ours ();
5937 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5939 if (query (_("The target is not responding to interrupt requests.\n"
5940 "Stop debugging it? ")))
5942 remote_unpush_target ();
5943 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5948 if (query (_("Interrupted while waiting for the program.\n"
5949 "Give up waiting? ")))
5953 do_cleanups (old_chain);
5956 /* Enable/disable target terminal ownership. Most targets can use
5957 terminal groups to control terminal ownership. Remote targets are
5958 different in that explicit transfer of ownership to/from GDB/target
5962 remote_terminal_inferior (struct target_ops *self)
5964 if (!target_async_permitted)
5965 /* Nothing to do. */
5968 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5969 idempotent. The event-loop GDB talking to an asynchronous target
5970 with a synchronous command calls this function from both
5971 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5972 transfer the terminal to the target when it shouldn't this guard
5974 if (!remote_async_terminal_ours_p)
5976 delete_file_handler (input_fd);
5977 remote_async_terminal_ours_p = 0;
5978 async_initialize_sigint_signal_handler ();
5979 /* NOTE: At this point we could also register our selves as the
5980 recipient of all input. Any characters typed could then be
5981 passed on down to the target. */
5985 remote_terminal_ours (struct target_ops *self)
5987 if (!target_async_permitted)
5988 /* Nothing to do. */
5991 /* See FIXME in remote_terminal_inferior. */
5992 if (remote_async_terminal_ours_p)
5994 async_cleanup_sigint_signal_handler (NULL);
5995 add_file_handler (input_fd, stdin_event_handler, 0);
5996 remote_async_terminal_ours_p = 1;
6000 remote_console_output (char *msg)
6004 for (p = msg; p[0] && p[1]; p += 2)
6007 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6011 fputs_unfiltered (tb, gdb_stdtarg);
6013 gdb_flush (gdb_stdtarg);
6016 typedef struct cached_reg
6019 gdb_byte data[MAX_REGISTER_SIZE];
6022 DEF_VEC_O(cached_reg_t);
6024 typedef struct stop_reply
6026 struct notif_event base;
6028 /* The identifier of the thread about this event */
6031 /* The remote state this event is associated with. When the remote
6032 connection, represented by a remote_state object, is closed,
6033 all the associated stop_reply events should be released. */
6034 struct remote_state *rs;
6036 struct target_waitstatus ws;
6038 /* Expedited registers. This makes remote debugging a bit more
6039 efficient for those targets that provide critical registers as
6040 part of their normal status mechanism (as another roundtrip to
6041 fetch them is avoided). */
6042 VEC(cached_reg_t) *regcache;
6044 enum target_stop_reason stop_reason;
6046 CORE_ADDR watch_data_address;
6051 DECLARE_QUEUE_P (stop_reply_p);
6052 DEFINE_QUEUE_P (stop_reply_p);
6053 /* The list of already fetched and acknowledged stop events. This
6054 queue is used for notification Stop, and other notifications
6055 don't need queue for their events, because the notification events
6056 of Stop can't be consumed immediately, so that events should be
6057 queued first, and be consumed by remote_wait_{ns,as} one per
6058 time. Other notifications can consume their events immediately,
6059 so queue is not needed for them. */
6060 static QUEUE (stop_reply_p) *stop_reply_queue;
6063 stop_reply_xfree (struct stop_reply *r)
6065 notif_event_xfree ((struct notif_event *) r);
6068 /* Return the length of the stop reply queue. */
6071 stop_reply_queue_length (void)
6073 return QUEUE_length (stop_reply_p, stop_reply_queue);
6077 remote_notif_stop_parse (struct notif_client *self, char *buf,
6078 struct notif_event *event)
6080 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6084 remote_notif_stop_ack (struct notif_client *self, char *buf,
6085 struct notif_event *event)
6087 struct stop_reply *stop_reply = (struct stop_reply *) event;
6090 putpkt ((char *) self->ack_command);
6092 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6093 /* We got an unknown stop reply. */
6094 error (_("Unknown stop reply"));
6096 push_stop_reply (stop_reply);
6100 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6102 /* We can't get pending events in remote_notif_process for
6103 notification stop, and we have to do this in remote_wait_ns
6104 instead. If we fetch all queued events from stub, remote stub
6105 may exit and we have no chance to process them back in
6107 mark_async_event_handler (remote_async_inferior_event_token);
6112 stop_reply_dtr (struct notif_event *event)
6114 struct stop_reply *r = (struct stop_reply *) event;
6116 VEC_free (cached_reg_t, r->regcache);
6119 static struct notif_event *
6120 remote_notif_stop_alloc_reply (void)
6122 /* We cast to a pointer to the "base class". */
6123 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6125 r->dtr = stop_reply_dtr;
6130 /* A client of notification Stop. */
6132 struct notif_client notif_client_stop =
6136 remote_notif_stop_parse,
6137 remote_notif_stop_ack,
6138 remote_notif_stop_can_get_pending_events,
6139 remote_notif_stop_alloc_reply,
6143 /* A parameter to pass data in and out. */
6145 struct queue_iter_param
6148 struct stop_reply *output;
6151 /* Determine if THREAD is a pending fork parent thread. ARG contains
6152 the pid of the process that owns the threads we want to check, or
6153 -1 if we want to check all threads. */
6156 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6159 if (ws->kind == TARGET_WAITKIND_FORKED
6160 || ws->kind == TARGET_WAITKIND_VFORKED)
6162 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6169 /* Check whether EVENT is a fork event, and if it is, remove the
6170 fork child from the context list passed in DATA. */
6173 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6174 QUEUE_ITER (stop_reply_p) *iter,
6178 struct queue_iter_param *param = (struct queue_iter_param *) data;
6179 struct threads_listing_context *context
6180 = (struct threads_listing_context *) param->input;
6182 if (event->ws.kind == TARGET_WAITKIND_FORKED
6183 || event->ws.kind == TARGET_WAITKIND_VFORKED
6184 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6185 threads_listing_context_remove (&event->ws, context);
6190 /* If CONTEXT contains any fork child threads that have not been
6191 reported yet, remove them from the CONTEXT list. If such a
6192 thread exists it is because we are stopped at a fork catchpoint
6193 and have not yet called follow_fork, which will set up the
6194 host-side data structures for the new process. */
6197 remove_new_fork_children (struct threads_listing_context *context)
6199 struct thread_info * thread;
6201 struct notif_client *notif = ¬if_client_stop;
6202 struct queue_iter_param param;
6204 /* For any threads stopped at a fork event, remove the corresponding
6205 fork child threads from the CONTEXT list. */
6206 ALL_NON_EXITED_THREADS (thread)
6208 struct target_waitstatus *ws;
6210 if (thread->suspend.waitstatus_pending_p)
6211 ws = &thread->suspend.waitstatus;
6213 ws = &thread->pending_follow;
6215 if (is_pending_fork_parent (ws, pid, thread->ptid))
6217 threads_listing_context_remove (ws, context);
6221 /* Check for any pending fork events (not reported or processed yet)
6222 in process PID and remove those fork child threads from the
6223 CONTEXT list as well. */
6224 remote_notif_get_pending_events (notif);
6225 param.input = context;
6226 param.output = NULL;
6227 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6228 remove_child_of_pending_fork, ¶m);
6231 /* Remove stop replies in the queue if its pid is equal to the given
6235 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6236 QUEUE_ITER (stop_reply_p) *iter,
6240 struct queue_iter_param *param = (struct queue_iter_param *) data;
6241 struct inferior *inf = (struct inferior *) param->input;
6243 if (ptid_get_pid (event->ptid) == inf->pid)
6245 stop_reply_xfree (event);
6246 QUEUE_remove_elem (stop_reply_p, q, iter);
6252 /* Discard all pending stop replies of inferior INF. */
6255 discard_pending_stop_replies (struct inferior *inf)
6257 struct queue_iter_param param;
6258 struct stop_reply *reply;
6259 struct remote_state *rs = get_remote_state ();
6260 struct remote_notif_state *rns = rs->notif_state;
6262 /* This function can be notified when an inferior exists. When the
6263 target is not remote, the notification state is NULL. */
6264 if (rs->remote_desc == NULL)
6267 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6269 /* Discard the in-flight notification. */
6270 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6272 stop_reply_xfree (reply);
6273 rns->pending_event[notif_client_stop.id] = NULL;
6277 param.output = NULL;
6278 /* Discard the stop replies we have already pulled with
6280 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6281 remove_stop_reply_for_inferior, ¶m);
6284 /* If its remote state is equal to the given remote state,
6285 remove EVENT from the stop reply queue. */
6288 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6289 QUEUE_ITER (stop_reply_p) *iter,
6293 struct queue_iter_param *param = (struct queue_iter_param *) data;
6294 struct remote_state *rs = (struct remote_state *) param->input;
6296 if (event->rs == rs)
6298 stop_reply_xfree (event);
6299 QUEUE_remove_elem (stop_reply_p, q, iter);
6305 /* Discard the stop replies for RS in stop_reply_queue. */
6308 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6310 struct queue_iter_param param;
6313 param.output = NULL;
6314 /* Discard the stop replies we have already pulled with
6316 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6317 remove_stop_reply_of_remote_state, ¶m);
6320 /* A parameter to pass data in and out. */
6323 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6324 QUEUE_ITER (stop_reply_p) *iter,
6328 struct queue_iter_param *param = (struct queue_iter_param *) data;
6329 ptid_t *ptid = (ptid_t *) param->input;
6331 if (ptid_match (event->ptid, *ptid))
6333 param->output = event;
6334 QUEUE_remove_elem (stop_reply_p, q, iter);
6341 /* Remove the first reply in 'stop_reply_queue' which matches
6344 static struct stop_reply *
6345 remote_notif_remove_queued_reply (ptid_t ptid)
6347 struct queue_iter_param param;
6349 param.input = &ptid;
6350 param.output = NULL;
6352 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6353 remote_notif_remove_once_on_match, ¶m);
6355 fprintf_unfiltered (gdb_stdlog,
6356 "notif: discard queued event: 'Stop' in %s\n",
6357 target_pid_to_str (ptid));
6359 return param.output;
6362 /* Look for a queued stop reply belonging to PTID. If one is found,
6363 remove it from the queue, and return it. Returns NULL if none is
6364 found. If there are still queued events left to process, tell the
6365 event loop to get back to target_wait soon. */
6367 static struct stop_reply *
6368 queued_stop_reply (ptid_t ptid)
6370 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6372 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6373 /* There's still at least an event left. */
6374 mark_async_event_handler (remote_async_inferior_event_token);
6379 /* Push a fully parsed stop reply in the stop reply queue. Since we
6380 know that we now have at least one queued event left to pass to the
6381 core side, tell the event loop to get back to target_wait soon. */
6384 push_stop_reply (struct stop_reply *new_event)
6386 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6389 fprintf_unfiltered (gdb_stdlog,
6390 "notif: push 'Stop' %s to queue %d\n",
6391 target_pid_to_str (new_event->ptid),
6392 QUEUE_length (stop_reply_p,
6395 mark_async_event_handler (remote_async_inferior_event_token);
6399 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6400 QUEUE_ITER (stop_reply_p) *iter,
6401 struct stop_reply *event,
6404 ptid_t *ptid = (ptid_t *) data;
6406 return !(ptid_equal (*ptid, event->ptid)
6407 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6410 /* Returns true if we have a stop reply for PTID. */
6413 peek_stop_reply (ptid_t ptid)
6415 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6416 stop_reply_match_ptid_and_ws, &ptid);
6419 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6420 starting with P and ending with PEND matches PREFIX. */
6423 strprefix (const char *p, const char *pend, const char *prefix)
6425 for ( ; p < pend; p++, prefix++)
6428 return *prefix == '\0';
6431 /* Parse the stop reply in BUF. Either the function succeeds, and the
6432 result is stored in EVENT, or throws an error. */
6435 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6437 struct remote_arch_state *rsa = get_remote_arch_state ();
6442 event->ptid = null_ptid;
6443 event->rs = get_remote_state ();
6444 event->ws.kind = TARGET_WAITKIND_IGNORE;
6445 event->ws.value.integer = 0;
6446 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6447 event->regcache = NULL;
6452 case 'T': /* Status with PC, SP, FP, ... */
6453 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6454 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6456 n... = register number
6457 r... = register contents
6460 p = &buf[3]; /* after Txx */
6466 p1 = strchr (p, ':');
6468 error (_("Malformed packet(a) (missing colon): %s\n\
6472 error (_("Malformed packet(a) (missing register number): %s\n\
6476 /* Some "registers" are actually extended stop information.
6477 Note if you're adding a new entry here: GDB 7.9 and
6478 earlier assume that all register "numbers" that start
6479 with an hex digit are real register numbers. Make sure
6480 the server only sends such a packet if it knows the
6481 client understands it. */
6483 if (strprefix (p, p1, "thread"))
6484 event->ptid = read_ptid (++p1, &p);
6485 else if (strprefix (p, p1, "syscall_entry"))
6489 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6490 p = unpack_varlen_hex (++p1, &sysno);
6491 event->ws.value.syscall_number = (int) sysno;
6493 else if (strprefix (p, p1, "syscall_return"))
6497 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6498 p = unpack_varlen_hex (++p1, &sysno);
6499 event->ws.value.syscall_number = (int) sysno;
6501 else if (strprefix (p, p1, "watch")
6502 || strprefix (p, p1, "rwatch")
6503 || strprefix (p, p1, "awatch"))
6505 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6506 p = unpack_varlen_hex (++p1, &addr);
6507 event->watch_data_address = (CORE_ADDR) addr;
6509 else if (strprefix (p, p1, "swbreak"))
6511 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6513 /* Make sure the stub doesn't forget to indicate support
6515 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6516 error (_("Unexpected swbreak stop reason"));
6518 /* The value part is documented as "must be empty",
6519 though we ignore it, in case we ever decide to make
6520 use of it in a backward compatible way. */
6521 p = strchrnul (p1 + 1, ';');
6523 else if (strprefix (p, p1, "hwbreak"))
6525 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6527 /* Make sure the stub doesn't forget to indicate support
6529 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6530 error (_("Unexpected hwbreak stop reason"));
6533 p = strchrnul (p1 + 1, ';');
6535 else if (strprefix (p, p1, "library"))
6537 event->ws.kind = TARGET_WAITKIND_LOADED;
6538 p = strchrnul (p1 + 1, ';');
6540 else if (strprefix (p, p1, "replaylog"))
6542 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6543 /* p1 will indicate "begin" or "end", but it makes
6544 no difference for now, so ignore it. */
6545 p = strchrnul (p1 + 1, ';');
6547 else if (strprefix (p, p1, "core"))
6551 p = unpack_varlen_hex (++p1, &c);
6554 else if (strprefix (p, p1, "fork"))
6556 event->ws.value.related_pid = read_ptid (++p1, &p);
6557 event->ws.kind = TARGET_WAITKIND_FORKED;
6559 else if (strprefix (p, p1, "vfork"))
6561 event->ws.value.related_pid = read_ptid (++p1, &p);
6562 event->ws.kind = TARGET_WAITKIND_VFORKED;
6564 else if (strprefix (p, p1, "vforkdone"))
6566 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6567 p = strchrnul (p1 + 1, ';');
6569 else if (strprefix (p, p1, "exec"))
6572 char pathname[PATH_MAX];
6575 /* Determine the length of the execd pathname. */
6576 p = unpack_varlen_hex (++p1, &ignored);
6577 pathlen = (p - p1) / 2;
6579 /* Save the pathname for event reporting and for
6580 the next run command. */
6581 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6582 pathname[pathlen] = '\0';
6584 /* This is freed during event handling. */
6585 event->ws.value.execd_pathname = xstrdup (pathname);
6586 event->ws.kind = TARGET_WAITKIND_EXECD;
6588 /* Skip the registers included in this packet, since
6589 they may be for an architecture different from the
6590 one used by the original program. */
6593 else if (strprefix (p, p1, "create"))
6595 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6596 p = strchrnul (p1 + 1, ';');
6605 p = strchrnul (p1 + 1, ';');
6610 /* Maybe a real ``P'' register number. */
6611 p_temp = unpack_varlen_hex (p, &pnum);
6612 /* If the first invalid character is the colon, we got a
6613 register number. Otherwise, it's an unknown stop
6617 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6618 cached_reg_t cached_reg;
6621 error (_("Remote sent bad register number %s: %s\n\
6623 hex_string (pnum), p, buf);
6625 cached_reg.num = reg->regnum;
6628 fieldsize = hex2bin (p, cached_reg.data,
6629 register_size (target_gdbarch (),
6632 if (fieldsize < register_size (target_gdbarch (),
6634 warning (_("Remote reply is too short: %s"), buf);
6636 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6640 /* Not a number. Silently skip unknown optional
6642 p = strchrnul (p1 + 1, ';');
6647 error (_("Remote register badly formatted: %s\nhere: %s"),
6652 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6656 case 'S': /* Old style status, just signal only. */
6660 event->ws.kind = TARGET_WAITKIND_STOPPED;
6661 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6662 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6663 event->ws.value.sig = (enum gdb_signal) sig;
6665 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6668 case 'w': /* Thread exited. */
6673 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6674 p = unpack_varlen_hex (&buf[1], &value);
6675 event->ws.value.integer = value;
6677 error (_("stop reply packet badly formatted: %s"), buf);
6678 event->ptid = read_ptid (++p, NULL);
6681 case 'W': /* Target exited. */
6688 /* GDB used to accept only 2 hex chars here. Stubs should
6689 only send more if they detect GDB supports multi-process
6691 p = unpack_varlen_hex (&buf[1], &value);
6695 /* The remote process exited. */
6696 event->ws.kind = TARGET_WAITKIND_EXITED;
6697 event->ws.value.integer = value;
6701 /* The remote process exited with a signal. */
6702 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6703 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6704 event->ws.value.sig = (enum gdb_signal) value;
6706 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6709 /* If no process is specified, assume inferior_ptid. */
6710 pid = ptid_get_pid (inferior_ptid);
6719 else if (startswith (p, "process:"))
6723 p += sizeof ("process:") - 1;
6724 unpack_varlen_hex (p, &upid);
6728 error (_("unknown stop reply packet: %s"), buf);
6731 error (_("unknown stop reply packet: %s"), buf);
6732 event->ptid = pid_to_ptid (pid);
6736 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6737 event->ptid = minus_one_ptid;
6741 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6742 error (_("No process or thread specified in stop reply: %s"), buf);
6745 /* When the stub wants to tell GDB about a new notification reply, it
6746 sends a notification (%Stop, for example). Those can come it at
6747 any time, hence, we have to make sure that any pending
6748 putpkt/getpkt sequence we're making is finished, before querying
6749 the stub for more events with the corresponding ack command
6750 (vStopped, for example). E.g., if we started a vStopped sequence
6751 immediately upon receiving the notification, something like this
6759 1.6) <-- (registers reply to step #1.3)
6761 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6764 To solve this, whenever we parse a %Stop notification successfully,
6765 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6766 doing whatever we were doing:
6772 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6773 2.5) <-- (registers reply to step #2.3)
6775 Eventualy after step #2.5, we return to the event loop, which
6776 notices there's an event on the
6777 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6778 associated callback --- the function below. At this point, we're
6779 always safe to start a vStopped sequence. :
6782 2.7) <-- T05 thread:2
6788 remote_notif_get_pending_events (struct notif_client *nc)
6790 struct remote_state *rs = get_remote_state ();
6792 if (rs->notif_state->pending_event[nc->id] != NULL)
6795 fprintf_unfiltered (gdb_stdlog,
6796 "notif: process: '%s' ack pending event\n",
6800 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6801 rs->notif_state->pending_event[nc->id] = NULL;
6805 getpkt (&rs->buf, &rs->buf_size, 0);
6806 if (strcmp (rs->buf, "OK") == 0)
6809 remote_notif_ack (nc, rs->buf);
6815 fprintf_unfiltered (gdb_stdlog,
6816 "notif: process: '%s' no pending reply\n",
6821 /* Called when it is decided that STOP_REPLY holds the info of the
6822 event that is to be returned to the core. This function always
6823 destroys STOP_REPLY. */
6826 process_stop_reply (struct stop_reply *stop_reply,
6827 struct target_waitstatus *status)
6831 *status = stop_reply->ws;
6832 ptid = stop_reply->ptid;
6834 /* If no thread/process was reported by the stub, assume the current
6836 if (ptid_equal (ptid, null_ptid))
6837 ptid = inferior_ptid;
6839 if (status->kind != TARGET_WAITKIND_EXITED
6840 && status->kind != TARGET_WAITKIND_SIGNALLED
6841 && status->kind != TARGET_WAITKIND_NO_RESUMED)
6843 struct private_thread_info *remote_thr;
6845 /* Expedited registers. */
6846 if (stop_reply->regcache)
6848 struct regcache *regcache
6849 = get_thread_arch_regcache (ptid, target_gdbarch ());
6854 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6856 regcache_raw_supply (regcache, reg->num, reg->data);
6857 VEC_free (cached_reg_t, stop_reply->regcache);
6860 remote_notice_new_inferior (ptid, 0);
6861 remote_thr = demand_private_info (ptid);
6862 remote_thr->core = stop_reply->core;
6863 remote_thr->stop_reason = stop_reply->stop_reason;
6864 remote_thr->watch_data_address = stop_reply->watch_data_address;
6867 stop_reply_xfree (stop_reply);
6871 /* The non-stop mode version of target_wait. */
6874 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6876 struct remote_state *rs = get_remote_state ();
6877 struct stop_reply *stop_reply;
6881 /* If in non-stop mode, get out of getpkt even if a
6882 notification is received. */
6884 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6885 0 /* forever */, &is_notif);
6888 if (ret != -1 && !is_notif)
6891 case 'E': /* Error of some sort. */
6892 /* We're out of sync with the target now. Did it continue
6893 or not? We can't tell which thread it was in non-stop,
6894 so just ignore this. */
6895 warning (_("Remote failure reply: %s"), rs->buf);
6897 case 'O': /* Console output. */
6898 remote_console_output (rs->buf + 1);
6901 warning (_("Invalid remote reply: %s"), rs->buf);
6905 /* Acknowledge a pending stop reply that may have arrived in the
6907 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6908 remote_notif_get_pending_events (¬if_client_stop);
6910 /* If indeed we noticed a stop reply, we're done. */
6911 stop_reply = queued_stop_reply (ptid);
6912 if (stop_reply != NULL)
6913 return process_stop_reply (stop_reply, status);
6915 /* Still no event. If we're just polling for an event, then
6916 return to the event loop. */
6917 if (options & TARGET_WNOHANG)
6919 status->kind = TARGET_WAITKIND_IGNORE;
6920 return minus_one_ptid;
6923 /* Otherwise do a blocking wait. */
6924 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6925 1 /* forever */, &is_notif);
6929 /* Wait until the remote machine stops, then return, storing status in
6930 STATUS just as `wait' would. */
6933 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6935 struct remote_state *rs = get_remote_state ();
6936 ptid_t event_ptid = null_ptid;
6938 struct stop_reply *stop_reply;
6942 status->kind = TARGET_WAITKIND_IGNORE;
6943 status->value.integer = 0;
6945 stop_reply = queued_stop_reply (ptid);
6946 if (stop_reply != NULL)
6947 return process_stop_reply (stop_reply, status);
6949 if (rs->cached_wait_status)
6950 /* Use the cached wait status, but only once. */
6951 rs->cached_wait_status = 0;
6956 int forever = ((options & TARGET_WNOHANG) == 0
6957 && wait_forever_enabled_p);
6959 if (!rs->waiting_for_stop_reply)
6961 status->kind = TARGET_WAITKIND_NO_RESUMED;
6962 return minus_one_ptid;
6965 if (!target_is_async_p ())
6967 ofunc = signal (SIGINT, sync_remote_interrupt);
6968 /* If the user hit C-c before this packet, or between packets,
6969 pretend that it was hit right here. */
6970 if (check_quit_flag ())
6973 sync_remote_interrupt (SIGINT);
6977 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6978 _never_ wait for ever -> test on target_is_async_p().
6979 However, before we do that we need to ensure that the caller
6980 knows how to take the target into/out of async mode. */
6981 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6982 forever, &is_notif);
6984 if (!target_is_async_p ())
6985 signal (SIGINT, ofunc);
6987 /* GDB gets a notification. Return to core as this event is
6989 if (ret != -1 && is_notif)
6990 return minus_one_ptid;
6992 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6993 return minus_one_ptid;
6998 /* Assume that the target has acknowledged Ctrl-C unless we receive
6999 an 'F' or 'O' packet. */
7000 if (buf[0] != 'F' && buf[0] != 'O')
7001 rs->ctrlc_pending_p = 0;
7005 case 'E': /* Error of some sort. */
7006 /* We're out of sync with the target now. Did it continue or
7007 not? Not is more likely, so report a stop. */
7008 rs->waiting_for_stop_reply = 0;
7010 warning (_("Remote failure reply: %s"), buf);
7011 status->kind = TARGET_WAITKIND_STOPPED;
7012 status->value.sig = GDB_SIGNAL_0;
7014 case 'F': /* File-I/O request. */
7015 /* GDB may access the inferior memory while handling the File-I/O
7016 request, but we don't want GDB accessing memory while waiting
7017 for a stop reply. See the comments in putpkt_binary. Set
7018 waiting_for_stop_reply to 0 temporarily. */
7019 rs->waiting_for_stop_reply = 0;
7020 remote_fileio_request (buf, rs->ctrlc_pending_p);
7021 rs->ctrlc_pending_p = 0;
7022 /* GDB handled the File-I/O request, and the target is running
7023 again. Keep waiting for events. */
7024 rs->waiting_for_stop_reply = 1;
7026 case 'N': case 'T': case 'S': case 'X': case 'W':
7028 struct stop_reply *stop_reply;
7030 /* There is a stop reply to handle. */
7031 rs->waiting_for_stop_reply = 0;
7034 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
7037 event_ptid = process_stop_reply (stop_reply, status);
7040 case 'O': /* Console output. */
7041 remote_console_output (buf + 1);
7044 if (rs->last_sent_signal != GDB_SIGNAL_0)
7046 /* Zero length reply means that we tried 'S' or 'C' and the
7047 remote system doesn't support it. */
7048 target_terminal_ours_for_output ();
7050 ("Can't send signals to this remote system. %s not sent.\n",
7051 gdb_signal_to_name (rs->last_sent_signal));
7052 rs->last_sent_signal = GDB_SIGNAL_0;
7053 target_terminal_inferior ();
7055 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
7056 putpkt ((char *) buf);
7059 /* else fallthrough */
7061 warning (_("Invalid remote reply: %s"), buf);
7065 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7066 return minus_one_ptid;
7067 else if (status->kind == TARGET_WAITKIND_IGNORE)
7069 /* Nothing interesting happened. If we're doing a non-blocking
7070 poll, we're done. Otherwise, go back to waiting. */
7071 if (options & TARGET_WNOHANG)
7072 return minus_one_ptid;
7076 else if (status->kind != TARGET_WAITKIND_EXITED
7077 && status->kind != TARGET_WAITKIND_SIGNALLED)
7079 if (!ptid_equal (event_ptid, null_ptid))
7080 record_currthread (rs, event_ptid);
7082 event_ptid = inferior_ptid;
7085 /* A process exit. Invalidate our notion of current thread. */
7086 record_currthread (rs, minus_one_ptid);
7091 /* Wait until the remote machine stops, then return, storing status in
7092 STATUS just as `wait' would. */
7095 remote_wait (struct target_ops *ops,
7096 ptid_t ptid, struct target_waitstatus *status, int options)
7100 if (target_is_non_stop_p ())
7101 event_ptid = remote_wait_ns (ptid, status, options);
7103 event_ptid = remote_wait_as (ptid, status, options);
7105 if (target_is_async_p ())
7107 /* If there are are events left in the queue tell the event loop
7109 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7110 mark_async_event_handler (remote_async_inferior_event_token);
7116 /* Fetch a single register using a 'p' packet. */
7119 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7121 struct remote_state *rs = get_remote_state ();
7123 char regp[MAX_REGISTER_SIZE];
7126 if (packet_support (PACKET_p) == PACKET_DISABLE)
7129 if (reg->pnum == -1)
7134 p += hexnumstr (p, reg->pnum);
7137 getpkt (&rs->buf, &rs->buf_size, 0);
7141 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7145 case PACKET_UNKNOWN:
7148 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7149 gdbarch_register_name (get_regcache_arch (regcache),
7154 /* If this register is unfetchable, tell the regcache. */
7157 regcache_raw_supply (regcache, reg->regnum, NULL);
7161 /* Otherwise, parse and supply the value. */
7167 error (_("fetch_register_using_p: early buf termination"));
7169 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7172 regcache_raw_supply (regcache, reg->regnum, regp);
7176 /* Fetch the registers included in the target's 'g' packet. */
7179 send_g_packet (void)
7181 struct remote_state *rs = get_remote_state ();
7184 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7185 remote_send (&rs->buf, &rs->buf_size);
7187 /* We can get out of synch in various cases. If the first character
7188 in the buffer is not a hex character, assume that has happened
7189 and try to fetch another packet to read. */
7190 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7191 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7192 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7193 && rs->buf[0] != 'x') /* New: unavailable register value. */
7196 fprintf_unfiltered (gdb_stdlog,
7197 "Bad register packet; fetching a new packet\n");
7198 getpkt (&rs->buf, &rs->buf_size, 0);
7201 buf_len = strlen (rs->buf);
7203 /* Sanity check the received packet. */
7204 if (buf_len % 2 != 0)
7205 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7211 process_g_packet (struct regcache *regcache)
7213 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7214 struct remote_state *rs = get_remote_state ();
7215 struct remote_arch_state *rsa = get_remote_arch_state ();
7220 buf_len = strlen (rs->buf);
7222 /* Further sanity checks, with knowledge of the architecture. */
7223 if (buf_len > 2 * rsa->sizeof_g_packet)
7224 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7226 /* Save the size of the packet sent to us by the target. It is used
7227 as a heuristic when determining the max size of packets that the
7228 target can safely receive. */
7229 if (rsa->actual_register_packet_size == 0)
7230 rsa->actual_register_packet_size = buf_len;
7232 /* If this is smaller than we guessed the 'g' packet would be,
7233 update our records. A 'g' reply that doesn't include a register's
7234 value implies either that the register is not available, or that
7235 the 'p' packet must be used. */
7236 if (buf_len < 2 * rsa->sizeof_g_packet)
7238 rsa->sizeof_g_packet = buf_len / 2;
7240 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7242 if (rsa->regs[i].pnum == -1)
7245 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7246 rsa->regs[i].in_g_packet = 0;
7248 rsa->regs[i].in_g_packet = 1;
7252 regs = (char *) alloca (rsa->sizeof_g_packet);
7254 /* Unimplemented registers read as all bits zero. */
7255 memset (regs, 0, rsa->sizeof_g_packet);
7257 /* Reply describes registers byte by byte, each byte encoded as two
7258 hex characters. Suck them all up, then supply them to the
7259 register cacheing/storage mechanism. */
7262 for (i = 0; i < rsa->sizeof_g_packet; i++)
7264 if (p[0] == 0 || p[1] == 0)
7265 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7266 internal_error (__FILE__, __LINE__,
7267 _("unexpected end of 'g' packet reply"));
7269 if (p[0] == 'x' && p[1] == 'x')
7270 regs[i] = 0; /* 'x' */
7272 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7276 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7278 struct packet_reg *r = &rsa->regs[i];
7282 if (r->offset * 2 >= strlen (rs->buf))
7283 /* This shouldn't happen - we adjusted in_g_packet above. */
7284 internal_error (__FILE__, __LINE__,
7285 _("unexpected end of 'g' packet reply"));
7286 else if (rs->buf[r->offset * 2] == 'x')
7288 gdb_assert (r->offset * 2 < strlen (rs->buf));
7289 /* The register isn't available, mark it as such (at
7290 the same time setting the value to zero). */
7291 regcache_raw_supply (regcache, r->regnum, NULL);
7294 regcache_raw_supply (regcache, r->regnum,
7301 fetch_registers_using_g (struct regcache *regcache)
7304 process_g_packet (regcache);
7307 /* Make the remote selected traceframe match GDB's selected
7311 set_remote_traceframe (void)
7314 struct remote_state *rs = get_remote_state ();
7316 if (rs->remote_traceframe_number == get_traceframe_number ())
7319 /* Avoid recursion, remote_trace_find calls us again. */
7320 rs->remote_traceframe_number = get_traceframe_number ();
7322 newnum = target_trace_find (tfind_number,
7323 get_traceframe_number (), 0, 0, NULL);
7325 /* Should not happen. If it does, all bets are off. */
7326 if (newnum != get_traceframe_number ())
7327 warning (_("could not set remote traceframe"));
7331 remote_fetch_registers (struct target_ops *ops,
7332 struct regcache *regcache, int regnum)
7334 struct remote_arch_state *rsa = get_remote_arch_state ();
7337 set_remote_traceframe ();
7338 set_general_thread (inferior_ptid);
7342 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7344 gdb_assert (reg != NULL);
7346 /* If this register might be in the 'g' packet, try that first -
7347 we are likely to read more than one register. If this is the
7348 first 'g' packet, we might be overly optimistic about its
7349 contents, so fall back to 'p'. */
7350 if (reg->in_g_packet)
7352 fetch_registers_using_g (regcache);
7353 if (reg->in_g_packet)
7357 if (fetch_register_using_p (regcache, reg))
7360 /* This register is not available. */
7361 regcache_raw_supply (regcache, reg->regnum, NULL);
7366 fetch_registers_using_g (regcache);
7368 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7369 if (!rsa->regs[i].in_g_packet)
7370 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7372 /* This register is not available. */
7373 regcache_raw_supply (regcache, i, NULL);
7377 /* Prepare to store registers. Since we may send them all (using a
7378 'G' request), we have to read out the ones we don't want to change
7382 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7384 struct remote_arch_state *rsa = get_remote_arch_state ();
7386 gdb_byte buf[MAX_REGISTER_SIZE];
7388 /* Make sure the entire registers array is valid. */
7389 switch (packet_support (PACKET_P))
7391 case PACKET_DISABLE:
7392 case PACKET_SUPPORT_UNKNOWN:
7393 /* Make sure all the necessary registers are cached. */
7394 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7395 if (rsa->regs[i].in_g_packet)
7396 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7403 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7404 packet was not recognized. */
7407 store_register_using_P (const struct regcache *regcache,
7408 struct packet_reg *reg)
7410 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7411 struct remote_state *rs = get_remote_state ();
7412 /* Try storing a single register. */
7413 char *buf = rs->buf;
7414 gdb_byte regp[MAX_REGISTER_SIZE];
7417 if (packet_support (PACKET_P) == PACKET_DISABLE)
7420 if (reg->pnum == -1)
7423 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7424 p = buf + strlen (buf);
7425 regcache_raw_collect (regcache, reg->regnum, regp);
7426 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7428 getpkt (&rs->buf, &rs->buf_size, 0);
7430 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7435 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7436 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7437 case PACKET_UNKNOWN:
7440 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7444 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7445 contents of the register cache buffer. FIXME: ignores errors. */
7448 store_registers_using_G (const struct regcache *regcache)
7450 struct remote_state *rs = get_remote_state ();
7451 struct remote_arch_state *rsa = get_remote_arch_state ();
7455 /* Extract all the registers in the regcache copying them into a
7460 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7461 memset (regs, 0, rsa->sizeof_g_packet);
7462 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7464 struct packet_reg *r = &rsa->regs[i];
7467 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7471 /* Command describes registers byte by byte,
7472 each byte encoded as two hex characters. */
7475 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7477 bin2hex (regs, p, rsa->sizeof_g_packet);
7479 getpkt (&rs->buf, &rs->buf_size, 0);
7480 if (packet_check_result (rs->buf) == PACKET_ERROR)
7481 error (_("Could not write registers; remote failure reply '%s'"),
7485 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7486 of the register cache buffer. FIXME: ignores errors. */
7489 remote_store_registers (struct target_ops *ops,
7490 struct regcache *regcache, int regnum)
7492 struct remote_arch_state *rsa = get_remote_arch_state ();
7495 set_remote_traceframe ();
7496 set_general_thread (inferior_ptid);
7500 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7502 gdb_assert (reg != NULL);
7504 /* Always prefer to store registers using the 'P' packet if
7505 possible; we often change only a small number of registers.
7506 Sometimes we change a larger number; we'd need help from a
7507 higher layer to know to use 'G'. */
7508 if (store_register_using_P (regcache, reg))
7511 /* For now, don't complain if we have no way to write the
7512 register. GDB loses track of unavailable registers too
7513 easily. Some day, this may be an error. We don't have
7514 any way to read the register, either... */
7515 if (!reg->in_g_packet)
7518 store_registers_using_G (regcache);
7522 store_registers_using_G (regcache);
7524 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7525 if (!rsa->regs[i].in_g_packet)
7526 if (!store_register_using_P (regcache, &rsa->regs[i]))
7527 /* See above for why we do not issue an error here. */
7532 /* Return the number of hex digits in num. */
7535 hexnumlen (ULONGEST num)
7539 for (i = 0; num != 0; i++)
7545 /* Set BUF to the minimum number of hex digits representing NUM. */
7548 hexnumstr (char *buf, ULONGEST num)
7550 int len = hexnumlen (num);
7552 return hexnumnstr (buf, num, len);
7556 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7559 hexnumnstr (char *buf, ULONGEST num, int width)
7565 for (i = width - 1; i >= 0; i--)
7567 buf[i] = "0123456789abcdef"[(num & 0xf)];
7574 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7577 remote_address_masked (CORE_ADDR addr)
7579 unsigned int address_size = remote_address_size;
7581 /* If "remoteaddresssize" was not set, default to target address size. */
7583 address_size = gdbarch_addr_bit (target_gdbarch ());
7585 if (address_size > 0
7586 && address_size < (sizeof (ULONGEST) * 8))
7588 /* Only create a mask when that mask can safely be constructed
7589 in a ULONGEST variable. */
7592 mask = (mask << address_size) - 1;
7598 /* Determine whether the remote target supports binary downloading.
7599 This is accomplished by sending a no-op memory write of zero length
7600 to the target at the specified address. It does not suffice to send
7601 the whole packet, since many stubs strip the eighth bit and
7602 subsequently compute a wrong checksum, which causes real havoc with
7605 NOTE: This can still lose if the serial line is not eight-bit
7606 clean. In cases like this, the user should clear "remote
7610 check_binary_download (CORE_ADDR addr)
7612 struct remote_state *rs = get_remote_state ();
7614 switch (packet_support (PACKET_X))
7616 case PACKET_DISABLE:
7620 case PACKET_SUPPORT_UNKNOWN:
7626 p += hexnumstr (p, (ULONGEST) addr);
7628 p += hexnumstr (p, (ULONGEST) 0);
7632 putpkt_binary (rs->buf, (int) (p - rs->buf));
7633 getpkt (&rs->buf, &rs->buf_size, 0);
7635 if (rs->buf[0] == '\0')
7638 fprintf_unfiltered (gdb_stdlog,
7639 "binary downloading NOT "
7640 "supported by target\n");
7641 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7646 fprintf_unfiltered (gdb_stdlog,
7647 "binary downloading supported by target\n");
7648 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7655 /* Helper function to resize the payload in order to try to get a good
7656 alignment. We try to write an amount of data such that the next write will
7657 start on an address aligned on REMOTE_ALIGN_WRITES. */
7660 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7662 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7665 /* Write memory data directly to the remote machine.
7666 This does not inform the data cache; the data cache uses this.
7667 HEADER is the starting part of the packet.
7668 MEMADDR is the address in the remote memory space.
7669 MYADDR is the address of the buffer in our space.
7670 LEN_UNITS is the number of addressable units to write.
7671 UNIT_SIZE is the length in bytes of an addressable unit.
7672 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7673 should send data as binary ('X'), or hex-encoded ('M').
7675 The function creates packet of the form
7676 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7678 where encoding of <DATA> is terminated by PACKET_FORMAT.
7680 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7683 Return the transferred status, error or OK (an
7684 'enum target_xfer_status' value). Save the number of addressable units
7685 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7687 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7688 exchange between gdb and the stub could look like (?? in place of the
7694 -> $M1000,3:eeeeffffeeee#??
7698 <- eeeeffffeeeedddd */
7700 static enum target_xfer_status
7701 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7702 const gdb_byte *myaddr, ULONGEST len_units,
7703 int unit_size, ULONGEST *xfered_len_units,
7704 char packet_format, int use_length)
7706 struct remote_state *rs = get_remote_state ();
7712 int payload_capacity_bytes;
7713 int payload_length_bytes;
7715 if (packet_format != 'X' && packet_format != 'M')
7716 internal_error (__FILE__, __LINE__,
7717 _("remote_write_bytes_aux: bad packet format"));
7720 return TARGET_XFER_EOF;
7722 payload_capacity_bytes = get_memory_write_packet_size ();
7724 /* The packet buffer will be large enough for the payload;
7725 get_memory_packet_size ensures this. */
7728 /* Compute the size of the actual payload by subtracting out the
7729 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7731 payload_capacity_bytes -= strlen ("$,:#NN");
7733 /* The comma won't be used. */
7734 payload_capacity_bytes += 1;
7735 payload_capacity_bytes -= strlen (header);
7736 payload_capacity_bytes -= hexnumlen (memaddr);
7738 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7740 strcat (rs->buf, header);
7741 p = rs->buf + strlen (header);
7743 /* Compute a best guess of the number of bytes actually transfered. */
7744 if (packet_format == 'X')
7746 /* Best guess at number of bytes that will fit. */
7747 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7749 payload_capacity_bytes -= hexnumlen (todo_units);
7750 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7754 /* Number of bytes that will fit. */
7755 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7757 payload_capacity_bytes -= hexnumlen (todo_units);
7758 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7761 if (todo_units <= 0)
7762 internal_error (__FILE__, __LINE__,
7763 _("minimum packet size too small to write data"));
7765 /* If we already need another packet, then try to align the end
7766 of this packet to a useful boundary. */
7767 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7768 todo_units = align_for_efficient_write (todo_units, memaddr);
7770 /* Append "<memaddr>". */
7771 memaddr = remote_address_masked (memaddr);
7772 p += hexnumstr (p, (ULONGEST) memaddr);
7779 /* Append the length and retain its location and size. It may need to be
7780 adjusted once the packet body has been created. */
7782 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7790 /* Append the packet body. */
7791 if (packet_format == 'X')
7793 /* Binary mode. Send target system values byte by byte, in
7794 increasing byte addresses. Only escape certain critical
7796 payload_length_bytes =
7797 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7798 &units_written, payload_capacity_bytes);
7800 /* If not all TODO units fit, then we'll need another packet. Make
7801 a second try to keep the end of the packet aligned. Don't do
7802 this if the packet is tiny. */
7803 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7807 new_todo_units = align_for_efficient_write (units_written, memaddr);
7809 if (new_todo_units != units_written)
7810 payload_length_bytes =
7811 remote_escape_output (myaddr, new_todo_units, unit_size,
7812 (gdb_byte *) p, &units_written,
7813 payload_capacity_bytes);
7816 p += payload_length_bytes;
7817 if (use_length && units_written < todo_units)
7819 /* Escape chars have filled up the buffer prematurely,
7820 and we have actually sent fewer units than planned.
7821 Fix-up the length field of the packet. Use the same
7822 number of characters as before. */
7823 plen += hexnumnstr (plen, (ULONGEST) units_written,
7825 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7830 /* Normal mode: Send target system values byte by byte, in
7831 increasing byte addresses. Each byte is encoded as a two hex
7833 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7834 units_written = todo_units;
7837 putpkt_binary (rs->buf, (int) (p - rs->buf));
7838 getpkt (&rs->buf, &rs->buf_size, 0);
7840 if (rs->buf[0] == 'E')
7841 return TARGET_XFER_E_IO;
7843 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7844 send fewer units than we'd planned. */
7845 *xfered_len_units = (ULONGEST) units_written;
7846 return TARGET_XFER_OK;
7849 /* Write memory data directly to the remote machine.
7850 This does not inform the data cache; the data cache uses this.
7851 MEMADDR is the address in the remote memory space.
7852 MYADDR is the address of the buffer in our space.
7853 LEN is the number of bytes.
7855 Return the transferred status, error or OK (an
7856 'enum target_xfer_status' value). Save the number of bytes
7857 transferred in *XFERED_LEN. Only transfer a single packet. */
7859 static enum target_xfer_status
7860 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7861 int unit_size, ULONGEST *xfered_len)
7863 char *packet_format = 0;
7865 /* Check whether the target supports binary download. */
7866 check_binary_download (memaddr);
7868 switch (packet_support (PACKET_X))
7871 packet_format = "X";
7873 case PACKET_DISABLE:
7874 packet_format = "M";
7876 case PACKET_SUPPORT_UNKNOWN:
7877 internal_error (__FILE__, __LINE__,
7878 _("remote_write_bytes: bad internal state"));
7880 internal_error (__FILE__, __LINE__, _("bad switch"));
7883 return remote_write_bytes_aux (packet_format,
7884 memaddr, myaddr, len, unit_size, xfered_len,
7885 packet_format[0], 1);
7888 /* Read memory data directly from the remote machine.
7889 This does not use the data cache; the data cache uses this.
7890 MEMADDR is the address in the remote memory space.
7891 MYADDR is the address of the buffer in our space.
7892 LEN_UNITS is the number of addressable memory units to read..
7893 UNIT_SIZE is the length in bytes of an addressable unit.
7895 Return the transferred status, error or OK (an
7896 'enum target_xfer_status' value). Save the number of bytes
7897 transferred in *XFERED_LEN_UNITS.
7899 See the comment of remote_write_bytes_aux for an example of
7900 memory read/write exchange between gdb and the stub. */
7902 static enum target_xfer_status
7903 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7904 int unit_size, ULONGEST *xfered_len_units)
7906 struct remote_state *rs = get_remote_state ();
7907 int buf_size_bytes; /* Max size of packet output buffer. */
7912 buf_size_bytes = get_memory_read_packet_size ();
7913 /* The packet buffer will be large enough for the payload;
7914 get_memory_packet_size ensures this. */
7916 /* Number of units that will fit. */
7917 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7919 /* Construct "m"<memaddr>","<len>". */
7920 memaddr = remote_address_masked (memaddr);
7923 p += hexnumstr (p, (ULONGEST) memaddr);
7925 p += hexnumstr (p, (ULONGEST) todo_units);
7928 getpkt (&rs->buf, &rs->buf_size, 0);
7929 if (rs->buf[0] == 'E'
7930 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7931 && rs->buf[3] == '\0')
7932 return TARGET_XFER_E_IO;
7933 /* Reply describes memory byte by byte, each byte encoded as two hex
7936 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7937 /* Return what we have. Let higher layers handle partial reads. */
7938 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7939 return TARGET_XFER_OK;
7942 /* Using the set of read-only target sections of remote, read live
7945 For interface/parameters/return description see target.h,
7948 static enum target_xfer_status
7949 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7950 ULONGEST memaddr, ULONGEST len,
7951 int unit_size, ULONGEST *xfered_len)
7953 struct target_section *secp;
7954 struct target_section_table *table;
7956 secp = target_section_by_addr (ops, memaddr);
7958 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7959 secp->the_bfd_section)
7962 struct target_section *p;
7963 ULONGEST memend = memaddr + len;
7965 table = target_get_section_table (ops);
7967 for (p = table->sections; p < table->sections_end; p++)
7969 if (memaddr >= p->addr)
7971 if (memend <= p->endaddr)
7973 /* Entire transfer is within this section. */
7974 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7977 else if (memaddr >= p->endaddr)
7979 /* This section ends before the transfer starts. */
7984 /* This section overlaps the transfer. Just do half. */
7985 len = p->endaddr - memaddr;
7986 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7993 return TARGET_XFER_EOF;
7996 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7997 first if the requested memory is unavailable in traceframe.
7998 Otherwise, fall back to remote_read_bytes_1. */
8000 static enum target_xfer_status
8001 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8002 gdb_byte *myaddr, ULONGEST len, int unit_size,
8003 ULONGEST *xfered_len)
8006 return TARGET_XFER_EOF;
8008 if (get_traceframe_number () != -1)
8010 VEC(mem_range_s) *available;
8012 /* If we fail to get the set of available memory, then the
8013 target does not support querying traceframe info, and so we
8014 attempt reading from the traceframe anyway (assuming the
8015 target implements the old QTro packet then). */
8016 if (traceframe_available_memory (&available, memaddr, len))
8018 struct cleanup *old_chain;
8020 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8022 if (VEC_empty (mem_range_s, available)
8023 || VEC_index (mem_range_s, available, 0)->start != memaddr)
8025 enum target_xfer_status res;
8027 /* Don't read into the traceframe's available
8029 if (!VEC_empty (mem_range_s, available))
8031 LONGEST oldlen = len;
8033 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8034 gdb_assert (len <= oldlen);
8037 do_cleanups (old_chain);
8039 /* This goes through the topmost target again. */
8040 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8041 len, unit_size, xfered_len);
8042 if (res == TARGET_XFER_OK)
8043 return TARGET_XFER_OK;
8046 /* No use trying further, we know some memory starting
8047 at MEMADDR isn't available. */
8049 return TARGET_XFER_UNAVAILABLE;
8053 /* Don't try to read more than how much is available, in
8054 case the target implements the deprecated QTro packet to
8055 cater for older GDBs (the target's knowledge of read-only
8056 sections may be outdated by now). */
8057 len = VEC_index (mem_range_s, available, 0)->length;
8059 do_cleanups (old_chain);
8063 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8068 /* Sends a packet with content determined by the printf format string
8069 FORMAT and the remaining arguments, then gets the reply. Returns
8070 whether the packet was a success, a failure, or unknown. */
8072 static enum packet_result remote_send_printf (const char *format, ...)
8073 ATTRIBUTE_PRINTF (1, 2);
8075 static enum packet_result
8076 remote_send_printf (const char *format, ...)
8078 struct remote_state *rs = get_remote_state ();
8079 int max_size = get_remote_packet_size ();
8082 va_start (ap, format);
8085 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8086 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8088 if (putpkt (rs->buf) < 0)
8089 error (_("Communication problem with target."));
8092 getpkt (&rs->buf, &rs->buf_size, 0);
8094 return packet_check_result (rs->buf);
8098 restore_remote_timeout (void *p)
8100 int value = *(int *)p;
8102 remote_timeout = value;
8105 /* Flash writing can take quite some time. We'll set
8106 effectively infinite timeout for flash operations.
8107 In future, we'll need to decide on a better approach. */
8108 static const int remote_flash_timeout = 1000;
8111 remote_flash_erase (struct target_ops *ops,
8112 ULONGEST address, LONGEST length)
8114 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8115 int saved_remote_timeout = remote_timeout;
8116 enum packet_result ret;
8117 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8118 &saved_remote_timeout);
8120 remote_timeout = remote_flash_timeout;
8122 ret = remote_send_printf ("vFlashErase:%s,%s",
8123 phex (address, addr_size),
8127 case PACKET_UNKNOWN:
8128 error (_("Remote target does not support flash erase"));
8130 error (_("Error erasing flash with vFlashErase packet"));
8135 do_cleanups (back_to);
8138 static enum target_xfer_status
8139 remote_flash_write (struct target_ops *ops, ULONGEST address,
8140 ULONGEST length, ULONGEST *xfered_len,
8141 const gdb_byte *data)
8143 int saved_remote_timeout = remote_timeout;
8144 enum target_xfer_status ret;
8145 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8146 &saved_remote_timeout);
8148 remote_timeout = remote_flash_timeout;
8149 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8151 do_cleanups (back_to);
8157 remote_flash_done (struct target_ops *ops)
8159 int saved_remote_timeout = remote_timeout;
8161 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8162 &saved_remote_timeout);
8164 remote_timeout = remote_flash_timeout;
8165 ret = remote_send_printf ("vFlashDone");
8166 do_cleanups (back_to);
8170 case PACKET_UNKNOWN:
8171 error (_("Remote target does not support vFlashDone"));
8173 error (_("Error finishing flash operation"));
8180 remote_files_info (struct target_ops *ignore)
8182 puts_filtered ("Debugging a target over a serial line.\n");
8185 /* Stuff for dealing with the packets which are part of this protocol.
8186 See comment at top of file for details. */
8188 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8189 error to higher layers. Called when a serial error is detected.
8190 The exception message is STRING, followed by a colon and a blank,
8191 the system error message for errno at function entry and final dot
8192 for output compatibility with throw_perror_with_name. */
8195 unpush_and_perror (const char *string)
8197 int saved_errno = errno;
8199 remote_unpush_target ();
8200 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8201 safe_strerror (saved_errno));
8204 /* Read a single character from the remote end. */
8207 readchar (int timeout)
8210 struct remote_state *rs = get_remote_state ();
8212 ch = serial_readchar (rs->remote_desc, timeout);
8217 switch ((enum serial_rc) ch)
8220 remote_unpush_target ();
8221 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8224 unpush_and_perror (_("Remote communication error. "
8225 "Target disconnected."));
8227 case SERIAL_TIMEOUT:
8233 /* Wrapper for serial_write that closes the target and throws if
8237 remote_serial_write (const char *str, int len)
8239 struct remote_state *rs = get_remote_state ();
8241 if (serial_write (rs->remote_desc, str, len))
8243 unpush_and_perror (_("Remote communication error. "
8244 "Target disconnected."));
8248 /* Send the command in *BUF to the remote machine, and read the reply
8249 into *BUF. Report an error if we get an error reply. Resize
8250 *BUF using xrealloc if necessary to hold the result, and update
8254 remote_send (char **buf,
8258 getpkt (buf, sizeof_buf, 0);
8260 if ((*buf)[0] == 'E')
8261 error (_("Remote failure reply: %s"), *buf);
8264 /* Return a pointer to an xmalloc'ed string representing an escaped
8265 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8266 etc. The caller is responsible for releasing the returned
8270 escape_buffer (const char *buf, int n)
8272 struct cleanup *old_chain;
8273 struct ui_file *stb;
8276 stb = mem_fileopen ();
8277 old_chain = make_cleanup_ui_file_delete (stb);
8279 fputstrn_unfiltered (buf, n, '\\', stb);
8280 str = ui_file_xstrdup (stb, NULL);
8281 do_cleanups (old_chain);
8285 /* Display a null-terminated packet on stdout, for debugging, using C
8289 print_packet (const char *buf)
8291 puts_filtered ("\"");
8292 fputstr_filtered (buf, '"', gdb_stdout);
8293 puts_filtered ("\"");
8297 putpkt (const char *buf)
8299 return putpkt_binary (buf, strlen (buf));
8302 /* Send a packet to the remote machine, with error checking. The data
8303 of the packet is in BUF. The string in BUF can be at most
8304 get_remote_packet_size () - 5 to account for the $, # and checksum,
8305 and for a possible /0 if we are debugging (remote_debug) and want
8306 to print the sent packet as a string. */
8309 putpkt_binary (const char *buf, int cnt)
8311 struct remote_state *rs = get_remote_state ();
8313 unsigned char csum = 0;
8314 char *buf2 = (char *) xmalloc (cnt + 6);
8315 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8321 /* Catch cases like trying to read memory or listing threads while
8322 we're waiting for a stop reply. The remote server wouldn't be
8323 ready to handle this request, so we'd hang and timeout. We don't
8324 have to worry about this in synchronous mode, because in that
8325 case it's not possible to issue a command while the target is
8326 running. This is not a problem in non-stop mode, because in that
8327 case, the stub is always ready to process serial input. */
8328 if (!target_is_non_stop_p ()
8329 && target_is_async_p ()
8330 && rs->waiting_for_stop_reply)
8332 error (_("Cannot execute this command while the target is running.\n"
8333 "Use the \"interrupt\" command to stop the target\n"
8334 "and then try again."));
8337 /* We're sending out a new packet. Make sure we don't look at a
8338 stale cached response. */
8339 rs->cached_wait_status = 0;
8341 /* Copy the packet into buffer BUF2, encapsulating it
8342 and giving it a checksum. */
8347 for (i = 0; i < cnt; i++)
8353 *p++ = tohex ((csum >> 4) & 0xf);
8354 *p++ = tohex (csum & 0xf);
8356 /* Send it over and over until we get a positive ack. */
8360 int started_error_output = 0;
8364 struct cleanup *old_chain;
8368 str = escape_buffer (buf2, p - buf2);
8369 old_chain = make_cleanup (xfree, str);
8370 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8371 gdb_flush (gdb_stdlog);
8372 do_cleanups (old_chain);
8374 remote_serial_write (buf2, p - buf2);
8376 /* If this is a no acks version of the remote protocol, send the
8377 packet and move on. */
8381 /* Read until either a timeout occurs (-2) or '+' is read.
8382 Handle any notification that arrives in the mean time. */
8385 ch = readchar (remote_timeout);
8393 case SERIAL_TIMEOUT:
8396 if (started_error_output)
8398 putchar_unfiltered ('\n');
8399 started_error_output = 0;
8408 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8409 do_cleanups (old_chain);
8413 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8415 case SERIAL_TIMEOUT:
8419 do_cleanups (old_chain);
8422 break; /* Retransmit buffer. */
8426 fprintf_unfiltered (gdb_stdlog,
8427 "Packet instead of Ack, ignoring it\n");
8428 /* It's probably an old response sent because an ACK
8429 was lost. Gobble up the packet and ack it so it
8430 doesn't get retransmitted when we resend this
8433 remote_serial_write ("+", 1);
8434 continue; /* Now, go look for +. */
8441 /* If we got a notification, handle it, and go back to looking
8443 /* We've found the start of a notification. Now
8444 collect the data. */
8445 val = read_frame (&rs->buf, &rs->buf_size);
8450 struct cleanup *old_chain;
8453 str = escape_buffer (rs->buf, val);
8454 old_chain = make_cleanup (xfree, str);
8455 fprintf_unfiltered (gdb_stdlog,
8456 " Notification received: %s\n",
8458 do_cleanups (old_chain);
8460 handle_notification (rs->notif_state, rs->buf);
8461 /* We're in sync now, rewait for the ack. */
8468 if (!started_error_output)
8470 started_error_output = 1;
8471 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8473 fputc_unfiltered (ch & 0177, gdb_stdlog);
8474 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8483 if (!started_error_output)
8485 started_error_output = 1;
8486 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8488 fputc_unfiltered (ch & 0177, gdb_stdlog);
8492 break; /* Here to retransmit. */
8496 /* This is wrong. If doing a long backtrace, the user should be
8497 able to get out next time we call QUIT, without anything as
8498 violent as interrupt_query. If we want to provide a way out of
8499 here without getting to the next QUIT, it should be based on
8500 hitting ^C twice as in remote_wait. */
8509 do_cleanups (old_chain);
8513 /* Come here after finding the start of a frame when we expected an
8514 ack. Do our best to discard the rest of this packet. */
8523 c = readchar (remote_timeout);
8526 case SERIAL_TIMEOUT:
8527 /* Nothing we can do. */
8530 /* Discard the two bytes of checksum and stop. */
8531 c = readchar (remote_timeout);
8533 c = readchar (remote_timeout);
8536 case '*': /* Run length encoding. */
8537 /* Discard the repeat count. */
8538 c = readchar (remote_timeout);
8543 /* A regular character. */
8549 /* Come here after finding the start of the frame. Collect the rest
8550 into *BUF, verifying the checksum, length, and handling run-length
8551 compression. NUL terminate the buffer. If there is not enough room,
8552 expand *BUF using xrealloc.
8554 Returns -1 on error, number of characters in buffer (ignoring the
8555 trailing NULL) on success. (could be extended to return one of the
8556 SERIAL status indications). */
8559 read_frame (char **buf_p,
8566 struct remote_state *rs = get_remote_state ();
8573 c = readchar (remote_timeout);
8576 case SERIAL_TIMEOUT:
8578 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8582 fputs_filtered ("Saw new packet start in middle of old one\n",
8584 return -1; /* Start a new packet, count retries. */
8587 unsigned char pktcsum;
8593 check_0 = readchar (remote_timeout);
8595 check_1 = readchar (remote_timeout);
8597 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8600 fputs_filtered ("Timeout in checksum, retrying\n",
8604 else if (check_0 < 0 || check_1 < 0)
8607 fputs_filtered ("Communication error in checksum\n",
8612 /* Don't recompute the checksum; with no ack packets we
8613 don't have any way to indicate a packet retransmission
8618 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8619 if (csum == pktcsum)
8624 struct cleanup *old_chain;
8627 str = escape_buffer (buf, bc);
8628 old_chain = make_cleanup (xfree, str);
8629 fprintf_unfiltered (gdb_stdlog,
8630 "Bad checksum, sentsum=0x%x, "
8631 "csum=0x%x, buf=%s\n",
8632 pktcsum, csum, str);
8633 do_cleanups (old_chain);
8635 /* Number of characters in buffer ignoring trailing
8639 case '*': /* Run length encoding. */
8644 c = readchar (remote_timeout);
8646 repeat = c - ' ' + 3; /* Compute repeat count. */
8648 /* The character before ``*'' is repeated. */
8650 if (repeat > 0 && repeat <= 255 && bc > 0)
8652 if (bc + repeat - 1 >= *sizeof_buf - 1)
8654 /* Make some more room in the buffer. */
8655 *sizeof_buf += repeat;
8656 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8660 memset (&buf[bc], buf[bc - 1], repeat);
8666 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8670 if (bc >= *sizeof_buf - 1)
8672 /* Make some more room in the buffer. */
8674 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8685 /* Read a packet from the remote machine, with error checking, and
8686 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8687 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8688 rather than timing out; this is used (in synchronous mode) to wait
8689 for a target that is is executing user code to stop. */
8690 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8691 don't have to change all the calls to getpkt to deal with the
8692 return value, because at the moment I don't know what the right
8693 thing to do it for those. */
8699 getpkt_sane (buf, sizeof_buf, forever);
8703 /* Read a packet from the remote machine, with error checking, and
8704 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8705 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8706 rather than timing out; this is used (in synchronous mode) to wait
8707 for a target that is is executing user code to stop. If FOREVER ==
8708 0, this function is allowed to time out gracefully and return an
8709 indication of this to the caller. Otherwise return the number of
8710 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8711 enough reason to return to the caller. *IS_NOTIF is an output
8712 boolean that indicates whether *BUF holds a notification or not
8713 (a regular packet). */
8716 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8717 int expecting_notif, int *is_notif)
8719 struct remote_state *rs = get_remote_state ();
8725 /* We're reading a new response. Make sure we don't look at a
8726 previously cached response. */
8727 rs->cached_wait_status = 0;
8729 strcpy (*buf, "timeout");
8732 timeout = watchdog > 0 ? watchdog : -1;
8733 else if (expecting_notif)
8734 timeout = 0; /* There should already be a char in the buffer. If
8737 timeout = remote_timeout;
8741 /* Process any number of notifications, and then return when
8745 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8747 for (tries = 1; tries <= MAX_TRIES; tries++)
8749 /* This can loop forever if the remote side sends us
8750 characters continuously, but if it pauses, we'll get
8751 SERIAL_TIMEOUT from readchar because of timeout. Then
8752 we'll count that as a retry.
8754 Note that even when forever is set, we will only wait
8755 forever prior to the start of a packet. After that, we
8756 expect characters to arrive at a brisk pace. They should
8757 show up within remote_timeout intervals. */
8759 c = readchar (timeout);
8760 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8762 if (c == SERIAL_TIMEOUT)
8764 if (expecting_notif)
8765 return -1; /* Don't complain, it's normal to not get
8766 anything in this case. */
8768 if (forever) /* Watchdog went off? Kill the target. */
8771 remote_unpush_target ();
8772 throw_error (TARGET_CLOSE_ERROR,
8773 _("Watchdog timeout has expired. "
8774 "Target detached."));
8777 fputs_filtered ("Timed out.\n", gdb_stdlog);
8781 /* We've found the start of a packet or notification.
8782 Now collect the data. */
8783 val = read_frame (buf, sizeof_buf);
8788 remote_serial_write ("-", 1);
8791 if (tries > MAX_TRIES)
8793 /* We have tried hard enough, and just can't receive the
8794 packet/notification. Give up. */
8795 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8797 /* Skip the ack char if we're in no-ack mode. */
8798 if (!rs->noack_mode)
8799 remote_serial_write ("+", 1);
8803 /* If we got an ordinary packet, return that to our caller. */
8808 struct cleanup *old_chain;
8811 str = escape_buffer (*buf, val);
8812 old_chain = make_cleanup (xfree, str);
8813 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8814 do_cleanups (old_chain);
8817 /* Skip the ack char if we're in no-ack mode. */
8818 if (!rs->noack_mode)
8819 remote_serial_write ("+", 1);
8820 if (is_notif != NULL)
8825 /* If we got a notification, handle it, and go back to looking
8829 gdb_assert (c == '%');
8833 struct cleanup *old_chain;
8836 str = escape_buffer (*buf, val);
8837 old_chain = make_cleanup (xfree, str);
8838 fprintf_unfiltered (gdb_stdlog,
8839 " Notification received: %s\n",
8841 do_cleanups (old_chain);
8843 if (is_notif != NULL)
8846 handle_notification (rs->notif_state, *buf);
8848 /* Notifications require no acknowledgement. */
8850 if (expecting_notif)
8857 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8859 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8863 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8866 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8870 /* Check whether EVENT is a fork event for the process specified
8871 by the pid passed in DATA, and if it is, kill the fork child. */
8874 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8875 QUEUE_ITER (stop_reply_p) *iter,
8879 struct queue_iter_param *param = (struct queue_iter_param *) data;
8880 int parent_pid = *(int *) param->input;
8882 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8884 struct remote_state *rs = get_remote_state ();
8885 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8888 res = remote_vkill (child_pid, rs);
8890 error (_("Can't kill fork child process %d"), child_pid);
8896 /* Kill any new fork children of process PID that haven't been
8897 processed by follow_fork. */
8900 kill_new_fork_children (int pid, struct remote_state *rs)
8902 struct thread_info *thread;
8903 struct notif_client *notif = ¬if_client_stop;
8904 struct queue_iter_param param;
8906 /* Kill the fork child threads of any threads in process PID
8907 that are stopped at a fork event. */
8908 ALL_NON_EXITED_THREADS (thread)
8910 struct target_waitstatus *ws = &thread->pending_follow;
8912 if (is_pending_fork_parent (ws, pid, thread->ptid))
8914 struct remote_state *rs = get_remote_state ();
8915 int child_pid = ptid_get_pid (ws->value.related_pid);
8918 res = remote_vkill (child_pid, rs);
8920 error (_("Can't kill fork child process %d"), child_pid);
8924 /* Check for any pending fork events (not reported or processed yet)
8925 in process PID and kill those fork child threads as well. */
8926 remote_notif_get_pending_events (notif);
8928 param.output = NULL;
8929 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8930 kill_child_of_pending_fork, ¶m);
8934 /* Target hook to kill the current inferior. */
8937 remote_kill (struct target_ops *ops)
8940 int pid = ptid_get_pid (inferior_ptid);
8941 struct remote_state *rs = get_remote_state ();
8943 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
8945 /* If we're stopped while forking and we haven't followed yet,
8946 kill the child task. We need to do this before killing the
8947 parent task because if this is a vfork then the parent will
8949 kill_new_fork_children (pid, rs);
8951 res = remote_vkill (pid, rs);
8954 target_mourn_inferior ();
8959 /* If we are in 'target remote' mode and we are killing the only
8960 inferior, then we will tell gdbserver to exit and unpush the
8962 if (res == -1 && !remote_multi_process_p (rs)
8963 && number_of_live_inferiors () == 1)
8967 /* We've killed the remote end, we get to mourn it. If we are
8968 not in extended mode, mourning the inferior also unpushes
8969 remote_ops from the target stack, which closes the remote
8971 target_mourn_inferior ();
8976 error (_("Can't kill process"));
8979 /* Send a kill request to the target using the 'vKill' packet. */
8982 remote_vkill (int pid, struct remote_state *rs)
8984 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8987 /* Tell the remote target to detach. */
8988 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8990 getpkt (&rs->buf, &rs->buf_size, 0);
8992 switch (packet_ok (rs->buf,
8993 &remote_protocol_packets[PACKET_vKill]))
8999 case PACKET_UNKNOWN:
9002 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9006 /* Send a kill request to the target using the 'k' packet. */
9009 remote_kill_k (void)
9011 /* Catch errors so the user can quit from gdb even when we
9012 aren't on speaking terms with the remote system. */
9017 CATCH (ex, RETURN_MASK_ERROR)
9019 if (ex.error == TARGET_CLOSE_ERROR)
9021 /* If we got an (EOF) error that caused the target
9022 to go away, then we're done, that's what we wanted.
9023 "k" is susceptible to cause a premature EOF, given
9024 that the remote server isn't actually required to
9025 reply to "k", and it can happen that it doesn't
9026 even get to reply ACK to the "k". */
9030 /* Otherwise, something went wrong. We didn't actually kill
9031 the target. Just propagate the exception, and let the
9032 user or higher layers decide what to do. */
9033 throw_exception (ex);
9039 remote_mourn (struct target_ops *target)
9041 struct remote_state *rs = get_remote_state ();
9043 /* In 'target remote' mode with one inferior, we close the connection. */
9044 if (!rs->extended && number_of_live_inferiors () <= 1)
9046 unpush_target (target);
9048 /* remote_close takes care of doing most of the clean up. */
9049 generic_mourn_inferior ();
9053 /* In case we got here due to an error, but we're going to stay
9055 rs->waiting_for_stop_reply = 0;
9057 /* If the current general thread belonged to the process we just
9058 detached from or has exited, the remote side current general
9059 thread becomes undefined. Considering a case like this:
9061 - We just got here due to a detach.
9062 - The process that we're detaching from happens to immediately
9063 report a global breakpoint being hit in non-stop mode, in the
9064 same thread we had selected before.
9065 - GDB attaches to this process again.
9066 - This event happens to be the next event we handle.
9068 GDB would consider that the current general thread didn't need to
9069 be set on the stub side (with Hg), since for all it knew,
9070 GENERAL_THREAD hadn't changed.
9072 Notice that although in all-stop mode, the remote server always
9073 sets the current thread to the thread reporting the stop event,
9074 that doesn't happen in non-stop mode; in non-stop, the stub *must
9075 not* change the current thread when reporting a breakpoint hit,
9076 due to the decoupling of event reporting and event handling.
9078 To keep things simple, we always invalidate our notion of the
9080 record_currthread (rs, minus_one_ptid);
9082 /* Call common code to mark the inferior as not running. */
9083 generic_mourn_inferior ();
9085 if (!have_inferiors ())
9087 if (!remote_multi_process_p (rs))
9089 /* Check whether the target is running now - some remote stubs
9090 automatically restart after kill. */
9092 getpkt (&rs->buf, &rs->buf_size, 0);
9094 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9096 /* Assume that the target has been restarted. Set
9097 inferior_ptid so that bits of core GDB realizes
9098 there's something here, e.g., so that the user can
9099 say "kill" again. */
9100 inferior_ptid = magic_null_ptid;
9107 extended_remote_supports_disable_randomization (struct target_ops *self)
9109 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9113 extended_remote_disable_randomization (int val)
9115 struct remote_state *rs = get_remote_state ();
9118 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9121 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9123 error (_("Target does not support QDisableRandomization."));
9124 if (strcmp (reply, "OK") != 0)
9125 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9129 extended_remote_run (char *args)
9131 struct remote_state *rs = get_remote_state ();
9133 const char *remote_exec_file = get_remote_exec_file ();
9135 /* If the user has disabled vRun support, or we have detected that
9136 support is not available, do not try it. */
9137 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9140 strcpy (rs->buf, "vRun;");
9141 len = strlen (rs->buf);
9143 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9144 error (_("Remote file name too long for run packet"));
9145 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9146 strlen (remote_exec_file));
9148 gdb_assert (args != NULL);
9151 struct cleanup *back_to;
9155 argv = gdb_buildargv (args);
9156 back_to = make_cleanup_freeargv (argv);
9157 for (i = 0; argv[i] != NULL; i++)
9159 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9160 error (_("Argument list too long for run packet"));
9161 rs->buf[len++] = ';';
9162 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9165 do_cleanups (back_to);
9168 rs->buf[len++] = '\0';
9171 getpkt (&rs->buf, &rs->buf_size, 0);
9173 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9176 /* We have a wait response. All is well. */
9178 case PACKET_UNKNOWN:
9181 if (remote_exec_file[0] == '\0')
9182 error (_("Running the default executable on the remote target failed; "
9183 "try \"set remote exec-file\"?"));
9185 error (_("Running \"%s\" on the remote target failed"),
9188 gdb_assert_not_reached (_("bad switch"));
9192 /* In the extended protocol we want to be able to do things like
9193 "run" and have them basically work as expected. So we need
9194 a special create_inferior function. We support changing the
9195 executable file and the command line arguments, but not the
9199 extended_remote_create_inferior (struct target_ops *ops,
9200 char *exec_file, char *args,
9201 char **env, int from_tty)
9205 struct remote_state *rs = get_remote_state ();
9206 const char *remote_exec_file = get_remote_exec_file ();
9208 /* If running asynchronously, register the target file descriptor
9209 with the event loop. */
9210 if (target_can_async_p ())
9213 /* Disable address space randomization if requested (and supported). */
9214 if (extended_remote_supports_disable_randomization (ops))
9215 extended_remote_disable_randomization (disable_randomization);
9217 /* Now restart the remote server. */
9218 run_worked = extended_remote_run (args) != -1;
9221 /* vRun was not supported. Fail if we need it to do what the
9223 if (remote_exec_file[0])
9224 error (_("Remote target does not support \"set remote exec-file\""));
9226 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9228 /* Fall back to "R". */
9229 extended_remote_restart ();
9232 if (!have_inferiors ())
9234 /* Clean up from the last time we ran, before we mark the target
9235 running again. This will mark breakpoints uninserted, and
9236 get_offsets may insert breakpoints. */
9237 init_thread_list ();
9238 init_wait_for_inferior ();
9241 /* vRun's success return is a stop reply. */
9242 stop_reply = run_worked ? rs->buf : NULL;
9243 add_current_inferior_and_thread (stop_reply);
9245 /* Get updated offsets, if the stub uses qOffsets. */
9250 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9251 the list of conditions (in agent expression bytecode format), if any, the
9252 target needs to evaluate. The output is placed into the packet buffer
9253 started from BUF and ended at BUF_END. */
9256 remote_add_target_side_condition (struct gdbarch *gdbarch,
9257 struct bp_target_info *bp_tgt, char *buf,
9260 struct agent_expr *aexpr = NULL;
9263 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9266 buf += strlen (buf);
9267 xsnprintf (buf, buf_end - buf, "%s", ";");
9270 /* Send conditions to the target and free the vector. */
9272 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9275 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9276 buf += strlen (buf);
9277 for (i = 0; i < aexpr->len; ++i)
9278 buf = pack_hex_byte (buf, aexpr->buf[i]);
9285 remote_add_target_side_commands (struct gdbarch *gdbarch,
9286 struct bp_target_info *bp_tgt, char *buf)
9288 struct agent_expr *aexpr = NULL;
9291 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9294 buf += strlen (buf);
9296 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9297 buf += strlen (buf);
9299 /* Concatenate all the agent expressions that are commands into the
9302 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9305 sprintf (buf, "X%x,", aexpr->len);
9306 buf += strlen (buf);
9307 for (i = 0; i < aexpr->len; ++i)
9308 buf = pack_hex_byte (buf, aexpr->buf[i]);
9313 /* Insert a breakpoint. On targets that have software breakpoint
9314 support, we ask the remote target to do the work; on targets
9315 which don't, we insert a traditional memory breakpoint. */
9318 remote_insert_breakpoint (struct target_ops *ops,
9319 struct gdbarch *gdbarch,
9320 struct bp_target_info *bp_tgt)
9322 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9323 If it succeeds, then set the support to PACKET_ENABLE. If it
9324 fails, and the user has explicitly requested the Z support then
9325 report an error, otherwise, mark it disabled and go on. */
9327 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9329 CORE_ADDR addr = bp_tgt->reqstd_address;
9330 struct remote_state *rs;
9334 /* Make sure the remote is pointing at the right process, if
9336 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9337 set_general_process ();
9339 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9341 rs = get_remote_state ();
9343 endbuf = rs->buf + get_remote_packet_size ();
9348 addr = (ULONGEST) remote_address_masked (addr);
9349 p += hexnumstr (p, addr);
9350 xsnprintf (p, endbuf - p, ",%d", bpsize);
9352 if (remote_supports_cond_breakpoints (ops))
9353 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9355 if (remote_can_run_breakpoint_commands (ops))
9356 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9359 getpkt (&rs->buf, &rs->buf_size, 0);
9361 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9366 bp_tgt->placed_address = addr;
9367 bp_tgt->placed_size = bpsize;
9369 case PACKET_UNKNOWN:
9374 /* If this breakpoint has target-side commands but this stub doesn't
9375 support Z0 packets, throw error. */
9376 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9377 throw_error (NOT_SUPPORTED_ERROR, _("\
9378 Target doesn't support breakpoints that have target side commands."));
9380 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9384 remote_remove_breakpoint (struct target_ops *ops,
9385 struct gdbarch *gdbarch,
9386 struct bp_target_info *bp_tgt)
9388 CORE_ADDR addr = bp_tgt->placed_address;
9389 struct remote_state *rs = get_remote_state ();
9391 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9394 char *endbuf = rs->buf + get_remote_packet_size ();
9396 /* Make sure the remote is pointing at the right process, if
9398 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9399 set_general_process ();
9405 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9406 p += hexnumstr (p, addr);
9407 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9410 getpkt (&rs->buf, &rs->buf_size, 0);
9412 return (rs->buf[0] == 'E');
9415 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9418 static enum Z_packet_type
9419 watchpoint_to_Z_packet (int type)
9424 return Z_PACKET_WRITE_WP;
9427 return Z_PACKET_READ_WP;
9430 return Z_PACKET_ACCESS_WP;
9433 internal_error (__FILE__, __LINE__,
9434 _("hw_bp_to_z: bad watchpoint type %d"), type);
9439 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9440 enum target_hw_bp_type type, struct expression *cond)
9442 struct remote_state *rs = get_remote_state ();
9443 char *endbuf = rs->buf + get_remote_packet_size ();
9445 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9447 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9450 /* Make sure the remote is pointing at the right process, if
9452 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9453 set_general_process ();
9455 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9456 p = strchr (rs->buf, '\0');
9457 addr = remote_address_masked (addr);
9458 p += hexnumstr (p, (ULONGEST) addr);
9459 xsnprintf (p, endbuf - p, ",%x", len);
9462 getpkt (&rs->buf, &rs->buf_size, 0);
9464 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9468 case PACKET_UNKNOWN:
9473 internal_error (__FILE__, __LINE__,
9474 _("remote_insert_watchpoint: reached end of function"));
9478 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9479 CORE_ADDR start, int length)
9481 CORE_ADDR diff = remote_address_masked (addr - start);
9483 return diff < length;
9488 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9489 enum target_hw_bp_type type, struct expression *cond)
9491 struct remote_state *rs = get_remote_state ();
9492 char *endbuf = rs->buf + get_remote_packet_size ();
9494 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9496 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9499 /* Make sure the remote is pointing at the right process, if
9501 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9502 set_general_process ();
9504 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9505 p = strchr (rs->buf, '\0');
9506 addr = remote_address_masked (addr);
9507 p += hexnumstr (p, (ULONGEST) addr);
9508 xsnprintf (p, endbuf - p, ",%x", len);
9510 getpkt (&rs->buf, &rs->buf_size, 0);
9512 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9515 case PACKET_UNKNOWN:
9520 internal_error (__FILE__, __LINE__,
9521 _("remote_remove_watchpoint: reached end of function"));
9525 int remote_hw_watchpoint_limit = -1;
9526 int remote_hw_watchpoint_length_limit = -1;
9527 int remote_hw_breakpoint_limit = -1;
9530 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9531 CORE_ADDR addr, int len)
9533 if (remote_hw_watchpoint_length_limit == 0)
9535 else if (remote_hw_watchpoint_length_limit < 0)
9537 else if (len <= remote_hw_watchpoint_length_limit)
9544 remote_check_watch_resources (struct target_ops *self,
9545 enum bptype type, int cnt, int ot)
9547 if (type == bp_hardware_breakpoint)
9549 if (remote_hw_breakpoint_limit == 0)
9551 else if (remote_hw_breakpoint_limit < 0)
9553 else if (cnt <= remote_hw_breakpoint_limit)
9558 if (remote_hw_watchpoint_limit == 0)
9560 else if (remote_hw_watchpoint_limit < 0)
9564 else if (cnt <= remote_hw_watchpoint_limit)
9570 /* The to_stopped_by_sw_breakpoint method of target remote. */
9573 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9575 struct thread_info *thread = inferior_thread ();
9577 return (thread->priv != NULL
9578 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9581 /* The to_supports_stopped_by_sw_breakpoint method of target
9585 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9587 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9590 /* The to_stopped_by_hw_breakpoint method of target remote. */
9593 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9595 struct thread_info *thread = inferior_thread ();
9597 return (thread->priv != NULL
9598 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9601 /* The to_supports_stopped_by_hw_breakpoint method of target
9605 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9607 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9611 remote_stopped_by_watchpoint (struct target_ops *ops)
9613 struct thread_info *thread = inferior_thread ();
9615 return (thread->priv != NULL
9616 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9620 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9622 struct thread_info *thread = inferior_thread ();
9624 if (thread->priv != NULL
9625 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9627 *addr_p = thread->priv->watch_data_address;
9636 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9637 struct bp_target_info *bp_tgt)
9639 CORE_ADDR addr = bp_tgt->reqstd_address;
9640 struct remote_state *rs;
9645 /* The length field should be set to the size of a breakpoint
9646 instruction, even though we aren't inserting one ourselves. */
9648 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9650 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9653 /* Make sure the remote is pointing at the right process, if
9655 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9656 set_general_process ();
9658 rs = get_remote_state ();
9660 endbuf = rs->buf + get_remote_packet_size ();
9666 addr = remote_address_masked (addr);
9667 p += hexnumstr (p, (ULONGEST) addr);
9668 xsnprintf (p, endbuf - p, ",%x", bpsize);
9670 if (remote_supports_cond_breakpoints (self))
9671 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9673 if (remote_can_run_breakpoint_commands (self))
9674 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9677 getpkt (&rs->buf, &rs->buf_size, 0);
9679 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9682 if (rs->buf[1] == '.')
9684 message = strchr (rs->buf + 2, '.');
9686 error (_("Remote failure reply: %s"), message + 1);
9689 case PACKET_UNKNOWN:
9692 bp_tgt->placed_address = addr;
9693 bp_tgt->placed_size = bpsize;
9696 internal_error (__FILE__, __LINE__,
9697 _("remote_insert_hw_breakpoint: reached end of function"));
9702 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9703 struct bp_target_info *bp_tgt)
9706 struct remote_state *rs = get_remote_state ();
9708 char *endbuf = rs->buf + get_remote_packet_size ();
9710 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9713 /* Make sure the remote is pointing at the right process, if
9715 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9716 set_general_process ();
9722 addr = remote_address_masked (bp_tgt->placed_address);
9723 p += hexnumstr (p, (ULONGEST) addr);
9724 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9727 getpkt (&rs->buf, &rs->buf_size, 0);
9729 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9732 case PACKET_UNKNOWN:
9737 internal_error (__FILE__, __LINE__,
9738 _("remote_remove_hw_breakpoint: reached end of function"));
9741 /* Verify memory using the "qCRC:" request. */
9744 remote_verify_memory (struct target_ops *ops,
9745 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9747 struct remote_state *rs = get_remote_state ();
9748 unsigned long host_crc, target_crc;
9751 /* It doesn't make sense to use qCRC if the remote target is
9752 connected but not running. */
9753 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9755 enum packet_result result;
9757 /* Make sure the remote is pointing at the right process. */
9758 set_general_process ();
9760 /* FIXME: assumes lma can fit into long. */
9761 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9762 (long) lma, (long) size);
9765 /* Be clever; compute the host_crc before waiting for target
9767 host_crc = xcrc32 (data, size, 0xffffffff);
9769 getpkt (&rs->buf, &rs->buf_size, 0);
9771 result = packet_ok (rs->buf,
9772 &remote_protocol_packets[PACKET_qCRC]);
9773 if (result == PACKET_ERROR)
9775 else if (result == PACKET_OK)
9777 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9778 target_crc = target_crc * 16 + fromhex (*tmp);
9780 return (host_crc == target_crc);
9784 return simple_verify_memory (ops, data, lma, size);
9787 /* compare-sections command
9789 With no arguments, compares each loadable section in the exec bfd
9790 with the same memory range on the target, and reports mismatches.
9791 Useful for verifying the image on the target against the exec file. */
9794 compare_sections_command (char *args, int from_tty)
9797 struct cleanup *old_chain;
9799 const char *sectname;
9808 error (_("command cannot be used without an exec file"));
9810 /* Make sure the remote is pointing at the right process. */
9811 set_general_process ();
9813 if (args != NULL && strcmp (args, "-r") == 0)
9819 for (s = exec_bfd->sections; s; s = s->next)
9821 if (!(s->flags & SEC_LOAD))
9822 continue; /* Skip non-loadable section. */
9824 if (read_only && (s->flags & SEC_READONLY) == 0)
9825 continue; /* Skip writeable sections */
9827 size = bfd_get_section_size (s);
9829 continue; /* Skip zero-length section. */
9831 sectname = bfd_get_section_name (exec_bfd, s);
9832 if (args && strcmp (args, sectname) != 0)
9833 continue; /* Not the section selected by user. */
9835 matched = 1; /* Do this section. */
9838 sectdata = (gdb_byte *) xmalloc (size);
9839 old_chain = make_cleanup (xfree, sectdata);
9840 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9842 res = target_verify_memory (sectdata, lma, size);
9845 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9846 paddress (target_gdbarch (), lma),
9847 paddress (target_gdbarch (), lma + size));
9849 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9850 paddress (target_gdbarch (), lma),
9851 paddress (target_gdbarch (), lma + size));
9853 printf_filtered ("matched.\n");
9856 printf_filtered ("MIS-MATCHED!\n");
9860 do_cleanups (old_chain);
9863 warning (_("One or more sections of the target image does not match\n\
9864 the loaded file\n"));
9865 if (args && !matched)
9866 printf_filtered (_("No loaded section named '%s'.\n"), args);
9869 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9870 into remote target. The number of bytes written to the remote
9871 target is returned, or -1 for error. */
9873 static enum target_xfer_status
9874 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9875 const char *annex, const gdb_byte *writebuf,
9876 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9877 struct packet_config *packet)
9881 struct remote_state *rs = get_remote_state ();
9882 int max_size = get_memory_write_packet_size ();
9884 if (packet->support == PACKET_DISABLE)
9885 return TARGET_XFER_E_IO;
9887 /* Insert header. */
9888 i = snprintf (rs->buf, max_size,
9889 "qXfer:%s:write:%s:%s:",
9890 object_name, annex ? annex : "",
9891 phex_nz (offset, sizeof offset));
9892 max_size -= (i + 1);
9894 /* Escape as much data as fits into rs->buf. */
9895 buf_len = remote_escape_output
9896 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9898 if (putpkt_binary (rs->buf, i + buf_len) < 0
9899 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9900 || packet_ok (rs->buf, packet) != PACKET_OK)
9901 return TARGET_XFER_E_IO;
9903 unpack_varlen_hex (rs->buf, &n);
9906 return TARGET_XFER_OK;
9909 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9910 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9911 number of bytes read is returned, or 0 for EOF, or -1 for error.
9912 The number of bytes read may be less than LEN without indicating an
9913 EOF. PACKET is checked and updated to indicate whether the remote
9914 target supports this object. */
9916 static enum target_xfer_status
9917 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9919 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9920 ULONGEST *xfered_len,
9921 struct packet_config *packet)
9923 struct remote_state *rs = get_remote_state ();
9924 LONGEST i, n, packet_len;
9926 if (packet->support == PACKET_DISABLE)
9927 return TARGET_XFER_E_IO;
9929 /* Check whether we've cached an end-of-object packet that matches
9931 if (rs->finished_object)
9933 if (strcmp (object_name, rs->finished_object) == 0
9934 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9935 && offset == rs->finished_offset)
9936 return TARGET_XFER_EOF;
9939 /* Otherwise, we're now reading something different. Discard
9941 xfree (rs->finished_object);
9942 xfree (rs->finished_annex);
9943 rs->finished_object = NULL;
9944 rs->finished_annex = NULL;
9947 /* Request only enough to fit in a single packet. The actual data
9948 may not, since we don't know how much of it will need to be escaped;
9949 the target is free to respond with slightly less data. We subtract
9950 five to account for the response type and the protocol frame. */
9951 n = min (get_remote_packet_size () - 5, len);
9952 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9953 object_name, annex ? annex : "",
9954 phex_nz (offset, sizeof offset),
9955 phex_nz (n, sizeof n));
9956 i = putpkt (rs->buf);
9958 return TARGET_XFER_E_IO;
9961 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9962 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9963 return TARGET_XFER_E_IO;
9965 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9966 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9968 /* 'm' means there is (or at least might be) more data after this
9969 batch. That does not make sense unless there's at least one byte
9970 of data in this reply. */
9971 if (rs->buf[0] == 'm' && packet_len == 1)
9972 error (_("Remote qXfer reply contained no data."));
9974 /* Got some data. */
9975 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9976 packet_len - 1, readbuf, n);
9978 /* 'l' is an EOF marker, possibly including a final block of data,
9979 or possibly empty. If we have the final block of a non-empty
9980 object, record this fact to bypass a subsequent partial read. */
9981 if (rs->buf[0] == 'l' && offset + i > 0)
9983 rs->finished_object = xstrdup (object_name);
9984 rs->finished_annex = xstrdup (annex ? annex : "");
9985 rs->finished_offset = offset + i;
9989 return TARGET_XFER_EOF;
9993 return TARGET_XFER_OK;
9997 static enum target_xfer_status
9998 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9999 const char *annex, gdb_byte *readbuf,
10000 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10001 ULONGEST *xfered_len)
10003 struct remote_state *rs;
10007 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10009 set_remote_traceframe ();
10010 set_general_thread (inferior_ptid);
10012 rs = get_remote_state ();
10014 /* Handle memory using the standard memory routines. */
10015 if (object == TARGET_OBJECT_MEMORY)
10017 /* If the remote target is connected but not running, we should
10018 pass this request down to a lower stratum (e.g. the executable
10020 if (!target_has_execution)
10021 return TARGET_XFER_EOF;
10023 if (writebuf != NULL)
10024 return remote_write_bytes (offset, writebuf, len, unit_size,
10027 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10031 /* Handle SPU memory using qxfer packets. */
10032 if (object == TARGET_OBJECT_SPU)
10035 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
10036 xfered_len, &remote_protocol_packets
10037 [PACKET_qXfer_spu_read]);
10039 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
10040 xfered_len, &remote_protocol_packets
10041 [PACKET_qXfer_spu_write]);
10044 /* Handle extra signal info using qxfer packets. */
10045 if (object == TARGET_OBJECT_SIGNAL_INFO)
10048 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10049 xfered_len, &remote_protocol_packets
10050 [PACKET_qXfer_siginfo_read]);
10052 return remote_write_qxfer (ops, "siginfo", annex,
10053 writebuf, offset, len, xfered_len,
10054 &remote_protocol_packets
10055 [PACKET_qXfer_siginfo_write]);
10058 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10061 return remote_read_qxfer (ops, "statictrace", annex,
10062 readbuf, offset, len, xfered_len,
10063 &remote_protocol_packets
10064 [PACKET_qXfer_statictrace_read]);
10066 return TARGET_XFER_E_IO;
10069 /* Only handle flash writes. */
10070 if (writebuf != NULL)
10074 case TARGET_OBJECT_FLASH:
10075 return remote_flash_write (ops, offset, len, xfered_len,
10079 return TARGET_XFER_E_IO;
10083 /* Map pre-existing objects onto letters. DO NOT do this for new
10084 objects!!! Instead specify new query packets. */
10087 case TARGET_OBJECT_AVR:
10091 case TARGET_OBJECT_AUXV:
10092 gdb_assert (annex == NULL);
10093 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10095 &remote_protocol_packets[PACKET_qXfer_auxv]);
10097 case TARGET_OBJECT_AVAILABLE_FEATURES:
10098 return remote_read_qxfer
10099 (ops, "features", annex, readbuf, offset, len, xfered_len,
10100 &remote_protocol_packets[PACKET_qXfer_features]);
10102 case TARGET_OBJECT_LIBRARIES:
10103 return remote_read_qxfer
10104 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10105 &remote_protocol_packets[PACKET_qXfer_libraries]);
10107 case TARGET_OBJECT_LIBRARIES_SVR4:
10108 return remote_read_qxfer
10109 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10110 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10112 case TARGET_OBJECT_MEMORY_MAP:
10113 gdb_assert (annex == NULL);
10114 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10116 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10118 case TARGET_OBJECT_OSDATA:
10119 /* Should only get here if we're connected. */
10120 gdb_assert (rs->remote_desc);
10121 return remote_read_qxfer
10122 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10123 &remote_protocol_packets[PACKET_qXfer_osdata]);
10125 case TARGET_OBJECT_THREADS:
10126 gdb_assert (annex == NULL);
10127 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10129 &remote_protocol_packets[PACKET_qXfer_threads]);
10131 case TARGET_OBJECT_TRACEFRAME_INFO:
10132 gdb_assert (annex == NULL);
10133 return remote_read_qxfer
10134 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10135 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10137 case TARGET_OBJECT_FDPIC:
10138 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10140 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10142 case TARGET_OBJECT_OPENVMS_UIB:
10143 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10145 &remote_protocol_packets[PACKET_qXfer_uib]);
10147 case TARGET_OBJECT_BTRACE:
10148 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10150 &remote_protocol_packets[PACKET_qXfer_btrace]);
10152 case TARGET_OBJECT_BTRACE_CONF:
10153 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10155 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10157 case TARGET_OBJECT_EXEC_FILE:
10158 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10160 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10163 return TARGET_XFER_E_IO;
10166 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10167 large enough let the caller deal with it. */
10168 if (len < get_remote_packet_size ())
10169 return TARGET_XFER_E_IO;
10170 len = get_remote_packet_size ();
10172 /* Except for querying the minimum buffer size, target must be open. */
10173 if (!rs->remote_desc)
10174 error (_("remote query is only available after target open"));
10176 gdb_assert (annex != NULL);
10177 gdb_assert (readbuf != NULL);
10181 *p2++ = query_type;
10183 /* We used one buffer char for the remote protocol q command and
10184 another for the query type. As the remote protocol encapsulation
10185 uses 4 chars plus one extra in case we are debugging
10186 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10189 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10191 /* Bad caller may have sent forbidden characters. */
10192 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10197 gdb_assert (annex[i] == '\0');
10199 i = putpkt (rs->buf);
10201 return TARGET_XFER_E_IO;
10203 getpkt (&rs->buf, &rs->buf_size, 0);
10204 strcpy ((char *) readbuf, rs->buf);
10206 *xfered_len = strlen ((char *) readbuf);
10207 return TARGET_XFER_OK;
10211 remote_search_memory (struct target_ops* ops,
10212 CORE_ADDR start_addr, ULONGEST search_space_len,
10213 const gdb_byte *pattern, ULONGEST pattern_len,
10214 CORE_ADDR *found_addrp)
10216 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10217 struct remote_state *rs = get_remote_state ();
10218 int max_size = get_memory_write_packet_size ();
10219 struct packet_config *packet =
10220 &remote_protocol_packets[PACKET_qSearch_memory];
10221 /* Number of packet bytes used to encode the pattern;
10222 this could be more than PATTERN_LEN due to escape characters. */
10223 int escaped_pattern_len;
10224 /* Amount of pattern that was encodable in the packet. */
10225 int used_pattern_len;
10228 ULONGEST found_addr;
10230 /* Don't go to the target if we don't have to.
10231 This is done before checking packet->support to avoid the possibility that
10232 a success for this edge case means the facility works in general. */
10233 if (pattern_len > search_space_len)
10235 if (pattern_len == 0)
10237 *found_addrp = start_addr;
10241 /* If we already know the packet isn't supported, fall back to the simple
10242 way of searching memory. */
10244 if (packet_config_support (packet) == PACKET_DISABLE)
10246 /* Target doesn't provided special support, fall back and use the
10247 standard support (copy memory and do the search here). */
10248 return simple_search_memory (ops, start_addr, search_space_len,
10249 pattern, pattern_len, found_addrp);
10252 /* Make sure the remote is pointing at the right process. */
10253 set_general_process ();
10255 /* Insert header. */
10256 i = snprintf (rs->buf, max_size,
10257 "qSearch:memory:%s;%s;",
10258 phex_nz (start_addr, addr_size),
10259 phex_nz (search_space_len, sizeof (search_space_len)));
10260 max_size -= (i + 1);
10262 /* Escape as much data as fits into rs->buf. */
10263 escaped_pattern_len =
10264 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10265 &used_pattern_len, max_size);
10267 /* Bail if the pattern is too large. */
10268 if (used_pattern_len != pattern_len)
10269 error (_("Pattern is too large to transmit to remote target."));
10271 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10272 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10273 || packet_ok (rs->buf, packet) != PACKET_OK)
10275 /* The request may not have worked because the command is not
10276 supported. If so, fall back to the simple way. */
10277 if (packet->support == PACKET_DISABLE)
10279 return simple_search_memory (ops, start_addr, search_space_len,
10280 pattern, pattern_len, found_addrp);
10285 if (rs->buf[0] == '0')
10287 else if (rs->buf[0] == '1')
10290 if (rs->buf[1] != ',')
10291 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10292 unpack_varlen_hex (rs->buf + 2, &found_addr);
10293 *found_addrp = found_addr;
10296 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10302 remote_rcmd (struct target_ops *self, const char *command,
10303 struct ui_file *outbuf)
10305 struct remote_state *rs = get_remote_state ();
10308 if (!rs->remote_desc)
10309 error (_("remote rcmd is only available after target open"));
10311 /* Send a NULL command across as an empty command. */
10312 if (command == NULL)
10315 /* The query prefix. */
10316 strcpy (rs->buf, "qRcmd,");
10317 p = strchr (rs->buf, '\0');
10319 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10320 > get_remote_packet_size ())
10321 error (_("\"monitor\" command ``%s'' is too long."), command);
10323 /* Encode the actual command. */
10324 bin2hex ((const gdb_byte *) command, p, strlen (command));
10326 if (putpkt (rs->buf) < 0)
10327 error (_("Communication problem with target."));
10329 /* get/display the response */
10334 /* XXX - see also remote_get_noisy_reply(). */
10335 QUIT; /* Allow user to bail out with ^C. */
10337 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10339 /* Timeout. Continue to (try to) read responses.
10340 This is better than stopping with an error, assuming the stub
10341 is still executing the (long) monitor command.
10342 If needed, the user can interrupt gdb using C-c, obtaining
10343 an effect similar to stop on timeout. */
10347 if (buf[0] == '\0')
10348 error (_("Target does not support this command."));
10349 if (buf[0] == 'O' && buf[1] != 'K')
10351 remote_console_output (buf + 1); /* 'O' message from stub. */
10354 if (strcmp (buf, "OK") == 0)
10356 if (strlen (buf) == 3 && buf[0] == 'E'
10357 && isdigit (buf[1]) && isdigit (buf[2]))
10359 error (_("Protocol error with Rcmd"));
10361 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10363 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10365 fputc_unfiltered (c, outbuf);
10371 static VEC(mem_region_s) *
10372 remote_memory_map (struct target_ops *ops)
10374 VEC(mem_region_s) *result = NULL;
10375 char *text = target_read_stralloc (¤t_target,
10376 TARGET_OBJECT_MEMORY_MAP, NULL);
10380 struct cleanup *back_to = make_cleanup (xfree, text);
10382 result = parse_memory_map (text);
10383 do_cleanups (back_to);
10390 packet_command (char *args, int from_tty)
10392 struct remote_state *rs = get_remote_state ();
10394 if (!rs->remote_desc)
10395 error (_("command can only be used with remote target"));
10398 error (_("remote-packet command requires packet text as argument"));
10400 puts_filtered ("sending: ");
10401 print_packet (args);
10402 puts_filtered ("\n");
10405 getpkt (&rs->buf, &rs->buf_size, 0);
10406 puts_filtered ("received: ");
10407 print_packet (rs->buf);
10408 puts_filtered ("\n");
10412 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10414 static void display_thread_info (struct gdb_ext_thread_info *info);
10416 static void threadset_test_cmd (char *cmd, int tty);
10418 static void threadalive_test (char *cmd, int tty);
10420 static void threadlist_test_cmd (char *cmd, int tty);
10422 int get_and_display_threadinfo (threadref *ref);
10424 static void threadinfo_test_cmd (char *cmd, int tty);
10426 static int thread_display_step (threadref *ref, void *context);
10428 static void threadlist_update_test_cmd (char *cmd, int tty);
10430 static void init_remote_threadtests (void);
10432 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10435 threadset_test_cmd (char *cmd, int tty)
10437 int sample_thread = SAMPLE_THREAD;
10439 printf_filtered (_("Remote threadset test\n"));
10440 set_general_thread (sample_thread);
10445 threadalive_test (char *cmd, int tty)
10447 int sample_thread = SAMPLE_THREAD;
10448 int pid = ptid_get_pid (inferior_ptid);
10449 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10451 if (remote_thread_alive (ptid))
10452 printf_filtered ("PASS: Thread alive test\n");
10454 printf_filtered ("FAIL: Thread alive test\n");
10457 void output_threadid (char *title, threadref *ref);
10460 output_threadid (char *title, threadref *ref)
10464 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10466 printf_filtered ("%s %s\n", title, (&hexid[0]));
10470 threadlist_test_cmd (char *cmd, int tty)
10473 threadref nextthread;
10474 int done, result_count;
10475 threadref threadlist[3];
10477 printf_filtered ("Remote Threadlist test\n");
10478 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10479 &result_count, &threadlist[0]))
10480 printf_filtered ("FAIL: threadlist test\n");
10483 threadref *scan = threadlist;
10484 threadref *limit = scan + result_count;
10486 while (scan < limit)
10487 output_threadid (" thread ", scan++);
10492 display_thread_info (struct gdb_ext_thread_info *info)
10494 output_threadid ("Threadid: ", &info->threadid);
10495 printf_filtered ("Name: %s\n ", info->shortname);
10496 printf_filtered ("State: %s\n", info->display);
10497 printf_filtered ("other: %s\n\n", info->more_display);
10501 get_and_display_threadinfo (threadref *ref)
10505 struct gdb_ext_thread_info threadinfo;
10507 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10508 | TAG_MOREDISPLAY | TAG_DISPLAY;
10509 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10510 display_thread_info (&threadinfo);
10515 threadinfo_test_cmd (char *cmd, int tty)
10517 int athread = SAMPLE_THREAD;
10521 int_to_threadref (&thread, athread);
10522 printf_filtered ("Remote Threadinfo test\n");
10523 if (!get_and_display_threadinfo (&thread))
10524 printf_filtered ("FAIL cannot get thread info\n");
10528 thread_display_step (threadref *ref, void *context)
10530 /* output_threadid(" threadstep ",ref); *//* simple test */
10531 return get_and_display_threadinfo (ref);
10535 threadlist_update_test_cmd (char *cmd, int tty)
10537 printf_filtered ("Remote Threadlist update test\n");
10538 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10542 init_remote_threadtests (void)
10544 add_com ("tlist", class_obscure, threadlist_test_cmd,
10545 _("Fetch and print the remote list of "
10546 "thread identifiers, one pkt only"));
10547 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10548 _("Fetch and display info about one thread"));
10549 add_com ("tset", class_obscure, threadset_test_cmd,
10550 _("Test setting to a different thread"));
10551 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10552 _("Iterate through updating all remote thread info"));
10553 add_com ("talive", class_obscure, threadalive_test,
10554 _(" Remote thread alive test "));
10559 /* Convert a thread ID to a string. Returns the string in a static
10563 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10565 static char buf[64];
10566 struct remote_state *rs = get_remote_state ();
10568 if (ptid_equal (ptid, null_ptid))
10569 return normal_pid_to_str (ptid);
10570 else if (ptid_is_pid (ptid))
10572 /* Printing an inferior target id. */
10574 /* When multi-process extensions are off, there's no way in the
10575 remote protocol to know the remote process id, if there's any
10576 at all. There's one exception --- when we're connected with
10577 target extended-remote, and we manually attached to a process
10578 with "attach PID". We don't record anywhere a flag that
10579 allows us to distinguish that case from the case of
10580 connecting with extended-remote and the stub already being
10581 attached to a process, and reporting yes to qAttached, hence
10582 no smart special casing here. */
10583 if (!remote_multi_process_p (rs))
10585 xsnprintf (buf, sizeof buf, "Remote target");
10589 return normal_pid_to_str (ptid);
10593 if (ptid_equal (magic_null_ptid, ptid))
10594 xsnprintf (buf, sizeof buf, "Thread <main>");
10595 else if (remote_multi_process_p (rs))
10596 if (ptid_get_lwp (ptid) == 0)
10597 return normal_pid_to_str (ptid);
10599 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10600 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10602 xsnprintf (buf, sizeof buf, "Thread %ld",
10603 ptid_get_lwp (ptid));
10608 /* Get the address of the thread local variable in OBJFILE which is
10609 stored at OFFSET within the thread local storage for thread PTID. */
10612 remote_get_thread_local_address (struct target_ops *ops,
10613 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10615 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10617 struct remote_state *rs = get_remote_state ();
10619 char *endp = rs->buf + get_remote_packet_size ();
10620 enum packet_result result;
10622 strcpy (p, "qGetTLSAddr:");
10624 p = write_ptid (p, endp, ptid);
10626 p += hexnumstr (p, offset);
10628 p += hexnumstr (p, lm);
10632 getpkt (&rs->buf, &rs->buf_size, 0);
10633 result = packet_ok (rs->buf,
10634 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10635 if (result == PACKET_OK)
10639 unpack_varlen_hex (rs->buf, &result);
10642 else if (result == PACKET_UNKNOWN)
10643 throw_error (TLS_GENERIC_ERROR,
10644 _("Remote target doesn't support qGetTLSAddr packet"));
10646 throw_error (TLS_GENERIC_ERROR,
10647 _("Remote target failed to process qGetTLSAddr request"));
10650 throw_error (TLS_GENERIC_ERROR,
10651 _("TLS not supported or disabled on this target"));
10656 /* Provide thread local base, i.e. Thread Information Block address.
10657 Returns 1 if ptid is found and thread_local_base is non zero. */
10660 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10662 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10664 struct remote_state *rs = get_remote_state ();
10666 char *endp = rs->buf + get_remote_packet_size ();
10667 enum packet_result result;
10669 strcpy (p, "qGetTIBAddr:");
10671 p = write_ptid (p, endp, ptid);
10675 getpkt (&rs->buf, &rs->buf_size, 0);
10676 result = packet_ok (rs->buf,
10677 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10678 if (result == PACKET_OK)
10682 unpack_varlen_hex (rs->buf, &result);
10684 *addr = (CORE_ADDR) result;
10687 else if (result == PACKET_UNKNOWN)
10688 error (_("Remote target doesn't support qGetTIBAddr packet"));
10690 error (_("Remote target failed to process qGetTIBAddr request"));
10693 error (_("qGetTIBAddr not supported or disabled on this target"));
10698 /* Support for inferring a target description based on the current
10699 architecture and the size of a 'g' packet. While the 'g' packet
10700 can have any size (since optional registers can be left off the
10701 end), some sizes are easily recognizable given knowledge of the
10702 approximate architecture. */
10704 struct remote_g_packet_guess
10707 const struct target_desc *tdesc;
10709 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10710 DEF_VEC_O(remote_g_packet_guess_s);
10712 struct remote_g_packet_data
10714 VEC(remote_g_packet_guess_s) *guesses;
10717 static struct gdbarch_data *remote_g_packet_data_handle;
10720 remote_g_packet_data_init (struct obstack *obstack)
10722 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10726 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10727 const struct target_desc *tdesc)
10729 struct remote_g_packet_data *data
10730 = ((struct remote_g_packet_data *)
10731 gdbarch_data (gdbarch, remote_g_packet_data_handle));
10732 struct remote_g_packet_guess new_guess, *guess;
10735 gdb_assert (tdesc != NULL);
10738 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10740 if (guess->bytes == bytes)
10741 internal_error (__FILE__, __LINE__,
10742 _("Duplicate g packet description added for size %d"),
10745 new_guess.bytes = bytes;
10746 new_guess.tdesc = tdesc;
10747 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10750 /* Return 1 if remote_read_description would do anything on this target
10751 and architecture, 0 otherwise. */
10754 remote_read_description_p (struct target_ops *target)
10756 struct remote_g_packet_data *data
10757 = ((struct remote_g_packet_data *)
10758 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10760 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10766 static const struct target_desc *
10767 remote_read_description (struct target_ops *target)
10769 struct remote_g_packet_data *data
10770 = ((struct remote_g_packet_data *)
10771 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10773 /* Do not try this during initial connection, when we do not know
10774 whether there is a running but stopped thread. */
10775 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10776 return target->beneath->to_read_description (target->beneath);
10778 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10780 struct remote_g_packet_guess *guess;
10782 int bytes = send_g_packet ();
10785 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10787 if (guess->bytes == bytes)
10788 return guess->tdesc;
10790 /* We discard the g packet. A minor optimization would be to
10791 hold on to it, and fill the register cache once we have selected
10792 an architecture, but it's too tricky to do safely. */
10795 return target->beneath->to_read_description (target->beneath);
10798 /* Remote file transfer support. This is host-initiated I/O, not
10799 target-initiated; for target-initiated, see remote-fileio.c. */
10801 /* If *LEFT is at least the length of STRING, copy STRING to
10802 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10803 decrease *LEFT. Otherwise raise an error. */
10806 remote_buffer_add_string (char **buffer, int *left, char *string)
10808 int len = strlen (string);
10811 error (_("Packet too long for target."));
10813 memcpy (*buffer, string, len);
10817 /* NUL-terminate the buffer as a convenience, if there is
10823 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10824 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10825 decrease *LEFT. Otherwise raise an error. */
10828 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10831 if (2 * len > *left)
10832 error (_("Packet too long for target."));
10834 bin2hex (bytes, *buffer, len);
10835 *buffer += 2 * len;
10838 /* NUL-terminate the buffer as a convenience, if there is
10844 /* If *LEFT is large enough, convert VALUE to hex and add it to
10845 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10846 decrease *LEFT. Otherwise raise an error. */
10849 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10851 int len = hexnumlen (value);
10854 error (_("Packet too long for target."));
10856 hexnumstr (*buffer, value);
10860 /* NUL-terminate the buffer as a convenience, if there is
10866 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10867 value, *REMOTE_ERRNO to the remote error number or zero if none
10868 was included, and *ATTACHMENT to point to the start of the annex
10869 if any. The length of the packet isn't needed here; there may
10870 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10872 Return 0 if the packet could be parsed, -1 if it could not. If
10873 -1 is returned, the other variables may not be initialized. */
10876 remote_hostio_parse_result (char *buffer, int *retcode,
10877 int *remote_errno, char **attachment)
10882 *attachment = NULL;
10884 if (buffer[0] != 'F')
10888 *retcode = strtol (&buffer[1], &p, 16);
10889 if (errno != 0 || p == &buffer[1])
10892 /* Check for ",errno". */
10896 *remote_errno = strtol (p + 1, &p2, 16);
10897 if (errno != 0 || p + 1 == p2)
10902 /* Check for ";attachment". If there is no attachment, the
10903 packet should end here. */
10906 *attachment = p + 1;
10909 else if (*p == '\0')
10915 /* Send a prepared I/O packet to the target and read its response.
10916 The prepared packet is in the global RS->BUF before this function
10917 is called, and the answer is there when we return.
10919 COMMAND_BYTES is the length of the request to send, which may include
10920 binary data. WHICH_PACKET is the packet configuration to check
10921 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10922 is set to the error number and -1 is returned. Otherwise the value
10923 returned by the function is returned.
10925 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10926 attachment is expected; an error will be reported if there's a
10927 mismatch. If one is found, *ATTACHMENT will be set to point into
10928 the packet buffer and *ATTACHMENT_LEN will be set to the
10929 attachment's length. */
10932 remote_hostio_send_command (int command_bytes, int which_packet,
10933 int *remote_errno, char **attachment,
10934 int *attachment_len)
10936 struct remote_state *rs = get_remote_state ();
10937 int ret, bytes_read;
10938 char *attachment_tmp;
10940 if (!rs->remote_desc
10941 || packet_support (which_packet) == PACKET_DISABLE)
10943 *remote_errno = FILEIO_ENOSYS;
10947 putpkt_binary (rs->buf, command_bytes);
10948 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10950 /* If it timed out, something is wrong. Don't try to parse the
10952 if (bytes_read < 0)
10954 *remote_errno = FILEIO_EINVAL;
10958 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10961 *remote_errno = FILEIO_EINVAL;
10963 case PACKET_UNKNOWN:
10964 *remote_errno = FILEIO_ENOSYS;
10970 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10973 *remote_errno = FILEIO_EINVAL;
10977 /* Make sure we saw an attachment if and only if we expected one. */
10978 if ((attachment_tmp == NULL && attachment != NULL)
10979 || (attachment_tmp != NULL && attachment == NULL))
10981 *remote_errno = FILEIO_EINVAL;
10985 /* If an attachment was found, it must point into the packet buffer;
10986 work out how many bytes there were. */
10987 if (attachment_tmp != NULL)
10989 *attachment = attachment_tmp;
10990 *attachment_len = bytes_read - (*attachment - rs->buf);
10996 /* Invalidate the readahead cache. */
10999 readahead_cache_invalidate (void)
11001 struct remote_state *rs = get_remote_state ();
11003 rs->readahead_cache.fd = -1;
11006 /* Invalidate the readahead cache if it is holding data for FD. */
11009 readahead_cache_invalidate_fd (int fd)
11011 struct remote_state *rs = get_remote_state ();
11013 if (rs->readahead_cache.fd == fd)
11014 rs->readahead_cache.fd = -1;
11017 /* Set the filesystem remote_hostio functions that take FILENAME
11018 arguments will use. Return 0 on success, or -1 if an error
11019 occurs (and set *REMOTE_ERRNO). */
11022 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11024 struct remote_state *rs = get_remote_state ();
11025 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11027 int left = get_remote_packet_size () - 1;
11031 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11034 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11037 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11039 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11040 remote_buffer_add_string (&p, &left, arg);
11042 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11043 remote_errno, NULL, NULL);
11045 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11049 rs->fs_pid = required_pid;
11054 /* Implementation of to_fileio_open. */
11057 remote_hostio_open (struct target_ops *self,
11058 struct inferior *inf, const char *filename,
11059 int flags, int mode, int warn_if_slow,
11062 struct remote_state *rs = get_remote_state ();
11064 int left = get_remote_packet_size () - 1;
11068 static int warning_issued = 0;
11070 printf_unfiltered (_("Reading %s from remote target...\n"),
11073 if (!warning_issued)
11075 warning (_("File transfers from remote targets can be slow."
11076 " Use \"set sysroot\" to access files locally"
11078 warning_issued = 1;
11082 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11085 remote_buffer_add_string (&p, &left, "vFile:open:");
11087 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11088 strlen (filename));
11089 remote_buffer_add_string (&p, &left, ",");
11091 remote_buffer_add_int (&p, &left, flags);
11092 remote_buffer_add_string (&p, &left, ",");
11094 remote_buffer_add_int (&p, &left, mode);
11096 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11097 remote_errno, NULL, NULL);
11100 /* Implementation of to_fileio_pwrite. */
11103 remote_hostio_pwrite (struct target_ops *self,
11104 int fd, const gdb_byte *write_buf, int len,
11105 ULONGEST offset, int *remote_errno)
11107 struct remote_state *rs = get_remote_state ();
11109 int left = get_remote_packet_size ();
11112 readahead_cache_invalidate_fd (fd);
11114 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11116 remote_buffer_add_int (&p, &left, fd);
11117 remote_buffer_add_string (&p, &left, ",");
11119 remote_buffer_add_int (&p, &left, offset);
11120 remote_buffer_add_string (&p, &left, ",");
11122 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11123 get_remote_packet_size () - (p - rs->buf));
11125 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11126 remote_errno, NULL, NULL);
11129 /* Helper for the implementation of to_fileio_pread. Read the file
11130 from the remote side with vFile:pread. */
11133 remote_hostio_pread_vFile (struct target_ops *self,
11134 int fd, gdb_byte *read_buf, int len,
11135 ULONGEST offset, int *remote_errno)
11137 struct remote_state *rs = get_remote_state ();
11140 int left = get_remote_packet_size ();
11141 int ret, attachment_len;
11144 remote_buffer_add_string (&p, &left, "vFile:pread:");
11146 remote_buffer_add_int (&p, &left, fd);
11147 remote_buffer_add_string (&p, &left, ",");
11149 remote_buffer_add_int (&p, &left, len);
11150 remote_buffer_add_string (&p, &left, ",");
11152 remote_buffer_add_int (&p, &left, offset);
11154 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11155 remote_errno, &attachment,
11161 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11163 if (read_len != ret)
11164 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11169 /* Serve pread from the readahead cache. Returns number of bytes
11170 read, or 0 if the request can't be served from the cache. */
11173 remote_hostio_pread_from_cache (struct remote_state *rs,
11174 int fd, gdb_byte *read_buf, size_t len,
11177 struct readahead_cache *cache = &rs->readahead_cache;
11179 if (cache->fd == fd
11180 && cache->offset <= offset
11181 && offset < cache->offset + cache->bufsize)
11183 ULONGEST max = cache->offset + cache->bufsize;
11185 if (offset + len > max)
11186 len = max - offset;
11188 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11195 /* Implementation of to_fileio_pread. */
11198 remote_hostio_pread (struct target_ops *self,
11199 int fd, gdb_byte *read_buf, int len,
11200 ULONGEST offset, int *remote_errno)
11203 struct remote_state *rs = get_remote_state ();
11204 struct readahead_cache *cache = &rs->readahead_cache;
11206 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11209 cache->hit_count++;
11212 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11213 pulongest (cache->hit_count));
11217 cache->miss_count++;
11219 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11220 pulongest (cache->miss_count));
11223 cache->offset = offset;
11224 cache->bufsize = get_remote_packet_size ();
11225 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11227 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11228 cache->offset, remote_errno);
11231 readahead_cache_invalidate_fd (fd);
11235 cache->bufsize = ret;
11236 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11239 /* Implementation of to_fileio_close. */
11242 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11244 struct remote_state *rs = get_remote_state ();
11246 int left = get_remote_packet_size () - 1;
11248 readahead_cache_invalidate_fd (fd);
11250 remote_buffer_add_string (&p, &left, "vFile:close:");
11252 remote_buffer_add_int (&p, &left, fd);
11254 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11255 remote_errno, NULL, NULL);
11258 /* Implementation of to_fileio_unlink. */
11261 remote_hostio_unlink (struct target_ops *self,
11262 struct inferior *inf, const char *filename,
11265 struct remote_state *rs = get_remote_state ();
11267 int left = get_remote_packet_size () - 1;
11269 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11272 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11274 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11275 strlen (filename));
11277 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11278 remote_errno, NULL, NULL);
11281 /* Implementation of to_fileio_readlink. */
11284 remote_hostio_readlink (struct target_ops *self,
11285 struct inferior *inf, const char *filename,
11288 struct remote_state *rs = get_remote_state ();
11291 int left = get_remote_packet_size ();
11292 int len, attachment_len;
11296 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11299 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11301 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11302 strlen (filename));
11304 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11305 remote_errno, &attachment,
11311 ret = (char *) xmalloc (len + 1);
11313 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11314 (gdb_byte *) ret, len);
11315 if (read_len != len)
11316 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11322 /* Implementation of to_fileio_fstat. */
11325 remote_hostio_fstat (struct target_ops *self,
11326 int fd, struct stat *st,
11329 struct remote_state *rs = get_remote_state ();
11331 int left = get_remote_packet_size ();
11332 int attachment_len, ret;
11334 struct fio_stat fst;
11337 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11339 remote_buffer_add_int (&p, &left, fd);
11341 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11342 remote_errno, &attachment,
11346 if (*remote_errno != FILEIO_ENOSYS)
11349 /* Strictly we should return -1, ENOSYS here, but when
11350 "set sysroot remote:" was implemented in August 2008
11351 BFD's need for a stat function was sidestepped with
11352 this hack. This was not remedied until March 2015
11353 so we retain the previous behavior to avoid breaking
11356 Note that the memset is a March 2015 addition; older
11357 GDBs set st_size *and nothing else* so the structure
11358 would have garbage in all other fields. This might
11359 break something but retaining the previous behavior
11360 here would be just too wrong. */
11362 memset (st, 0, sizeof (struct stat));
11363 st->st_size = INT_MAX;
11367 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11368 (gdb_byte *) &fst, sizeof (fst));
11370 if (read_len != ret)
11371 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11373 if (read_len != sizeof (fst))
11374 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11375 read_len, (int) sizeof (fst));
11377 remote_fileio_to_host_stat (&fst, st);
11382 /* Implementation of to_filesystem_is_local. */
11385 remote_filesystem_is_local (struct target_ops *self)
11387 /* Valgrind GDB presents itself as a remote target but works
11388 on the local filesystem: it does not implement remote get
11389 and users are not expected to set a sysroot. To handle
11390 this case we treat the remote filesystem as local if the
11391 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11392 does not support vFile:open. */
11393 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11395 enum packet_support ps = packet_support (PACKET_vFile_open);
11397 if (ps == PACKET_SUPPORT_UNKNOWN)
11399 int fd, remote_errno;
11401 /* Try opening a file to probe support. The supplied
11402 filename is irrelevant, we only care about whether
11403 the stub recognizes the packet or not. */
11404 fd = remote_hostio_open (self, NULL, "just probing",
11405 FILEIO_O_RDONLY, 0700, 0,
11409 remote_hostio_close (self, fd, &remote_errno);
11411 ps = packet_support (PACKET_vFile_open);
11414 if (ps == PACKET_DISABLE)
11416 static int warning_issued = 0;
11418 if (!warning_issued)
11420 warning (_("remote target does not support file"
11421 " transfer, attempting to access files"
11422 " from local filesystem."));
11423 warning_issued = 1;
11434 remote_fileio_errno_to_host (int errnum)
11440 case FILEIO_ENOENT:
11448 case FILEIO_EACCES:
11450 case FILEIO_EFAULT:
11454 case FILEIO_EEXIST:
11456 case FILEIO_ENODEV:
11458 case FILEIO_ENOTDIR:
11460 case FILEIO_EISDIR:
11462 case FILEIO_EINVAL:
11464 case FILEIO_ENFILE:
11466 case FILEIO_EMFILE:
11470 case FILEIO_ENOSPC:
11472 case FILEIO_ESPIPE:
11476 case FILEIO_ENOSYS:
11478 case FILEIO_ENAMETOOLONG:
11479 return ENAMETOOLONG;
11485 remote_hostio_error (int errnum)
11487 int host_error = remote_fileio_errno_to_host (errnum);
11489 if (host_error == -1)
11490 error (_("Unknown remote I/O error %d"), errnum);
11492 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11496 remote_hostio_close_cleanup (void *opaque)
11498 int fd = *(int *) opaque;
11501 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11505 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11507 struct cleanup *back_to, *close_cleanup;
11508 int retcode, fd, remote_errno, bytes, io_size;
11511 int bytes_in_buffer;
11514 struct remote_state *rs = get_remote_state ();
11516 if (!rs->remote_desc)
11517 error (_("command can only be used with remote target"));
11519 file = gdb_fopen_cloexec (local_file, "rb");
11521 perror_with_name (local_file);
11522 back_to = make_cleanup_fclose (file);
11524 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11525 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11527 0700, 0, &remote_errno);
11529 remote_hostio_error (remote_errno);
11531 /* Send up to this many bytes at once. They won't all fit in the
11532 remote packet limit, so we'll transfer slightly fewer. */
11533 io_size = get_remote_packet_size ();
11534 buffer = (gdb_byte *) xmalloc (io_size);
11535 make_cleanup (xfree, buffer);
11537 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11539 bytes_in_buffer = 0;
11542 while (bytes_in_buffer || !saw_eof)
11546 bytes = fread (buffer + bytes_in_buffer, 1,
11547 io_size - bytes_in_buffer,
11552 error (_("Error reading %s."), local_file);
11555 /* EOF. Unless there is something still in the
11556 buffer from the last iteration, we are done. */
11558 if (bytes_in_buffer == 0)
11566 bytes += bytes_in_buffer;
11567 bytes_in_buffer = 0;
11569 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11571 offset, &remote_errno);
11574 remote_hostio_error (remote_errno);
11575 else if (retcode == 0)
11576 error (_("Remote write of %d bytes returned 0!"), bytes);
11577 else if (retcode < bytes)
11579 /* Short write. Save the rest of the read data for the next
11581 bytes_in_buffer = bytes - retcode;
11582 memmove (buffer, buffer + retcode, bytes_in_buffer);
11588 discard_cleanups (close_cleanup);
11589 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11590 remote_hostio_error (remote_errno);
11593 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11594 do_cleanups (back_to);
11598 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11600 struct cleanup *back_to, *close_cleanup;
11601 int fd, remote_errno, bytes, io_size;
11605 struct remote_state *rs = get_remote_state ();
11607 if (!rs->remote_desc)
11608 error (_("command can only be used with remote target"));
11610 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11611 remote_file, FILEIO_O_RDONLY, 0, 0,
11614 remote_hostio_error (remote_errno);
11616 file = gdb_fopen_cloexec (local_file, "wb");
11618 perror_with_name (local_file);
11619 back_to = make_cleanup_fclose (file);
11621 /* Send up to this many bytes at once. They won't all fit in the
11622 remote packet limit, so we'll transfer slightly fewer. */
11623 io_size = get_remote_packet_size ();
11624 buffer = (gdb_byte *) xmalloc (io_size);
11625 make_cleanup (xfree, buffer);
11627 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11632 bytes = remote_hostio_pread (find_target_at (process_stratum),
11633 fd, buffer, io_size, offset, &remote_errno);
11635 /* Success, but no bytes, means end-of-file. */
11638 remote_hostio_error (remote_errno);
11642 bytes = fwrite (buffer, 1, bytes, file);
11644 perror_with_name (local_file);
11647 discard_cleanups (close_cleanup);
11648 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11649 remote_hostio_error (remote_errno);
11652 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11653 do_cleanups (back_to);
11657 remote_file_delete (const char *remote_file, int from_tty)
11659 int retcode, remote_errno;
11660 struct remote_state *rs = get_remote_state ();
11662 if (!rs->remote_desc)
11663 error (_("command can only be used with remote target"));
11665 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11666 NULL, remote_file, &remote_errno);
11668 remote_hostio_error (remote_errno);
11671 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11675 remote_put_command (char *args, int from_tty)
11677 struct cleanup *back_to;
11681 error_no_arg (_("file to put"));
11683 argv = gdb_buildargv (args);
11684 back_to = make_cleanup_freeargv (argv);
11685 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11686 error (_("Invalid parameters to remote put"));
11688 remote_file_put (argv[0], argv[1], from_tty);
11690 do_cleanups (back_to);
11694 remote_get_command (char *args, int from_tty)
11696 struct cleanup *back_to;
11700 error_no_arg (_("file to get"));
11702 argv = gdb_buildargv (args);
11703 back_to = make_cleanup_freeargv (argv);
11704 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11705 error (_("Invalid parameters to remote get"));
11707 remote_file_get (argv[0], argv[1], from_tty);
11709 do_cleanups (back_to);
11713 remote_delete_command (char *args, int from_tty)
11715 struct cleanup *back_to;
11719 error_no_arg (_("file to delete"));
11721 argv = gdb_buildargv (args);
11722 back_to = make_cleanup_freeargv (argv);
11723 if (argv[0] == NULL || argv[1] != NULL)
11724 error (_("Invalid parameters to remote delete"));
11726 remote_file_delete (argv[0], from_tty);
11728 do_cleanups (back_to);
11732 remote_command (char *args, int from_tty)
11734 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11738 remote_can_execute_reverse (struct target_ops *self)
11740 if (packet_support (PACKET_bs) == PACKET_ENABLE
11741 || packet_support (PACKET_bc) == PACKET_ENABLE)
11748 remote_supports_non_stop (struct target_ops *self)
11754 remote_supports_disable_randomization (struct target_ops *self)
11756 /* Only supported in extended mode. */
11761 remote_supports_multi_process (struct target_ops *self)
11763 struct remote_state *rs = get_remote_state ();
11765 return remote_multi_process_p (rs);
11769 remote_supports_cond_tracepoints (void)
11771 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11775 remote_supports_cond_breakpoints (struct target_ops *self)
11777 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11781 remote_supports_fast_tracepoints (void)
11783 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11787 remote_supports_static_tracepoints (void)
11789 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11793 remote_supports_install_in_trace (void)
11795 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11799 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11801 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11806 remote_supports_string_tracing (struct target_ops *self)
11808 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11812 remote_can_run_breakpoint_commands (struct target_ops *self)
11814 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11818 remote_trace_init (struct target_ops *self)
11821 remote_get_noisy_reply (&target_buf, &target_buf_size);
11822 if (strcmp (target_buf, "OK") != 0)
11823 error (_("Target does not support this command."));
11826 static void free_actions_list (char **actions_list);
11827 static void free_actions_list_cleanup_wrapper (void *);
11829 free_actions_list_cleanup_wrapper (void *al)
11831 free_actions_list ((char **) al);
11835 free_actions_list (char **actions_list)
11839 if (actions_list == 0)
11842 for (ndx = 0; actions_list[ndx]; ndx++)
11843 xfree (actions_list[ndx]);
11845 xfree (actions_list);
11848 /* Recursive routine to walk through command list including loops, and
11849 download packets for each command. */
11852 remote_download_command_source (int num, ULONGEST addr,
11853 struct command_line *cmds)
11855 struct remote_state *rs = get_remote_state ();
11856 struct command_line *cmd;
11858 for (cmd = cmds; cmd; cmd = cmd->next)
11860 QUIT; /* Allow user to bail out with ^C. */
11861 strcpy (rs->buf, "QTDPsrc:");
11862 encode_source_string (num, addr, "cmd", cmd->line,
11863 rs->buf + strlen (rs->buf),
11864 rs->buf_size - strlen (rs->buf));
11866 remote_get_noisy_reply (&target_buf, &target_buf_size);
11867 if (strcmp (target_buf, "OK"))
11868 warning (_("Target does not support source download."));
11870 if (cmd->control_type == while_control
11871 || cmd->control_type == while_stepping_control)
11873 remote_download_command_source (num, addr, *cmd->body_list);
11875 QUIT; /* Allow user to bail out with ^C. */
11876 strcpy (rs->buf, "QTDPsrc:");
11877 encode_source_string (num, addr, "cmd", "end",
11878 rs->buf + strlen (rs->buf),
11879 rs->buf_size - strlen (rs->buf));
11881 remote_get_noisy_reply (&target_buf, &target_buf_size);
11882 if (strcmp (target_buf, "OK"))
11883 warning (_("Target does not support source download."));
11889 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11891 #define BUF_SIZE 2048
11895 char buf[BUF_SIZE];
11896 char **tdp_actions;
11897 char **stepping_actions;
11899 struct cleanup *old_chain = NULL;
11900 struct agent_expr *aexpr;
11901 struct cleanup *aexpr_chain = NULL;
11903 struct breakpoint *b = loc->owner;
11904 struct tracepoint *t = (struct tracepoint *) b;
11906 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11907 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11909 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11912 tpaddr = loc->address;
11913 sprintf_vma (addrbuf, tpaddr);
11914 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11915 addrbuf, /* address */
11916 (b->enable_state == bp_enabled ? 'E' : 'D'),
11917 t->step_count, t->pass_count);
11918 /* Fast tracepoints are mostly handled by the target, but we can
11919 tell the target how big of an instruction block should be moved
11921 if (b->type == bp_fast_tracepoint)
11923 /* Only test for support at download time; we may not know
11924 target capabilities at definition time. */
11925 if (remote_supports_fast_tracepoints ())
11927 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11929 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11930 gdb_insn_length (loc->gdbarch, tpaddr));
11932 /* If it passed validation at definition but fails now,
11933 something is very wrong. */
11934 internal_error (__FILE__, __LINE__,
11935 _("Fast tracepoint not "
11936 "valid during download"));
11939 /* Fast tracepoints are functionally identical to regular
11940 tracepoints, so don't take lack of support as a reason to
11941 give up on the trace run. */
11942 warning (_("Target does not support fast tracepoints, "
11943 "downloading %d as regular tracepoint"), b->number);
11945 else if (b->type == bp_static_tracepoint)
11947 /* Only test for support at download time; we may not know
11948 target capabilities at definition time. */
11949 if (remote_supports_static_tracepoints ())
11951 struct static_tracepoint_marker marker;
11953 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11954 strcat (buf, ":S");
11956 error (_("Static tracepoint not valid during download"));
11959 /* Fast tracepoints are functionally identical to regular
11960 tracepoints, so don't take lack of support as a reason
11961 to give up on the trace run. */
11962 error (_("Target does not support static tracepoints"));
11964 /* If the tracepoint has a conditional, make it into an agent
11965 expression and append to the definition. */
11968 /* Only test support at download time, we may not know target
11969 capabilities at definition time. */
11970 if (remote_supports_cond_tracepoints ())
11972 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11973 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11974 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11976 pkt = buf + strlen (buf);
11977 for (ndx = 0; ndx < aexpr->len; ++ndx)
11978 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11980 do_cleanups (aexpr_chain);
11983 warning (_("Target does not support conditional tracepoints, "
11984 "ignoring tp %d cond"), b->number);
11987 if (b->commands || *default_collect)
11990 remote_get_noisy_reply (&target_buf, &target_buf_size);
11991 if (strcmp (target_buf, "OK"))
11992 error (_("Target does not support tracepoints."));
11994 /* do_single_steps (t); */
11997 for (ndx = 0; tdp_actions[ndx]; ndx++)
11999 QUIT; /* Allow user to bail out with ^C. */
12000 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12001 b->number, addrbuf, /* address */
12003 ((tdp_actions[ndx + 1] || stepping_actions)
12006 remote_get_noisy_reply (&target_buf,
12008 if (strcmp (target_buf, "OK"))
12009 error (_("Error on target while setting tracepoints."));
12012 if (stepping_actions)
12014 for (ndx = 0; stepping_actions[ndx]; ndx++)
12016 QUIT; /* Allow user to bail out with ^C. */
12017 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12018 b->number, addrbuf, /* address */
12019 ((ndx == 0) ? "S" : ""),
12020 stepping_actions[ndx],
12021 (stepping_actions[ndx + 1] ? "-" : ""));
12023 remote_get_noisy_reply (&target_buf,
12025 if (strcmp (target_buf, "OK"))
12026 error (_("Error on target while setting tracepoints."));
12030 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12032 if (b->location != NULL)
12034 strcpy (buf, "QTDPsrc:");
12035 encode_source_string (b->number, loc->address, "at",
12036 event_location_to_string (b->location),
12037 buf + strlen (buf), 2048 - strlen (buf));
12039 remote_get_noisy_reply (&target_buf, &target_buf_size);
12040 if (strcmp (target_buf, "OK"))
12041 warning (_("Target does not support source download."));
12043 if (b->cond_string)
12045 strcpy (buf, "QTDPsrc:");
12046 encode_source_string (b->number, loc->address,
12047 "cond", b->cond_string, buf + strlen (buf),
12048 2048 - strlen (buf));
12050 remote_get_noisy_reply (&target_buf, &target_buf_size);
12051 if (strcmp (target_buf, "OK"))
12052 warning (_("Target does not support source download."));
12054 remote_download_command_source (b->number, loc->address,
12055 breakpoint_commands (b));
12058 do_cleanups (old_chain);
12062 remote_can_download_tracepoint (struct target_ops *self)
12064 struct remote_state *rs = get_remote_state ();
12065 struct trace_status *ts;
12068 /* Don't try to install tracepoints until we've relocated our
12069 symbols, and fetched and merged the target's tracepoint list with
12071 if (rs->starting_up)
12074 ts = current_trace_status ();
12075 status = remote_get_trace_status (self, ts);
12077 if (status == -1 || !ts->running_known || !ts->running)
12080 /* If we are in a tracing experiment, but remote stub doesn't support
12081 installing tracepoint in trace, we have to return. */
12082 if (!remote_supports_install_in_trace ())
12090 remote_download_trace_state_variable (struct target_ops *self,
12091 struct trace_state_variable *tsv)
12093 struct remote_state *rs = get_remote_state ();
12096 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12097 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12099 p = rs->buf + strlen (rs->buf);
12100 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12101 error (_("Trace state variable name too long for tsv definition packet"));
12102 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12105 remote_get_noisy_reply (&target_buf, &target_buf_size);
12106 if (*target_buf == '\0')
12107 error (_("Target does not support this command."));
12108 if (strcmp (target_buf, "OK") != 0)
12109 error (_("Error on target while downloading trace state variable."));
12113 remote_enable_tracepoint (struct target_ops *self,
12114 struct bp_location *location)
12116 struct remote_state *rs = get_remote_state ();
12119 sprintf_vma (addr_buf, location->address);
12120 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12121 location->owner->number, addr_buf);
12123 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12124 if (*rs->buf == '\0')
12125 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12126 if (strcmp (rs->buf, "OK") != 0)
12127 error (_("Error on target while enabling tracepoint."));
12131 remote_disable_tracepoint (struct target_ops *self,
12132 struct bp_location *location)
12134 struct remote_state *rs = get_remote_state ();
12137 sprintf_vma (addr_buf, location->address);
12138 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12139 location->owner->number, addr_buf);
12141 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12142 if (*rs->buf == '\0')
12143 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12144 if (strcmp (rs->buf, "OK") != 0)
12145 error (_("Error on target while disabling tracepoint."));
12149 remote_trace_set_readonly_regions (struct target_ops *self)
12153 bfd_size_type size;
12159 return; /* No information to give. */
12161 strcpy (target_buf, "QTro");
12162 offset = strlen (target_buf);
12163 for (s = exec_bfd->sections; s; s = s->next)
12165 char tmp1[40], tmp2[40];
12168 if ((s->flags & SEC_LOAD) == 0 ||
12169 /* (s->flags & SEC_CODE) == 0 || */
12170 (s->flags & SEC_READONLY) == 0)
12174 vma = bfd_get_section_vma (abfd, s);
12175 size = bfd_get_section_size (s);
12176 sprintf_vma (tmp1, vma);
12177 sprintf_vma (tmp2, vma + size);
12178 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12179 if (offset + sec_length + 1 > target_buf_size)
12181 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12183 Too many sections for read-only sections definition packet."));
12186 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12188 offset += sec_length;
12192 putpkt (target_buf);
12193 getpkt (&target_buf, &target_buf_size, 0);
12198 remote_trace_start (struct target_ops *self)
12200 putpkt ("QTStart");
12201 remote_get_noisy_reply (&target_buf, &target_buf_size);
12202 if (*target_buf == '\0')
12203 error (_("Target does not support this command."));
12204 if (strcmp (target_buf, "OK") != 0)
12205 error (_("Bogus reply from target: %s"), target_buf);
12209 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12211 /* Initialize it just to avoid a GCC false warning. */
12213 /* FIXME we need to get register block size some other way. */
12214 extern int trace_regblock_size;
12215 enum packet_result result;
12217 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12220 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12222 putpkt ("qTStatus");
12226 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12228 CATCH (ex, RETURN_MASK_ERROR)
12230 if (ex.error != TARGET_CLOSE_ERROR)
12232 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12235 throw_exception (ex);
12239 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12241 /* If the remote target doesn't do tracing, flag it. */
12242 if (result == PACKET_UNKNOWN)
12245 /* We're working with a live target. */
12246 ts->filename = NULL;
12249 error (_("Bogus trace status reply from target: %s"), target_buf);
12251 /* Function 'parse_trace_status' sets default value of each field of
12252 'ts' at first, so we don't have to do it here. */
12253 parse_trace_status (p, ts);
12255 return ts->running;
12259 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12260 struct uploaded_tp *utp)
12262 struct remote_state *rs = get_remote_state ();
12264 struct bp_location *loc;
12265 struct tracepoint *tp = (struct tracepoint *) bp;
12266 size_t size = get_remote_packet_size ();
12270 tp->base.hit_count = 0;
12271 tp->traceframe_usage = 0;
12272 for (loc = tp->base.loc; loc; loc = loc->next)
12274 /* If the tracepoint was never downloaded, don't go asking for
12276 if (tp->number_on_target == 0)
12278 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12279 phex_nz (loc->address, 0));
12281 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12282 if (reply && *reply)
12285 parse_tracepoint_status (reply + 1, bp, utp);
12291 utp->hit_count = 0;
12292 utp->traceframe_usage = 0;
12293 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12294 phex_nz (utp->addr, 0));
12296 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12297 if (reply && *reply)
12300 parse_tracepoint_status (reply + 1, bp, utp);
12306 remote_trace_stop (struct target_ops *self)
12309 remote_get_noisy_reply (&target_buf, &target_buf_size);
12310 if (*target_buf == '\0')
12311 error (_("Target does not support this command."));
12312 if (strcmp (target_buf, "OK") != 0)
12313 error (_("Bogus reply from target: %s"), target_buf);
12317 remote_trace_find (struct target_ops *self,
12318 enum trace_find_type type, int num,
12319 CORE_ADDR addr1, CORE_ADDR addr2,
12322 struct remote_state *rs = get_remote_state ();
12323 char *endbuf = rs->buf + get_remote_packet_size ();
12325 int target_frameno = -1, target_tracept = -1;
12327 /* Lookups other than by absolute frame number depend on the current
12328 trace selected, so make sure it is correct on the remote end
12330 if (type != tfind_number)
12331 set_remote_traceframe ();
12334 strcpy (p, "QTFrame:");
12335 p = strchr (p, '\0');
12339 xsnprintf (p, endbuf - p, "%x", num);
12342 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12345 xsnprintf (p, endbuf - p, "tdp:%x", num);
12348 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12349 phex_nz (addr2, 0));
12351 case tfind_outside:
12352 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12353 phex_nz (addr2, 0));
12356 error (_("Unknown trace find type %d"), type);
12360 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12361 if (*reply == '\0')
12362 error (_("Target does not support this command."));
12364 while (reply && *reply)
12369 target_frameno = (int) strtol (p, &reply, 16);
12371 error (_("Unable to parse trace frame number"));
12372 /* Don't update our remote traceframe number cache on failure
12373 to select a remote traceframe. */
12374 if (target_frameno == -1)
12379 target_tracept = (int) strtol (p, &reply, 16);
12381 error (_("Unable to parse tracepoint number"));
12383 case 'O': /* "OK"? */
12384 if (reply[1] == 'K' && reply[2] == '\0')
12387 error (_("Bogus reply from target: %s"), reply);
12390 error (_("Bogus reply from target: %s"), reply);
12393 *tpp = target_tracept;
12395 rs->remote_traceframe_number = target_frameno;
12396 return target_frameno;
12400 remote_get_trace_state_variable_value (struct target_ops *self,
12401 int tsvnum, LONGEST *val)
12403 struct remote_state *rs = get_remote_state ();
12407 set_remote_traceframe ();
12409 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12411 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12412 if (reply && *reply)
12416 unpack_varlen_hex (reply + 1, &uval);
12417 *val = (LONGEST) uval;
12425 remote_save_trace_data (struct target_ops *self, const char *filename)
12427 struct remote_state *rs = get_remote_state ();
12431 strcpy (p, "QTSave:");
12433 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12434 error (_("Remote file name too long for trace save packet"));
12435 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12438 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12439 if (*reply == '\0')
12440 error (_("Target does not support this command."));
12441 if (strcmp (reply, "OK") != 0)
12442 error (_("Bogus reply from target: %s"), reply);
12446 /* This is basically a memory transfer, but needs to be its own packet
12447 because we don't know how the target actually organizes its trace
12448 memory, plus we want to be able to ask for as much as possible, but
12449 not be unhappy if we don't get as much as we ask for. */
12452 remote_get_raw_trace_data (struct target_ops *self,
12453 gdb_byte *buf, ULONGEST offset, LONGEST len)
12455 struct remote_state *rs = get_remote_state ();
12461 strcpy (p, "qTBuffer:");
12463 p += hexnumstr (p, offset);
12465 p += hexnumstr (p, len);
12469 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12470 if (reply && *reply)
12472 /* 'l' by itself means we're at the end of the buffer and
12473 there is nothing more to get. */
12477 /* Convert the reply into binary. Limit the number of bytes to
12478 convert according to our passed-in buffer size, rather than
12479 what was returned in the packet; if the target is
12480 unexpectedly generous and gives us a bigger reply than we
12481 asked for, we don't want to crash. */
12482 rslt = hex2bin (target_buf, buf, len);
12486 /* Something went wrong, flag as an error. */
12491 remote_set_disconnected_tracing (struct target_ops *self, int val)
12493 struct remote_state *rs = get_remote_state ();
12495 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12499 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12501 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12502 if (*reply == '\0')
12503 error (_("Target does not support this command."));
12504 if (strcmp (reply, "OK") != 0)
12505 error (_("Bogus reply from target: %s"), reply);
12508 warning (_("Target does not support disconnected tracing."));
12512 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12514 struct thread_info *info = find_thread_ptid (ptid);
12516 if (info && info->priv)
12517 return info->priv->core;
12522 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12524 struct remote_state *rs = get_remote_state ();
12527 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12529 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12530 if (*reply == '\0')
12531 error (_("Target does not support this command."));
12532 if (strcmp (reply, "OK") != 0)
12533 error (_("Bogus reply from target: %s"), reply);
12536 static struct traceframe_info *
12537 remote_traceframe_info (struct target_ops *self)
12541 text = target_read_stralloc (¤t_target,
12542 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12545 struct traceframe_info *info;
12546 struct cleanup *back_to = make_cleanup (xfree, text);
12548 info = parse_traceframe_info (text);
12549 do_cleanups (back_to);
12556 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12557 instruction on which a fast tracepoint may be placed. Returns -1
12558 if the packet is not supported, and 0 if the minimum instruction
12559 length is unknown. */
12562 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12564 struct remote_state *rs = get_remote_state ();
12567 /* If we're not debugging a process yet, the IPA can't be
12569 if (!target_has_execution)
12572 /* Make sure the remote is pointing at the right process. */
12573 set_general_process ();
12575 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12577 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12578 if (*reply == '\0')
12582 ULONGEST min_insn_len;
12584 unpack_varlen_hex (reply, &min_insn_len);
12586 return (int) min_insn_len;
12591 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12593 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12595 struct remote_state *rs = get_remote_state ();
12596 char *buf = rs->buf;
12597 char *endbuf = rs->buf + get_remote_packet_size ();
12598 enum packet_result result;
12600 gdb_assert (val >= 0 || val == -1);
12601 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12602 /* Send -1 as literal "-1" to avoid host size dependency. */
12606 buf += hexnumstr (buf, (ULONGEST) -val);
12609 buf += hexnumstr (buf, (ULONGEST) val);
12612 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12613 result = packet_ok (rs->buf,
12614 &remote_protocol_packets[PACKET_QTBuffer_size]);
12616 if (result != PACKET_OK)
12617 warning (_("Bogus reply from target: %s"), rs->buf);
12622 remote_set_trace_notes (struct target_ops *self,
12623 const char *user, const char *notes,
12624 const char *stop_notes)
12626 struct remote_state *rs = get_remote_state ();
12628 char *buf = rs->buf;
12629 char *endbuf = rs->buf + get_remote_packet_size ();
12632 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12635 buf += xsnprintf (buf, endbuf - buf, "user:");
12636 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12642 buf += xsnprintf (buf, endbuf - buf, "notes:");
12643 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12649 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12650 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12654 /* Ensure the buffer is terminated. */
12658 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12659 if (*reply == '\0')
12662 if (strcmp (reply, "OK") != 0)
12663 error (_("Bogus reply from target: %s"), reply);
12669 remote_use_agent (struct target_ops *self, int use)
12671 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12673 struct remote_state *rs = get_remote_state ();
12675 /* If the stub supports QAgent. */
12676 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12678 getpkt (&rs->buf, &rs->buf_size, 0);
12680 if (strcmp (rs->buf, "OK") == 0)
12691 remote_can_use_agent (struct target_ops *self)
12693 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12696 struct btrace_target_info
12698 /* The ptid of the traced thread. */
12701 /* The obtained branch trace configuration. */
12702 struct btrace_config conf;
12705 /* Reset our idea of our target's btrace configuration. */
12708 remote_btrace_reset (void)
12710 struct remote_state *rs = get_remote_state ();
12712 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12715 /* Check whether the target supports branch tracing. */
12718 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12720 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12722 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12727 case BTRACE_FORMAT_NONE:
12730 case BTRACE_FORMAT_BTS:
12731 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12733 case BTRACE_FORMAT_PT:
12734 /* The trace is decoded on the host. Even if our target supports it,
12735 we still need to have libipt to decode the trace. */
12736 #if defined (HAVE_LIBIPT)
12737 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12738 #else /* !defined (HAVE_LIBIPT) */
12740 #endif /* !defined (HAVE_LIBIPT) */
12743 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12746 /* Synchronize the configuration with the target. */
12749 btrace_sync_conf (const struct btrace_config *conf)
12751 struct packet_config *packet;
12752 struct remote_state *rs;
12753 char *buf, *pos, *endbuf;
12755 rs = get_remote_state ();
12757 endbuf = buf + get_remote_packet_size ();
12759 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12760 if (packet_config_support (packet) == PACKET_ENABLE
12761 && conf->bts.size != rs->btrace_config.bts.size)
12764 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12768 getpkt (&buf, &rs->buf_size, 0);
12770 if (packet_ok (buf, packet) == PACKET_ERROR)
12772 if (buf[0] == 'E' && buf[1] == '.')
12773 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12775 error (_("Failed to configure the BTS buffer size."));
12778 rs->btrace_config.bts.size = conf->bts.size;
12781 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12782 if (packet_config_support (packet) == PACKET_ENABLE
12783 && conf->pt.size != rs->btrace_config.pt.size)
12786 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12790 getpkt (&buf, &rs->buf_size, 0);
12792 if (packet_ok (buf, packet) == PACKET_ERROR)
12794 if (buf[0] == 'E' && buf[1] == '.')
12795 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12797 error (_("Failed to configure the trace buffer size."));
12800 rs->btrace_config.pt.size = conf->pt.size;
12804 /* Read the current thread's btrace configuration from the target and
12805 store it into CONF. */
12808 btrace_read_config (struct btrace_config *conf)
12812 xml = target_read_stralloc (¤t_target,
12813 TARGET_OBJECT_BTRACE_CONF, "");
12816 struct cleanup *cleanup;
12818 cleanup = make_cleanup (xfree, xml);
12819 parse_xml_btrace_conf (conf, xml);
12820 do_cleanups (cleanup);
12824 /* Enable branch tracing. */
12826 static struct btrace_target_info *
12827 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12828 const struct btrace_config *conf)
12830 struct btrace_target_info *tinfo = NULL;
12831 struct packet_config *packet = NULL;
12832 struct remote_state *rs = get_remote_state ();
12833 char *buf = rs->buf;
12834 char *endbuf = rs->buf + get_remote_packet_size ();
12836 switch (conf->format)
12838 case BTRACE_FORMAT_BTS:
12839 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12842 case BTRACE_FORMAT_PT:
12843 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12847 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12848 error (_("Target does not support branch tracing."));
12850 btrace_sync_conf (conf);
12852 set_general_thread (ptid);
12854 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12856 getpkt (&rs->buf, &rs->buf_size, 0);
12858 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12860 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12861 error (_("Could not enable branch tracing for %s: %s"),
12862 target_pid_to_str (ptid), rs->buf + 2);
12864 error (_("Could not enable branch tracing for %s."),
12865 target_pid_to_str (ptid));
12868 tinfo = XCNEW (struct btrace_target_info);
12869 tinfo->ptid = ptid;
12871 /* If we fail to read the configuration, we lose some information, but the
12872 tracing itself is not impacted. */
12875 btrace_read_config (&tinfo->conf);
12877 CATCH (err, RETURN_MASK_ERROR)
12879 if (err.message != NULL)
12880 warning ("%s", err.message);
12887 /* Disable branch tracing. */
12890 remote_disable_btrace (struct target_ops *self,
12891 struct btrace_target_info *tinfo)
12893 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12894 struct remote_state *rs = get_remote_state ();
12895 char *buf = rs->buf;
12896 char *endbuf = rs->buf + get_remote_packet_size ();
12898 if (packet_config_support (packet) != PACKET_ENABLE)
12899 error (_("Target does not support branch tracing."));
12901 set_general_thread (tinfo->ptid);
12903 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12905 getpkt (&rs->buf, &rs->buf_size, 0);
12907 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12909 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12910 error (_("Could not disable branch tracing for %s: %s"),
12911 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12913 error (_("Could not disable branch tracing for %s."),
12914 target_pid_to_str (tinfo->ptid));
12920 /* Teardown branch tracing. */
12923 remote_teardown_btrace (struct target_ops *self,
12924 struct btrace_target_info *tinfo)
12926 /* We must not talk to the target during teardown. */
12930 /* Read the branch trace. */
12932 static enum btrace_error
12933 remote_read_btrace (struct target_ops *self,
12934 struct btrace_data *btrace,
12935 struct btrace_target_info *tinfo,
12936 enum btrace_read_type type)
12938 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12939 struct cleanup *cleanup;
12943 if (packet_config_support (packet) != PACKET_ENABLE)
12944 error (_("Target does not support branch tracing."));
12946 #if !defined(HAVE_LIBEXPAT)
12947 error (_("Cannot process branch tracing result. XML parsing not supported."));
12952 case BTRACE_READ_ALL:
12955 case BTRACE_READ_NEW:
12958 case BTRACE_READ_DELTA:
12962 internal_error (__FILE__, __LINE__,
12963 _("Bad branch tracing read type: %u."),
12964 (unsigned int) type);
12967 xml = target_read_stralloc (¤t_target,
12968 TARGET_OBJECT_BTRACE, annex);
12970 return BTRACE_ERR_UNKNOWN;
12972 cleanup = make_cleanup (xfree, xml);
12973 parse_xml_btrace (btrace, xml);
12974 do_cleanups (cleanup);
12976 return BTRACE_ERR_NONE;
12979 static const struct btrace_config *
12980 remote_btrace_conf (struct target_ops *self,
12981 const struct btrace_target_info *tinfo)
12983 return &tinfo->conf;
12987 remote_augmented_libraries_svr4_read (struct target_ops *self)
12989 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12993 /* Implementation of to_load. */
12996 remote_load (struct target_ops *self, const char *name, int from_tty)
12998 generic_load (name, from_tty);
13001 /* Accepts an integer PID; returns a string representing a file that
13002 can be opened on the remote side to get the symbols for the child
13003 process. Returns NULL if the operation is not supported. */
13006 remote_pid_to_exec_file (struct target_ops *self, int pid)
13008 static char *filename = NULL;
13009 struct inferior *inf;
13010 char *annex = NULL;
13012 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13015 if (filename != NULL)
13018 inf = find_inferior_pid (pid);
13020 internal_error (__FILE__, __LINE__,
13021 _("not currently attached to process %d"), pid);
13023 if (!inf->fake_pid_p)
13025 const int annex_size = 9;
13027 annex = (char *) alloca (annex_size);
13028 xsnprintf (annex, annex_size, "%x", pid);
13031 filename = target_read_stralloc (¤t_target,
13032 TARGET_OBJECT_EXEC_FILE, annex);
13037 /* Implement the to_can_do_single_step target_ops method. */
13040 remote_can_do_single_step (struct target_ops *ops)
13042 /* We can only tell whether target supports single step or not by
13043 supported s and S vCont actions if the stub supports vContSupported
13044 feature. If the stub doesn't support vContSupported feature,
13045 we have conservatively to think target doesn't supports single
13047 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13049 struct remote_state *rs = get_remote_state ();
13051 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13052 remote_vcont_probe (rs);
13054 return rs->supports_vCont.s && rs->supports_vCont.S;
13061 init_remote_ops (void)
13063 remote_ops.to_shortname = "remote";
13064 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13065 remote_ops.to_doc =
13066 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13067 Specify the serial device it is connected to\n\
13068 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13069 remote_ops.to_open = remote_open;
13070 remote_ops.to_close = remote_close;
13071 remote_ops.to_detach = remote_detach;
13072 remote_ops.to_disconnect = remote_disconnect;
13073 remote_ops.to_resume = remote_resume;
13074 remote_ops.to_wait = remote_wait;
13075 remote_ops.to_fetch_registers = remote_fetch_registers;
13076 remote_ops.to_store_registers = remote_store_registers;
13077 remote_ops.to_prepare_to_store = remote_prepare_to_store;
13078 remote_ops.to_files_info = remote_files_info;
13079 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13080 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13081 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13082 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13083 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13084 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13085 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13086 remote_ops.to_stopped_data_address = remote_stopped_data_address;
13087 remote_ops.to_watchpoint_addr_within_range =
13088 remote_watchpoint_addr_within_range;
13089 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13090 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13091 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13092 remote_ops.to_region_ok_for_hw_watchpoint
13093 = remote_region_ok_for_hw_watchpoint;
13094 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13095 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13096 remote_ops.to_kill = remote_kill;
13097 remote_ops.to_load = remote_load;
13098 remote_ops.to_mourn_inferior = remote_mourn;
13099 remote_ops.to_pass_signals = remote_pass_signals;
13100 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13101 remote_ops.to_program_signals = remote_program_signals;
13102 remote_ops.to_thread_alive = remote_thread_alive;
13103 remote_ops.to_thread_name = remote_thread_name;
13104 remote_ops.to_update_thread_list = remote_update_thread_list;
13105 remote_ops.to_pid_to_str = remote_pid_to_str;
13106 remote_ops.to_extra_thread_info = remote_threads_extra_info;
13107 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13108 remote_ops.to_stop = remote_stop;
13109 remote_ops.to_interrupt = remote_interrupt;
13110 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
13111 remote_ops.to_xfer_partial = remote_xfer_partial;
13112 remote_ops.to_rcmd = remote_rcmd;
13113 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13114 remote_ops.to_log_command = serial_log_command;
13115 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13116 remote_ops.to_stratum = process_stratum;
13117 remote_ops.to_has_all_memory = default_child_has_all_memory;
13118 remote_ops.to_has_memory = default_child_has_memory;
13119 remote_ops.to_has_stack = default_child_has_stack;
13120 remote_ops.to_has_registers = default_child_has_registers;
13121 remote_ops.to_has_execution = default_child_has_execution;
13122 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
13123 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13124 remote_ops.to_magic = OPS_MAGIC;
13125 remote_ops.to_memory_map = remote_memory_map;
13126 remote_ops.to_flash_erase = remote_flash_erase;
13127 remote_ops.to_flash_done = remote_flash_done;
13128 remote_ops.to_read_description = remote_read_description;
13129 remote_ops.to_search_memory = remote_search_memory;
13130 remote_ops.to_can_async_p = remote_can_async_p;
13131 remote_ops.to_is_async_p = remote_is_async_p;
13132 remote_ops.to_async = remote_async;
13133 remote_ops.to_thread_events = remote_thread_events;
13134 remote_ops.to_can_do_single_step = remote_can_do_single_step;
13135 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13136 remote_ops.to_terminal_ours = remote_terminal_ours;
13137 remote_ops.to_supports_non_stop = remote_supports_non_stop;
13138 remote_ops.to_supports_multi_process = remote_supports_multi_process;
13139 remote_ops.to_supports_disable_randomization
13140 = remote_supports_disable_randomization;
13141 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13142 remote_ops.to_fileio_open = remote_hostio_open;
13143 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13144 remote_ops.to_fileio_pread = remote_hostio_pread;
13145 remote_ops.to_fileio_fstat = remote_hostio_fstat;
13146 remote_ops.to_fileio_close = remote_hostio_close;
13147 remote_ops.to_fileio_unlink = remote_hostio_unlink;
13148 remote_ops.to_fileio_readlink = remote_hostio_readlink;
13149 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13150 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13151 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13152 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13153 remote_ops.to_trace_init = remote_trace_init;
13154 remote_ops.to_download_tracepoint = remote_download_tracepoint;
13155 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13156 remote_ops.to_download_trace_state_variable
13157 = remote_download_trace_state_variable;
13158 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13159 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13160 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13161 remote_ops.to_trace_start = remote_trace_start;
13162 remote_ops.to_get_trace_status = remote_get_trace_status;
13163 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13164 remote_ops.to_trace_stop = remote_trace_stop;
13165 remote_ops.to_trace_find = remote_trace_find;
13166 remote_ops.to_get_trace_state_variable_value
13167 = remote_get_trace_state_variable_value;
13168 remote_ops.to_save_trace_data = remote_save_trace_data;
13169 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13170 remote_ops.to_upload_trace_state_variables
13171 = remote_upload_trace_state_variables;
13172 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13173 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13174 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13175 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13176 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13177 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13178 remote_ops.to_core_of_thread = remote_core_of_thread;
13179 remote_ops.to_verify_memory = remote_verify_memory;
13180 remote_ops.to_get_tib_address = remote_get_tib_address;
13181 remote_ops.to_set_permissions = remote_set_permissions;
13182 remote_ops.to_static_tracepoint_marker_at
13183 = remote_static_tracepoint_marker_at;
13184 remote_ops.to_static_tracepoint_markers_by_strid
13185 = remote_static_tracepoint_markers_by_strid;
13186 remote_ops.to_traceframe_info = remote_traceframe_info;
13187 remote_ops.to_use_agent = remote_use_agent;
13188 remote_ops.to_can_use_agent = remote_can_use_agent;
13189 remote_ops.to_supports_btrace = remote_supports_btrace;
13190 remote_ops.to_enable_btrace = remote_enable_btrace;
13191 remote_ops.to_disable_btrace = remote_disable_btrace;
13192 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13193 remote_ops.to_read_btrace = remote_read_btrace;
13194 remote_ops.to_btrace_conf = remote_btrace_conf;
13195 remote_ops.to_augmented_libraries_svr4_read =
13196 remote_augmented_libraries_svr4_read;
13197 remote_ops.to_follow_fork = remote_follow_fork;
13198 remote_ops.to_follow_exec = remote_follow_exec;
13199 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13200 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13201 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13202 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13203 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13204 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13207 /* Set up the extended remote vector by making a copy of the standard
13208 remote vector and adding to it. */
13211 init_extended_remote_ops (void)
13213 extended_remote_ops = remote_ops;
13215 extended_remote_ops.to_shortname = "extended-remote";
13216 extended_remote_ops.to_longname =
13217 "Extended remote serial target in gdb-specific protocol";
13218 extended_remote_ops.to_doc =
13219 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13220 Specify the serial device it is connected to (e.g. /dev/ttya).";
13221 extended_remote_ops.to_open = extended_remote_open;
13222 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13223 extended_remote_ops.to_detach = extended_remote_detach;
13224 extended_remote_ops.to_attach = extended_remote_attach;
13225 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13226 extended_remote_ops.to_supports_disable_randomization
13227 = extended_remote_supports_disable_randomization;
13231 remote_can_async_p (struct target_ops *ops)
13233 struct remote_state *rs = get_remote_state ();
13235 if (!target_async_permitted)
13236 /* We only enable async when the user specifically asks for it. */
13239 /* We're async whenever the serial device is. */
13240 return serial_can_async_p (rs->remote_desc);
13244 remote_is_async_p (struct target_ops *ops)
13246 struct remote_state *rs = get_remote_state ();
13248 if (!target_async_permitted)
13249 /* We only enable async when the user specifically asks for it. */
13252 /* We're async whenever the serial device is. */
13253 return serial_is_async_p (rs->remote_desc);
13256 /* Pass the SERIAL event on and up to the client. One day this code
13257 will be able to delay notifying the client of an event until the
13258 point where an entire packet has been received. */
13260 static serial_event_ftype remote_async_serial_handler;
13263 remote_async_serial_handler (struct serial *scb, void *context)
13265 /* Don't propogate error information up to the client. Instead let
13266 the client find out about the error by querying the target. */
13267 inferior_event_handler (INF_REG_EVENT, NULL);
13271 remote_async_inferior_event_handler (gdb_client_data data)
13273 inferior_event_handler (INF_REG_EVENT, NULL);
13277 remote_async (struct target_ops *ops, int enable)
13279 struct remote_state *rs = get_remote_state ();
13283 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13285 /* If there are pending events in the stop reply queue tell the
13286 event loop to process them. */
13287 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13288 mark_async_event_handler (remote_async_inferior_event_token);
13289 /* For simplicity, below we clear the pending events token
13290 without remembering whether it is marked, so here we always
13291 mark it. If there's actually no pending notification to
13292 process, this ends up being a no-op (other than a spurious
13293 event-loop wakeup). */
13294 if (target_is_non_stop_p ())
13295 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13299 serial_async (rs->remote_desc, NULL, NULL);
13300 /* If the core is disabling async, it doesn't want to be
13301 disturbed with target events. Clear all async event sources
13303 clear_async_event_handler (remote_async_inferior_event_token);
13304 if (target_is_non_stop_p ())
13305 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13309 /* Implementation of the to_thread_events method. */
13312 remote_thread_events (struct target_ops *ops, int enable)
13314 struct remote_state *rs = get_remote_state ();
13315 size_t size = get_remote_packet_size ();
13317 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13320 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13322 getpkt (&rs->buf, &rs->buf_size, 0);
13324 switch (packet_ok (rs->buf,
13325 &remote_protocol_packets[PACKET_QThreadEvents]))
13328 if (strcmp (rs->buf, "OK") != 0)
13329 error (_("Remote refused setting thread events: %s"), rs->buf);
13332 warning (_("Remote failure reply: %s"), rs->buf);
13334 case PACKET_UNKNOWN:
13340 set_remote_cmd (char *args, int from_tty)
13342 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13346 show_remote_cmd (char *args, int from_tty)
13348 /* We can't just use cmd_show_list here, because we want to skip
13349 the redundant "show remote Z-packet" and the legacy aliases. */
13350 struct cleanup *showlist_chain;
13351 struct cmd_list_element *list = remote_show_cmdlist;
13352 struct ui_out *uiout = current_uiout;
13354 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13355 for (; list != NULL; list = list->next)
13356 if (strcmp (list->name, "Z-packet") == 0)
13358 else if (list->type == not_set_cmd)
13359 /* Alias commands are exactly like the original, except they
13360 don't have the normal type. */
13364 struct cleanup *option_chain
13365 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13367 ui_out_field_string (uiout, "name", list->name);
13368 ui_out_text (uiout, ": ");
13369 if (list->type == show_cmd)
13370 do_show_command ((char *) NULL, from_tty, list);
13372 cmd_func (list, NULL, from_tty);
13373 /* Close the tuple. */
13374 do_cleanups (option_chain);
13377 /* Close the tuple. */
13378 do_cleanups (showlist_chain);
13382 /* Function to be called whenever a new objfile (shlib) is detected. */
13384 remote_new_objfile (struct objfile *objfile)
13386 struct remote_state *rs = get_remote_state ();
13388 if (rs->remote_desc != 0) /* Have a remote connection. */
13389 remote_check_symbols ();
13392 /* Pull all the tracepoints defined on the target and create local
13393 data structures representing them. We don't want to create real
13394 tracepoints yet, we don't want to mess up the user's existing
13398 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13400 struct remote_state *rs = get_remote_state ();
13403 /* Ask for a first packet of tracepoint definition. */
13405 getpkt (&rs->buf, &rs->buf_size, 0);
13407 while (*p && *p != 'l')
13409 parse_tracepoint_definition (p, utpp);
13410 /* Ask for another packet of tracepoint definition. */
13412 getpkt (&rs->buf, &rs->buf_size, 0);
13419 remote_upload_trace_state_variables (struct target_ops *self,
13420 struct uploaded_tsv **utsvp)
13422 struct remote_state *rs = get_remote_state ();
13425 /* Ask for a first packet of variable definition. */
13427 getpkt (&rs->buf, &rs->buf_size, 0);
13429 while (*p && *p != 'l')
13431 parse_tsv_definition (p, utsvp);
13432 /* Ask for another packet of variable definition. */
13434 getpkt (&rs->buf, &rs->buf_size, 0);
13440 /* The "set/show range-stepping" show hook. */
13443 show_range_stepping (struct ui_file *file, int from_tty,
13444 struct cmd_list_element *c,
13447 fprintf_filtered (file,
13448 _("Debugger's willingness to use range stepping "
13449 "is %s.\n"), value);
13452 /* The "set/show range-stepping" set hook. */
13455 set_range_stepping (char *ignore_args, int from_tty,
13456 struct cmd_list_element *c)
13458 struct remote_state *rs = get_remote_state ();
13460 /* Whene enabling, check whether range stepping is actually
13461 supported by the target, and warn if not. */
13462 if (use_range_stepping)
13464 if (rs->remote_desc != NULL)
13466 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13467 remote_vcont_probe (rs);
13469 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13470 && rs->supports_vCont.r)
13474 warning (_("Range stepping is not supported by the current target"));
13479 _initialize_remote (void)
13481 struct cmd_list_element *cmd;
13482 const char *cmd_name;
13484 /* architecture specific data */
13485 remote_gdbarch_data_handle =
13486 gdbarch_data_register_post_init (init_remote_state);
13487 remote_g_packet_data_handle =
13488 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13491 = register_program_space_data_with_cleanup (NULL,
13492 remote_pspace_data_cleanup);
13494 /* Initialize the per-target state. At the moment there is only one
13495 of these, not one per target. Only one target is active at a
13497 remote_state = new_remote_state ();
13499 init_remote_ops ();
13500 add_target (&remote_ops);
13502 init_extended_remote_ops ();
13503 add_target (&extended_remote_ops);
13505 /* Hook into new objfile notification. */
13506 observer_attach_new_objfile (remote_new_objfile);
13507 /* We're no longer interested in notification events of an inferior
13509 observer_attach_inferior_exit (discard_pending_stop_replies);
13511 /* Set up signal handlers. */
13512 async_sigint_remote_token =
13513 create_async_signal_handler (async_remote_interrupt, NULL);
13514 async_sigint_remote_twice_token =
13515 create_async_signal_handler (async_remote_interrupt_twice, NULL);
13518 init_remote_threadtests ();
13521 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13522 /* set/show remote ... */
13524 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13525 Remote protocol specific variables\n\
13526 Configure various remote-protocol specific variables such as\n\
13527 the packets being used"),
13528 &remote_set_cmdlist, "set remote ",
13529 0 /* allow-unknown */, &setlist);
13530 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13531 Remote protocol specific variables\n\
13532 Configure various remote-protocol specific variables such as\n\
13533 the packets being used"),
13534 &remote_show_cmdlist, "show remote ",
13535 0 /* allow-unknown */, &showlist);
13537 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13538 Compare section data on target to the exec file.\n\
13539 Argument is a single section name (default: all loaded sections).\n\
13540 To compare only read-only loaded sections, specify the -r option."),
13543 add_cmd ("packet", class_maintenance, packet_command, _("\
13544 Send an arbitrary packet to a remote target.\n\
13545 maintenance packet TEXT\n\
13546 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13547 this command sends the string TEXT to the inferior, and displays the\n\
13548 response packet. GDB supplies the initial `$' character, and the\n\
13549 terminating `#' character and checksum."),
13552 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13553 Set whether to send break if interrupted."), _("\
13554 Show whether to send break if interrupted."), _("\
13555 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13556 set_remotebreak, show_remotebreak,
13557 &setlist, &showlist);
13558 cmd_name = "remotebreak";
13559 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13560 deprecate_cmd (cmd, "set remote interrupt-sequence");
13561 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13562 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13563 deprecate_cmd (cmd, "show remote interrupt-sequence");
13565 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13566 interrupt_sequence_modes, &interrupt_sequence_mode,
13568 Set interrupt sequence to remote target."), _("\
13569 Show interrupt sequence to remote target."), _("\
13570 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13571 NULL, show_interrupt_sequence,
13572 &remote_set_cmdlist,
13573 &remote_show_cmdlist);
13575 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13576 &interrupt_on_connect, _("\
13577 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13578 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13579 If set, interrupt sequence is sent to remote target."),
13581 &remote_set_cmdlist, &remote_show_cmdlist);
13583 /* Install commands for configuring memory read/write packets. */
13585 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13586 Set the maximum number of bytes per memory write packet (deprecated)."),
13588 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13589 Show the maximum number of bytes per memory write packet (deprecated)."),
13591 add_cmd ("memory-write-packet-size", no_class,
13592 set_memory_write_packet_size, _("\
13593 Set the maximum number of bytes per memory-write packet.\n\
13594 Specify the number of bytes in a packet or 0 (zero) for the\n\
13595 default packet size. The actual limit is further reduced\n\
13596 dependent on the target. Specify ``fixed'' to disable the\n\
13597 further restriction and ``limit'' to enable that restriction."),
13598 &remote_set_cmdlist);
13599 add_cmd ("memory-read-packet-size", no_class,
13600 set_memory_read_packet_size, _("\
13601 Set the maximum number of bytes per memory-read packet.\n\
13602 Specify the number of bytes in a packet or 0 (zero) for the\n\
13603 default packet size. The actual limit is further reduced\n\
13604 dependent on the target. Specify ``fixed'' to disable the\n\
13605 further restriction and ``limit'' to enable that restriction."),
13606 &remote_set_cmdlist);
13607 add_cmd ("memory-write-packet-size", no_class,
13608 show_memory_write_packet_size,
13609 _("Show the maximum number of bytes per memory-write packet."),
13610 &remote_show_cmdlist);
13611 add_cmd ("memory-read-packet-size", no_class,
13612 show_memory_read_packet_size,
13613 _("Show the maximum number of bytes per memory-read packet."),
13614 &remote_show_cmdlist);
13616 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13617 &remote_hw_watchpoint_limit, _("\
13618 Set the maximum number of target hardware watchpoints."), _("\
13619 Show the maximum number of target hardware watchpoints."), _("\
13620 Specify a negative limit for unlimited."),
13621 NULL, NULL, /* FIXME: i18n: The maximum
13622 number of target hardware
13623 watchpoints is %s. */
13624 &remote_set_cmdlist, &remote_show_cmdlist);
13625 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13626 &remote_hw_watchpoint_length_limit, _("\
13627 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13628 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13629 Specify a negative limit for unlimited."),
13630 NULL, NULL, /* FIXME: i18n: The maximum
13631 length (in bytes) of a target
13632 hardware watchpoint is %s. */
13633 &remote_set_cmdlist, &remote_show_cmdlist);
13634 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13635 &remote_hw_breakpoint_limit, _("\
13636 Set the maximum number of target hardware breakpoints."), _("\
13637 Show the maximum number of target hardware breakpoints."), _("\
13638 Specify a negative limit for unlimited."),
13639 NULL, NULL, /* FIXME: i18n: The maximum
13640 number of target hardware
13641 breakpoints is %s. */
13642 &remote_set_cmdlist, &remote_show_cmdlist);
13644 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13645 &remote_address_size, _("\
13646 Set the maximum size of the address (in bits) in a memory packet."), _("\
13647 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13649 NULL, /* FIXME: i18n: */
13650 &setlist, &showlist);
13652 init_all_packet_configs ();
13654 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13655 "X", "binary-download", 1);
13657 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13658 "vCont", "verbose-resume", 0);
13660 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13661 "QPassSignals", "pass-signals", 0);
13663 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13664 "QCatchSyscalls", "catch-syscalls", 0);
13666 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13667 "QProgramSignals", "program-signals", 0);
13669 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13670 "qSymbol", "symbol-lookup", 0);
13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13673 "P", "set-register", 1);
13675 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13676 "p", "fetch-register", 1);
13678 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13679 "Z0", "software-breakpoint", 0);
13681 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13682 "Z1", "hardware-breakpoint", 0);
13684 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13685 "Z2", "write-watchpoint", 0);
13687 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13688 "Z3", "read-watchpoint", 0);
13690 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13691 "Z4", "access-watchpoint", 0);
13693 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13694 "qXfer:auxv:read", "read-aux-vector", 0);
13696 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13697 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13699 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13700 "qXfer:features:read", "target-features", 0);
13702 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13703 "qXfer:libraries:read", "library-info", 0);
13705 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13706 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13708 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13709 "qXfer:memory-map:read", "memory-map", 0);
13711 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13712 "qXfer:spu:read", "read-spu-object", 0);
13714 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13715 "qXfer:spu:write", "write-spu-object", 0);
13717 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13718 "qXfer:osdata:read", "osdata", 0);
13720 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13721 "qXfer:threads:read", "threads", 0);
13723 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13724 "qXfer:siginfo:read", "read-siginfo-object", 0);
13726 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13727 "qXfer:siginfo:write", "write-siginfo-object", 0);
13729 add_packet_config_cmd
13730 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13731 "qXfer:traceframe-info:read", "traceframe-info", 0);
13733 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13734 "qXfer:uib:read", "unwind-info-block", 0);
13736 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13737 "qGetTLSAddr", "get-thread-local-storage-address",
13740 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13741 "qGetTIBAddr", "get-thread-information-block-address",
13744 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13745 "bc", "reverse-continue", 0);
13747 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13748 "bs", "reverse-step", 0);
13750 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13751 "qSupported", "supported-packets", 0);
13753 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13754 "qSearch:memory", "search-memory", 0);
13756 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13757 "qTStatus", "trace-status", 0);
13759 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13760 "vFile:setfs", "hostio-setfs", 0);
13762 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13763 "vFile:open", "hostio-open", 0);
13765 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13766 "vFile:pread", "hostio-pread", 0);
13768 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13769 "vFile:pwrite", "hostio-pwrite", 0);
13771 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13772 "vFile:close", "hostio-close", 0);
13774 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13775 "vFile:unlink", "hostio-unlink", 0);
13777 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13778 "vFile:readlink", "hostio-readlink", 0);
13780 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13781 "vFile:fstat", "hostio-fstat", 0);
13783 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13784 "vAttach", "attach", 0);
13786 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13789 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13790 "QStartNoAckMode", "noack", 0);
13792 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13793 "vKill", "kill", 0);
13795 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13796 "qAttached", "query-attached", 0);
13798 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13799 "ConditionalTracepoints",
13800 "conditional-tracepoints", 0);
13802 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13803 "ConditionalBreakpoints",
13804 "conditional-breakpoints", 0);
13806 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13807 "BreakpointCommands",
13808 "breakpoint-commands", 0);
13810 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13811 "FastTracepoints", "fast-tracepoints", 0);
13813 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13814 "TracepointSource", "TracepointSource", 0);
13816 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13817 "QAllow", "allow", 0);
13819 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13820 "StaticTracepoints", "static-tracepoints", 0);
13822 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13823 "InstallInTrace", "install-in-trace", 0);
13825 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13826 "qXfer:statictrace:read", "read-sdata-object", 0);
13828 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13829 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13831 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13832 "QDisableRandomization", "disable-randomization", 0);
13834 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13835 "QAgent", "agent", 0);
13837 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13838 "QTBuffer:size", "trace-buffer-size", 0);
13840 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13841 "Qbtrace:off", "disable-btrace", 0);
13843 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13844 "Qbtrace:bts", "enable-btrace-bts", 0);
13846 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13847 "Qbtrace:pt", "enable-btrace-pt", 0);
13849 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13850 "qXfer:btrace", "read-btrace", 0);
13852 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13853 "qXfer:btrace-conf", "read-btrace-conf", 0);
13855 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13856 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13858 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13859 "multiprocess-feature", "multiprocess-feature", 0);
13861 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13862 "swbreak-feature", "swbreak-feature", 0);
13864 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13865 "hwbreak-feature", "hwbreak-feature", 0);
13867 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13868 "fork-event-feature", "fork-event-feature", 0);
13870 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13871 "vfork-event-feature", "vfork-event-feature", 0);
13873 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13874 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13876 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13877 "vContSupported", "verbose-resume-supported", 0);
13879 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13880 "exec-event-feature", "exec-event-feature", 0);
13882 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13883 "vCtrlC", "ctrl-c", 0);
13885 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13886 "QThreadEvents", "thread-events", 0);
13888 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13889 "N stop reply", "no-resumed-stop-reply", 0);
13891 /* Assert that we've registered "set remote foo-packet" commands
13892 for all packet configs. */
13896 for (i = 0; i < PACKET_MAX; i++)
13898 /* Ideally all configs would have a command associated. Some
13899 still don't though. */
13904 case PACKET_QNonStop:
13905 case PACKET_EnableDisableTracepoints_feature:
13906 case PACKET_tracenz_feature:
13907 case PACKET_DisconnectedTracing_feature:
13908 case PACKET_augmented_libraries_svr4_read_feature:
13910 /* Additions to this list need to be well justified:
13911 pre-existing packets are OK; new packets are not. */
13919 /* This catches both forgetting to add a config command, and
13920 forgetting to remove a packet from the exception list. */
13921 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13925 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13926 Z sub-packet has its own set and show commands, but users may
13927 have sets to this variable in their .gdbinit files (or in their
13929 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13930 &remote_Z_packet_detect, _("\
13931 Set use of remote protocol `Z' packets"), _("\
13932 Show use of remote protocol `Z' packets "), _("\
13933 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13935 set_remote_protocol_Z_packet_cmd,
13936 show_remote_protocol_Z_packet_cmd,
13937 /* FIXME: i18n: Use of remote protocol
13938 `Z' packets is %s. */
13939 &remote_set_cmdlist, &remote_show_cmdlist);
13941 add_prefix_cmd ("remote", class_files, remote_command, _("\
13942 Manipulate files on the remote system\n\
13943 Transfer files to and from the remote target system."),
13944 &remote_cmdlist, "remote ",
13945 0 /* allow-unknown */, &cmdlist);
13947 add_cmd ("put", class_files, remote_put_command,
13948 _("Copy a local file to the remote system."),
13951 add_cmd ("get", class_files, remote_get_command,
13952 _("Copy a remote file to the local system."),
13955 add_cmd ("delete", class_files, remote_delete_command,
13956 _("Delete a remote file."),
13959 add_setshow_string_noescape_cmd ("exec-file", class_files,
13960 &remote_exec_file_var, _("\
13961 Set the remote pathname for \"run\""), _("\
13962 Show the remote pathname for \"run\""), NULL,
13963 set_remote_exec_file,
13964 show_remote_exec_file,
13965 &remote_set_cmdlist,
13966 &remote_show_cmdlist);
13968 add_setshow_boolean_cmd ("range-stepping", class_run,
13969 &use_range_stepping, _("\
13970 Enable or disable range stepping."), _("\
13971 Show whether target-assisted range stepping is enabled."), _("\
13972 If on, and the target supports it, when stepping a source line, GDB\n\
13973 tells the target to step the corresponding range of addresses itself instead\n\
13974 of issuing multiple single-steps. This speeds up source level\n\
13975 stepping. If off, GDB always issues single-steps, even if range\n\
13976 stepping is supported by the target. The default is on."),
13977 set_range_stepping,
13978 show_range_stepping,
13982 /* Eventually initialize fileio. See fileio.c */
13983 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13985 /* Take advantage of the fact that the TID field is not used, to tag
13986 special ptids with it set to != 0. */
13987 magic_null_ptid = ptid_build (42000, -1, 1);
13988 not_sent_ptid = ptid_build (42000, -2, 1);
13989 any_thread_ptid = ptid_build (42000, 0, 1);
13991 target_buf_size = 2048;
13992 target_buf = (char *) xmalloc (target_buf_size);