1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
30 /*#include "terminal.h" */
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
36 #include "remote-notif.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
50 #include "gdb_sys_time.h"
52 #include "event-loop.h"
53 #include "event-top.h"
59 #include "gdbcore.h" /* for exec_bfd */
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
74 /* Temp hacks for tracepoint encoding migration. */
75 static char *target_buf;
76 static long target_buf_size;
78 /* 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_mourn (struct target_ops *ops);
124 static void extended_remote_restart (void);
126 static void extended_remote_mourn (struct target_ops *);
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 sync_remote_interrupt_twice (int signo);
144 static void interrupt_query (void);
146 static void set_general_thread (struct ptid ptid);
147 static void set_continue_thread (struct ptid ptid);
149 static void get_offsets (void);
151 static void skip_frame (void);
153 static long read_frame (char **buf_p, long *sizeof_buf);
155 static int hexnumlen (ULONGEST num);
157 static void init_remote_ops (void);
159 static void init_extended_remote_ops (void);
161 static void remote_stop (struct target_ops *self, ptid_t);
163 static int stubhex (int ch);
165 static int hexnumstr (char *, ULONGEST);
167 static int hexnumnstr (char *, ULONGEST, int);
169 static CORE_ADDR remote_address_masked (CORE_ADDR);
171 static void print_packet (const char *);
173 static void compare_sections_command (char *, int);
175 static void packet_command (char *, int);
177 static int stub_unpack_int (char *buff, int fieldlength);
179 static ptid_t remote_current_thread (ptid_t oldptid);
181 static int putpkt_binary (const char *buf, int cnt);
183 static void check_binary_download (CORE_ADDR addr);
185 struct packet_config;
187 static void show_packet_config_cmd (struct packet_config *config);
189 static void show_remote_protocol_packet_cmd (struct ui_file *file,
191 struct cmd_list_element *c,
194 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
195 static ptid_t read_ptid (char *buf, char **obuf);
197 static void remote_set_permissions (struct target_ops *self);
199 static int remote_get_trace_status (struct target_ops *self,
200 struct trace_status *ts);
202 static int remote_upload_tracepoints (struct target_ops *self,
203 struct uploaded_tp **utpp);
205 static int remote_upload_trace_state_variables (struct target_ops *self,
206 struct uploaded_tsv **utsvp);
208 static void remote_query_supported (void);
210 static void remote_check_symbols (void);
212 void _initialize_remote (void);
215 static void stop_reply_xfree (struct stop_reply *);
216 static void remote_parse_stop_reply (char *, struct stop_reply *);
217 static void push_stop_reply (struct stop_reply *);
218 static void discard_pending_stop_replies_in_queue (struct remote_state *);
219 static int peek_stop_reply (ptid_t ptid);
221 struct threads_listing_context;
222 static void remove_new_fork_children (struct threads_listing_context *);
224 static void remote_async_inferior_event_handler (gdb_client_data);
226 static void remote_terminal_ours (struct target_ops *self);
228 static int remote_read_description_p (struct target_ops *target);
230 static void remote_console_output (char *msg);
232 static int remote_supports_cond_breakpoints (struct target_ops *self);
234 static int remote_can_run_breakpoint_commands (struct target_ops *self);
236 static void remote_btrace_reset (void);
238 static int stop_reply_queue_length (void);
240 static void readahead_cache_invalidate (void);
244 static struct cmd_list_element *remote_cmdlist;
246 /* For "set remote" and "show remote". */
248 static struct cmd_list_element *remote_set_cmdlist;
249 static struct cmd_list_element *remote_show_cmdlist;
251 /* Stub vCont actions support.
253 Each field is a boolean flag indicating whether the stub reports
254 support for the corresponding action. */
256 struct vCont_action_support
271 /* Controls whether GDB is willing to use range stepping. */
273 static int use_range_stepping = 1;
275 #define OPAQUETHREADBYTES 8
277 /* a 64 bit opaque identifier */
278 typedef unsigned char threadref[OPAQUETHREADBYTES];
280 /* About this many threadisds fit in a packet. */
282 #define MAXTHREADLISTRESULTS 32
284 /* Data for the vFile:pread readahead cache. */
286 struct readahead_cache
288 /* The file descriptor for the file that is being cached. -1 if the
292 /* The offset into the file that the cache buffer corresponds
296 /* The buffer holding the cache contents. */
298 /* The buffer's size. We try to read as much as fits into a packet
302 /* Cache hit and miss counters. */
307 /* Description of the remote protocol state for the currently
308 connected target. This is per-target state, and independent of the
309 selected architecture. */
313 /* A buffer to use for incoming packets, and its current size. The
314 buffer is grown dynamically for larger incoming packets.
315 Outgoing packets may also be constructed in this buffer.
316 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
317 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
322 /* True if we're going through initial connection setup (finding out
323 about the remote side's threads, relocating symbols, etc.). */
326 /* If we negotiated packet size explicitly (and thus can bypass
327 heuristics for the largest packet size that will not overflow
328 a buffer in the stub), this will be set to that packet size.
329 Otherwise zero, meaning to use the guessed size. */
330 long explicit_packet_size;
332 /* remote_wait is normally called when the target is running and
333 waits for a stop reply packet. But sometimes we need to call it
334 when the target is already stopped. We can send a "?" packet
335 and have remote_wait read the response. Or, if we already have
336 the response, we can stash it in BUF and tell remote_wait to
337 skip calling getpkt. This flag is set when BUF contains a
338 stop reply packet and the target is not waiting. */
339 int cached_wait_status;
341 /* True, if in no ack mode. That is, neither GDB nor the stub will
342 expect acks from each other. The connection is assumed to be
346 /* True if we're connected in extended remote mode. */
349 /* True if we resumed the target and we're waiting for the target to
350 stop. In the mean time, we can't start another command/query.
351 The remote server wouldn't be ready to process it, so we'd
352 timeout waiting for a reply that would never come and eventually
353 we'd close the connection. This can happen in asynchronous mode
354 because we allow GDB commands while the target is running. */
355 int waiting_for_stop_reply;
357 /* The status of the stub support for the various vCont actions. */
358 struct vCont_action_support supports_vCont;
360 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
361 responded to that. */
364 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
365 remote_open knows that we don't have a file open when the program
367 struct serial *remote_desc;
369 /* These are the threads which we last sent to the remote system. The
370 TID member will be -1 for all or -2 for not sent yet. */
371 ptid_t general_thread;
372 ptid_t continue_thread;
374 /* This is the traceframe which we last selected on the remote system.
375 It will be -1 if no traceframe is selected. */
376 int remote_traceframe_number;
378 char *last_pass_packet;
380 /* The last QProgramSignals packet sent to the target. We bypass
381 sending a new program signals list down to the target if the new
382 packet is exactly the same as the last we sent. IOW, we only let
383 the target know about program signals list changes. */
384 char *last_program_signals_packet;
386 enum gdb_signal last_sent_signal;
390 char *finished_object;
391 char *finished_annex;
392 ULONGEST finished_offset;
394 /* Should we try the 'ThreadInfo' query packet?
396 This variable (NOT available to the user: auto-detect only!)
397 determines whether GDB will use the new, simpler "ThreadInfo"
398 query or the older, more complex syntax for thread queries.
399 This is an auto-detect variable (set to true at each connect,
400 and set to false when the target fails to recognize it). */
401 int use_threadinfo_query;
402 int use_threadextra_query;
404 threadref echo_nextthread;
405 threadref nextthread;
406 threadref resultthreadlist[MAXTHREADLISTRESULTS];
408 /* The state of remote notification. */
409 struct remote_notif_state *notif_state;
411 /* The branch trace configuration. */
412 struct btrace_config btrace_config;
414 /* The argument to the last "vFile:setfs:" packet we sent, used
415 to avoid sending repeated unnecessary "vFile:setfs:" packets.
416 Initialized to -1 to indicate that no "vFile:setfs:" packet
417 has yet been sent. */
420 /* A readahead cache for vFile:pread. Often, reading a binary
421 involves a sequence of small reads. E.g., when parsing an ELF
422 file. A readahead cache helps mostly the case of remote
423 debugging on a connection with higher latency, due to the
424 request/reply nature of the RSP. We only cache data for a single
425 file descriptor at a time. */
426 struct readahead_cache readahead_cache;
429 /* Private data that we'll store in (struct thread_info)->private. */
430 struct private_thread_info
436 /* Whether the target stopped for a breakpoint/watchpoint. */
437 enum target_stop_reason stop_reason;
439 /* This is set to the data address of the access causing the target
440 to stop for a watchpoint. */
441 CORE_ADDR watch_data_address;
445 free_private_thread_info (struct private_thread_info *info)
452 /* This data could be associated with a target, but we do not always
453 have access to the current target when we need it, so for now it is
454 static. This will be fine for as long as only one target is in use
456 static struct remote_state *remote_state;
458 static struct remote_state *
459 get_remote_state_raw (void)
464 /* Allocate a new struct remote_state with xmalloc, initialize it, and
467 static struct remote_state *
468 new_remote_state (void)
470 struct remote_state *result = XCNEW (struct remote_state);
472 /* The default buffer size is unimportant; it will be expanded
473 whenever a larger buffer is needed. */
474 result->buf_size = 400;
475 result->buf = (char *) xmalloc (result->buf_size);
476 result->remote_traceframe_number = -1;
477 result->last_sent_signal = GDB_SIGNAL_0;
483 /* Description of the remote protocol for a given architecture. */
487 long offset; /* Offset into G packet. */
488 long regnum; /* GDB's internal register number. */
489 LONGEST pnum; /* Remote protocol register number. */
490 int in_g_packet; /* Always part of G packet. */
491 /* long size in bytes; == register_size (target_gdbarch (), regnum);
493 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
497 struct remote_arch_state
499 /* Description of the remote protocol registers. */
500 long sizeof_g_packet;
502 /* Description of the remote protocol registers indexed by REGNUM
503 (making an array gdbarch_num_regs in size). */
504 struct packet_reg *regs;
506 /* This is the size (in chars) of the first response to the ``g''
507 packet. It is used as a heuristic when determining the maximum
508 size of memory-read and memory-write packets. A target will
509 typically only reserve a buffer large enough to hold the ``g''
510 packet. The size does not include packet overhead (headers and
512 long actual_register_packet_size;
514 /* This is the maximum size (in chars) of a non read/write packet.
515 It is also used as a cap on the size of read/write packets. */
516 long remote_packet_size;
519 /* Utility: generate error from an incoming stub packet. */
521 trace_error (char *buf)
524 return; /* not an error msg */
527 case '1': /* malformed packet error */
528 if (*++buf == '0') /* general case: */
529 error (_("remote.c: error in outgoing packet."));
531 error (_("remote.c: error in outgoing packet at field #%ld."),
532 strtol (buf, NULL, 16));
534 error (_("Target returns error code '%s'."), buf);
538 /* Utility: wait for reply from stub, while accepting "O" packets. */
540 remote_get_noisy_reply (char **buf_p,
543 do /* Loop on reply from remote stub. */
547 QUIT; /* Allow user to bail out with ^C. */
548 getpkt (buf_p, sizeof_buf, 0);
552 else if (startswith (buf, "qRelocInsn:"))
555 CORE_ADDR from, to, org_to;
557 int adjusted_size = 0;
560 p = buf + strlen ("qRelocInsn:");
561 pp = unpack_varlen_hex (p, &ul);
563 error (_("invalid qRelocInsn packet: %s"), buf);
567 unpack_varlen_hex (p, &ul);
574 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
577 CATCH (ex, RETURN_MASK_ALL)
579 if (ex.error == MEMORY_ERROR)
581 /* Propagate memory errors silently back to the
582 target. The stub may have limited the range of
583 addresses we can write to, for example. */
587 /* Something unexpectedly bad happened. Be verbose
588 so we can tell what, and propagate the error back
589 to the stub, so it doesn't get stuck waiting for
591 exception_fprintf (gdb_stderr, ex,
592 _("warning: relocating instruction: "));
600 adjusted_size = to - org_to;
602 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
606 else if (buf[0] == 'O' && buf[1] != 'K')
607 remote_console_output (buf + 1); /* 'O' message from stub */
609 return buf; /* Here's the actual reply. */
614 /* Handle for retreving the remote protocol data from gdbarch. */
615 static struct gdbarch_data *remote_gdbarch_data_handle;
617 static struct remote_arch_state *
618 get_remote_arch_state (void)
620 gdb_assert (target_gdbarch () != NULL);
621 return ((struct remote_arch_state *)
622 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
625 /* Fetch the global remote target state. */
627 static struct remote_state *
628 get_remote_state (void)
630 /* Make sure that the remote architecture state has been
631 initialized, because doing so might reallocate rs->buf. Any
632 function which calls getpkt also needs to be mindful of changes
633 to rs->buf, but this call limits the number of places which run
635 get_remote_arch_state ();
637 return get_remote_state_raw ();
640 /* Cleanup routine for the remote module's pspace data. */
643 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
645 char *remote_exec_file = (char *) arg;
647 xfree (remote_exec_file);
650 /* Fetch the remote exec-file from the current program space. */
653 get_remote_exec_file (void)
655 char *remote_exec_file;
658 = (char *) program_space_data (current_program_space,
660 if (remote_exec_file == NULL)
663 return remote_exec_file;
666 /* Set the remote exec file for PSPACE. */
669 set_pspace_remote_exec_file (struct program_space *pspace,
670 char *remote_exec_file)
672 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
675 set_program_space_data (pspace, remote_pspace_data,
676 xstrdup (remote_exec_file));
679 /* The "set/show remote exec-file" set command hook. */
682 set_remote_exec_file (char *ignored, int from_tty,
683 struct cmd_list_element *c)
685 gdb_assert (remote_exec_file_var != NULL);
686 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
689 /* The "set/show remote exec-file" show command hook. */
692 show_remote_exec_file (struct ui_file *file, int from_tty,
693 struct cmd_list_element *cmd, const char *value)
695 fprintf_filtered (file, "%s\n", remote_exec_file_var);
699 compare_pnums (const void *lhs_, const void *rhs_)
701 const struct packet_reg * const *lhs
702 = (const struct packet_reg * const *) lhs_;
703 const struct packet_reg * const *rhs
704 = (const struct packet_reg * const *) rhs_;
706 if ((*lhs)->pnum < (*rhs)->pnum)
708 else if ((*lhs)->pnum == (*rhs)->pnum)
715 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
717 int regnum, num_remote_regs, offset;
718 struct packet_reg **remote_regs;
720 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
722 struct packet_reg *r = ®s[regnum];
724 if (register_size (gdbarch, regnum) == 0)
725 /* Do not try to fetch zero-sized (placeholder) registers. */
728 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
733 /* Define the g/G packet format as the contents of each register
734 with a remote protocol number, in order of ascending protocol
737 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
738 for (num_remote_regs = 0, regnum = 0;
739 regnum < gdbarch_num_regs (gdbarch);
741 if (regs[regnum].pnum != -1)
742 remote_regs[num_remote_regs++] = ®s[regnum];
744 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
747 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
749 remote_regs[regnum]->in_g_packet = 1;
750 remote_regs[regnum]->offset = offset;
751 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
757 /* Given the architecture described by GDBARCH, return the remote
758 protocol register's number and the register's offset in the g/G
759 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
760 If the target does not have a mapping for REGNUM, return false,
761 otherwise, return true. */
764 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
765 int *pnum, int *poffset)
768 struct packet_reg *regs;
769 struct cleanup *old_chain;
771 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
773 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
774 old_chain = make_cleanup (xfree, regs);
776 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
778 *pnum = regs[regnum].pnum;
779 *poffset = regs[regnum].offset;
781 do_cleanups (old_chain);
787 init_remote_state (struct gdbarch *gdbarch)
789 struct remote_state *rs = get_remote_state_raw ();
790 struct remote_arch_state *rsa;
792 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
794 /* Use the architecture to build a regnum<->pnum table, which will be
795 1:1 unless a feature set specifies otherwise. */
796 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
797 gdbarch_num_regs (gdbarch),
800 /* Record the maximum possible size of the g packet - it may turn out
802 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
804 /* Default maximum number of characters in a packet body. Many
805 remote stubs have a hardwired buffer size of 400 bytes
806 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
807 as the maximum packet-size to ensure that the packet and an extra
808 NUL character can always fit in the buffer. This stops GDB
809 trashing stubs that try to squeeze an extra NUL into what is
810 already a full buffer (As of 1999-12-04 that was most stubs). */
811 rsa->remote_packet_size = 400 - 1;
813 /* This one is filled in when a ``g'' packet is received. */
814 rsa->actual_register_packet_size = 0;
816 /* Should rsa->sizeof_g_packet needs more space than the
817 default, adjust the size accordingly. Remember that each byte is
818 encoded as two characters. 32 is the overhead for the packet
819 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
820 (``$NN:G...#NN'') is a better guess, the below has been padded a
822 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
823 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
825 /* Make sure that the packet buffer is plenty big enough for
826 this architecture. */
827 if (rs->buf_size < rsa->remote_packet_size)
829 rs->buf_size = 2 * rsa->remote_packet_size;
830 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
836 /* Return the current allowed size of a remote packet. This is
837 inferred from the current architecture, and should be used to
838 limit the length of outgoing packets. */
840 get_remote_packet_size (void)
842 struct remote_state *rs = get_remote_state ();
843 struct remote_arch_state *rsa = get_remote_arch_state ();
845 if (rs->explicit_packet_size)
846 return rs->explicit_packet_size;
848 return rsa->remote_packet_size;
851 static struct packet_reg *
852 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
854 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
858 struct packet_reg *r = &rsa->regs[regnum];
860 gdb_assert (r->regnum == regnum);
865 static struct packet_reg *
866 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
870 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
872 struct packet_reg *r = &rsa->regs[i];
880 static struct target_ops remote_ops;
882 static struct target_ops extended_remote_ops;
884 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
885 ``forever'' still use the normal timeout mechanism. This is
886 currently used by the ASYNC code to guarentee that target reads
887 during the initial connect always time-out. Once getpkt has been
888 modified to return a timeout indication and, in turn
889 remote_wait()/wait_for_inferior() have gained a timeout parameter
891 static int wait_forever_enabled_p = 1;
893 /* Allow the user to specify what sequence to send to the remote
894 when he requests a program interruption: Although ^C is usually
895 what remote systems expect (this is the default, here), it is
896 sometimes preferable to send a break. On other systems such
897 as the Linux kernel, a break followed by g, which is Magic SysRq g
898 is required in order to interrupt the execution. */
899 const char interrupt_sequence_control_c[] = "Ctrl-C";
900 const char interrupt_sequence_break[] = "BREAK";
901 const char interrupt_sequence_break_g[] = "BREAK-g";
902 static const char *const interrupt_sequence_modes[] =
904 interrupt_sequence_control_c,
905 interrupt_sequence_break,
906 interrupt_sequence_break_g,
909 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
912 show_interrupt_sequence (struct ui_file *file, int from_tty,
913 struct cmd_list_element *c,
916 if (interrupt_sequence_mode == interrupt_sequence_control_c)
917 fprintf_filtered (file,
918 _("Send the ASCII ETX character (Ctrl-c) "
919 "to the remote target to interrupt the "
920 "execution of the program.\n"));
921 else if (interrupt_sequence_mode == interrupt_sequence_break)
922 fprintf_filtered (file,
923 _("send a break signal to the remote target "
924 "to interrupt the execution of the program.\n"));
925 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
926 fprintf_filtered (file,
927 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
928 "the remote target to interrupt the execution "
929 "of Linux kernel.\n"));
931 internal_error (__FILE__, __LINE__,
932 _("Invalid value for interrupt_sequence_mode: %s."),
933 interrupt_sequence_mode);
936 /* This boolean variable specifies whether interrupt_sequence is sent
937 to the remote target when gdb connects to it.
938 This is mostly needed when you debug the Linux kernel: The Linux kernel
939 expects BREAK g which is Magic SysRq g for connecting gdb. */
940 static int interrupt_on_connect = 0;
942 /* This variable is used to implement the "set/show remotebreak" commands.
943 Since these commands are now deprecated in favor of "set/show remote
944 interrupt-sequence", it no longer has any effect on the code. */
945 static int remote_break;
948 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
951 interrupt_sequence_mode = interrupt_sequence_break;
953 interrupt_sequence_mode = interrupt_sequence_control_c;
957 show_remotebreak (struct ui_file *file, int from_tty,
958 struct cmd_list_element *c,
963 /* This variable sets the number of bits in an address that are to be
964 sent in a memory ("M" or "m") packet. Normally, after stripping
965 leading zeros, the entire address would be sent. This variable
966 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
967 initial implementation of remote.c restricted the address sent in
968 memory packets to ``host::sizeof long'' bytes - (typically 32
969 bits). Consequently, for 64 bit targets, the upper 32 bits of an
970 address was never sent. Since fixing this bug may cause a break in
971 some remote targets this variable is principly provided to
972 facilitate backward compatibility. */
974 static unsigned int remote_address_size;
976 /* Temporary to track who currently owns the terminal. See
977 remote_terminal_* for more details. */
979 static int remote_async_terminal_ours_p;
982 /* User configurable variables for the number of characters in a
983 memory read/write packet. MIN (rsa->remote_packet_size,
984 rsa->sizeof_g_packet) is the default. Some targets need smaller
985 values (fifo overruns, et.al.) and some users need larger values
986 (speed up transfers). The variables ``preferred_*'' (the user
987 request), ``current_*'' (what was actually set) and ``forced_*''
988 (Positive - a soft limit, negative - a hard limit). */
990 struct memory_packet_config
997 /* The default max memory-write-packet-size. The 16k is historical.
998 (It came from older GDB's using alloca for buffers and the
999 knowledge (folklore?) that some hosts don't cope very well with
1000 large alloca calls.) */
1001 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1003 /* The minimum remote packet size for memory transfers. Ensures we
1004 can write at least one byte. */
1005 #define MIN_MEMORY_PACKET_SIZE 20
1007 /* Compute the current size of a read/write packet. Since this makes
1008 use of ``actual_register_packet_size'' the computation is dynamic. */
1011 get_memory_packet_size (struct memory_packet_config *config)
1013 struct remote_state *rs = get_remote_state ();
1014 struct remote_arch_state *rsa = get_remote_arch_state ();
1017 if (config->fixed_p)
1019 if (config->size <= 0)
1020 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1022 what_they_get = config->size;
1026 what_they_get = get_remote_packet_size ();
1027 /* Limit the packet to the size specified by the user. */
1028 if (config->size > 0
1029 && what_they_get > config->size)
1030 what_they_get = config->size;
1032 /* Limit it to the size of the targets ``g'' response unless we have
1033 permission from the stub to use a larger packet size. */
1034 if (rs->explicit_packet_size == 0
1035 && rsa->actual_register_packet_size > 0
1036 && what_they_get > rsa->actual_register_packet_size)
1037 what_they_get = rsa->actual_register_packet_size;
1039 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1040 what_they_get = MIN_MEMORY_PACKET_SIZE;
1042 /* Make sure there is room in the global buffer for this packet
1043 (including its trailing NUL byte). */
1044 if (rs->buf_size < what_they_get + 1)
1046 rs->buf_size = 2 * what_they_get;
1047 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1050 return what_they_get;
1053 /* Update the size of a read/write packet. If they user wants
1054 something really big then do a sanity check. */
1057 set_memory_packet_size (char *args, struct memory_packet_config *config)
1059 int fixed_p = config->fixed_p;
1060 long size = config->size;
1063 error (_("Argument required (integer, `fixed' or `limited')."));
1064 else if (strcmp (args, "hard") == 0
1065 || strcmp (args, "fixed") == 0)
1067 else if (strcmp (args, "soft") == 0
1068 || strcmp (args, "limit") == 0)
1074 size = strtoul (args, &end, 0);
1076 error (_("Invalid %s (bad syntax)."), config->name);
1078 /* Instead of explicitly capping the size of a packet to or
1079 disallowing it, the user is allowed to set the size to
1080 something arbitrarily large. */
1083 /* So that the query shows the correct value. */
1085 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1088 if (fixed_p && !config->fixed_p)
1090 if (! query (_("The target may not be able to correctly handle a %s\n"
1091 "of %ld bytes. Change the packet size? "),
1092 config->name, size))
1093 error (_("Packet size not changed."));
1095 /* Update the config. */
1096 config->fixed_p = fixed_p;
1097 config->size = size;
1101 show_memory_packet_size (struct memory_packet_config *config)
1103 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1104 if (config->fixed_p)
1105 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1106 get_memory_packet_size (config));
1108 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1109 get_memory_packet_size (config));
1112 static struct memory_packet_config memory_write_packet_config =
1114 "memory-write-packet-size",
1118 set_memory_write_packet_size (char *args, int from_tty)
1120 set_memory_packet_size (args, &memory_write_packet_config);
1124 show_memory_write_packet_size (char *args, int from_tty)
1126 show_memory_packet_size (&memory_write_packet_config);
1130 get_memory_write_packet_size (void)
1132 return get_memory_packet_size (&memory_write_packet_config);
1135 static struct memory_packet_config memory_read_packet_config =
1137 "memory-read-packet-size",
1141 set_memory_read_packet_size (char *args, int from_tty)
1143 set_memory_packet_size (args, &memory_read_packet_config);
1147 show_memory_read_packet_size (char *args, int from_tty)
1149 show_memory_packet_size (&memory_read_packet_config);
1153 get_memory_read_packet_size (void)
1155 long size = get_memory_packet_size (&memory_read_packet_config);
1157 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1158 extra buffer size argument before the memory read size can be
1159 increased beyond this. */
1160 if (size > get_remote_packet_size ())
1161 size = get_remote_packet_size ();
1166 /* Generic configuration support for packets the stub optionally
1167 supports. Allows the user to specify the use of the packet as well
1168 as allowing GDB to auto-detect support in the remote stub. */
1172 PACKET_SUPPORT_UNKNOWN = 0,
1177 struct packet_config
1182 /* If auto, GDB auto-detects support for this packet or feature,
1183 either through qSupported, or by trying the packet and looking
1184 at the response. If true, GDB assumes the target supports this
1185 packet. If false, the packet is disabled. Configs that don't
1186 have an associated command always have this set to auto. */
1187 enum auto_boolean detect;
1189 /* Does the target support this packet? */
1190 enum packet_support support;
1193 /* Analyze a packet's return value and update the packet config
1203 static enum packet_support packet_config_support (struct packet_config *config);
1204 static enum packet_support packet_support (int packet);
1207 show_packet_config_cmd (struct packet_config *config)
1209 char *support = "internal-error";
1211 switch (packet_config_support (config))
1214 support = "enabled";
1216 case PACKET_DISABLE:
1217 support = "disabled";
1219 case PACKET_SUPPORT_UNKNOWN:
1220 support = "unknown";
1223 switch (config->detect)
1225 case AUTO_BOOLEAN_AUTO:
1226 printf_filtered (_("Support for the `%s' packet "
1227 "is auto-detected, currently %s.\n"),
1228 config->name, support);
1230 case AUTO_BOOLEAN_TRUE:
1231 case AUTO_BOOLEAN_FALSE:
1232 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1233 config->name, support);
1239 add_packet_config_cmd (struct packet_config *config, const char *name,
1240 const char *title, int legacy)
1246 config->name = name;
1247 config->title = title;
1248 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1250 show_doc = xstrprintf ("Show current use of remote "
1251 "protocol `%s' (%s) packet",
1253 /* set/show TITLE-packet {auto,on,off} */
1254 cmd_name = xstrprintf ("%s-packet", title);
1255 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1256 &config->detect, set_doc,
1257 show_doc, NULL, /* help_doc */
1259 show_remote_protocol_packet_cmd,
1260 &remote_set_cmdlist, &remote_show_cmdlist);
1261 /* The command code copies the documentation strings. */
1264 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1269 legacy_name = xstrprintf ("%s-packet", name);
1270 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1271 &remote_set_cmdlist);
1272 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1273 &remote_show_cmdlist);
1277 static enum packet_result
1278 packet_check_result (const char *buf)
1282 /* The stub recognized the packet request. Check that the
1283 operation succeeded. */
1285 && isxdigit (buf[1]) && isxdigit (buf[2])
1287 /* "Enn" - definitly an error. */
1288 return PACKET_ERROR;
1290 /* Always treat "E." as an error. This will be used for
1291 more verbose error messages, such as E.memtypes. */
1292 if (buf[0] == 'E' && buf[1] == '.')
1293 return PACKET_ERROR;
1295 /* The packet may or may not be OK. Just assume it is. */
1299 /* The stub does not support the packet. */
1300 return PACKET_UNKNOWN;
1303 static enum packet_result
1304 packet_ok (const char *buf, struct packet_config *config)
1306 enum packet_result result;
1308 if (config->detect != AUTO_BOOLEAN_TRUE
1309 && config->support == PACKET_DISABLE)
1310 internal_error (__FILE__, __LINE__,
1311 _("packet_ok: attempt to use a disabled packet"));
1313 result = packet_check_result (buf);
1318 /* The stub recognized the packet request. */
1319 if (config->support == PACKET_SUPPORT_UNKNOWN)
1322 fprintf_unfiltered (gdb_stdlog,
1323 "Packet %s (%s) is supported\n",
1324 config->name, config->title);
1325 config->support = PACKET_ENABLE;
1328 case PACKET_UNKNOWN:
1329 /* The stub does not support the packet. */
1330 if (config->detect == AUTO_BOOLEAN_AUTO
1331 && config->support == PACKET_ENABLE)
1333 /* If the stub previously indicated that the packet was
1334 supported then there is a protocol error. */
1335 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1336 config->name, config->title);
1338 else if (config->detect == AUTO_BOOLEAN_TRUE)
1340 /* The user set it wrong. */
1341 error (_("Enabled packet %s (%s) not recognized by stub"),
1342 config->name, config->title);
1346 fprintf_unfiltered (gdb_stdlog,
1347 "Packet %s (%s) is NOT supported\n",
1348 config->name, config->title);
1349 config->support = PACKET_DISABLE;
1370 PACKET_vFile_pwrite,
1372 PACKET_vFile_unlink,
1373 PACKET_vFile_readlink,
1376 PACKET_qXfer_features,
1377 PACKET_qXfer_exec_file,
1378 PACKET_qXfer_libraries,
1379 PACKET_qXfer_libraries_svr4,
1380 PACKET_qXfer_memory_map,
1381 PACKET_qXfer_spu_read,
1382 PACKET_qXfer_spu_write,
1383 PACKET_qXfer_osdata,
1384 PACKET_qXfer_threads,
1385 PACKET_qXfer_statictrace_read,
1386 PACKET_qXfer_traceframe_info,
1392 PACKET_QPassSignals,
1393 PACKET_QProgramSignals,
1395 PACKET_qSearch_memory,
1398 PACKET_QStartNoAckMode,
1400 PACKET_qXfer_siginfo_read,
1401 PACKET_qXfer_siginfo_write,
1404 /* Support for conditional tracepoints. */
1405 PACKET_ConditionalTracepoints,
1407 /* Support for target-side breakpoint conditions. */
1408 PACKET_ConditionalBreakpoints,
1410 /* Support for target-side breakpoint commands. */
1411 PACKET_BreakpointCommands,
1413 /* Support for fast tracepoints. */
1414 PACKET_FastTracepoints,
1416 /* Support for static tracepoints. */
1417 PACKET_StaticTracepoints,
1419 /* Support for installing tracepoints while a trace experiment is
1421 PACKET_InstallInTrace,
1425 PACKET_TracepointSource,
1428 PACKET_QDisableRandomization,
1430 PACKET_QTBuffer_size,
1434 PACKET_qXfer_btrace,
1436 /* Support for the QNonStop packet. */
1439 /* Support for multi-process extensions. */
1440 PACKET_multiprocess_feature,
1442 /* Support for enabling and disabling tracepoints while a trace
1443 experiment is running. */
1444 PACKET_EnableDisableTracepoints_feature,
1446 /* Support for collecting strings using the tracenz bytecode. */
1447 PACKET_tracenz_feature,
1449 /* Support for continuing to run a trace experiment while GDB is
1451 PACKET_DisconnectedTracing_feature,
1453 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1454 PACKET_augmented_libraries_svr4_read_feature,
1456 /* Support for the qXfer:btrace-conf:read packet. */
1457 PACKET_qXfer_btrace_conf,
1459 /* Support for the Qbtrace-conf:bts:size packet. */
1460 PACKET_Qbtrace_conf_bts_size,
1462 /* Support for swbreak+ feature. */
1463 PACKET_swbreak_feature,
1465 /* Support for hwbreak+ feature. */
1466 PACKET_hwbreak_feature,
1468 /* Support for fork events. */
1469 PACKET_fork_event_feature,
1471 /* Support for vfork events. */
1472 PACKET_vfork_event_feature,
1474 /* Support for the Qbtrace-conf:pt:size packet. */
1475 PACKET_Qbtrace_conf_pt_size,
1477 /* Support for exec events. */
1478 PACKET_exec_event_feature,
1480 /* Support for query supported vCont actions. */
1481 PACKET_vContSupported,
1483 /* Support remote CTRL-C. */
1489 static struct packet_config remote_protocol_packets[PACKET_MAX];
1491 /* Returns the packet's corresponding "set remote foo-packet" command
1492 state. See struct packet_config for more details. */
1494 static enum auto_boolean
1495 packet_set_cmd_state (int packet)
1497 return remote_protocol_packets[packet].detect;
1500 /* Returns whether a given packet or feature is supported. This takes
1501 into account the state of the corresponding "set remote foo-packet"
1502 command, which may be used to bypass auto-detection. */
1504 static enum packet_support
1505 packet_config_support (struct packet_config *config)
1507 switch (config->detect)
1509 case AUTO_BOOLEAN_TRUE:
1510 return PACKET_ENABLE;
1511 case AUTO_BOOLEAN_FALSE:
1512 return PACKET_DISABLE;
1513 case AUTO_BOOLEAN_AUTO:
1514 return config->support;
1516 gdb_assert_not_reached (_("bad switch"));
1520 /* Same as packet_config_support, but takes the packet's enum value as
1523 static enum packet_support
1524 packet_support (int packet)
1526 struct packet_config *config = &remote_protocol_packets[packet];
1528 return packet_config_support (config);
1532 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1533 struct cmd_list_element *c,
1536 struct packet_config *packet;
1538 for (packet = remote_protocol_packets;
1539 packet < &remote_protocol_packets[PACKET_MAX];
1542 if (&packet->detect == c->var)
1544 show_packet_config_cmd (packet);
1548 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1552 /* Should we try one of the 'Z' requests? */
1556 Z_PACKET_SOFTWARE_BP,
1557 Z_PACKET_HARDWARE_BP,
1564 /* For compatibility with older distributions. Provide a ``set remote
1565 Z-packet ...'' command that updates all the Z packet types. */
1567 static enum auto_boolean remote_Z_packet_detect;
1570 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1571 struct cmd_list_element *c)
1575 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1576 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1580 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1581 struct cmd_list_element *c,
1586 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1588 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1592 /* Returns true if the multi-process extensions are in effect. */
1595 remote_multi_process_p (struct remote_state *rs)
1597 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1600 /* Returns true if fork events are supported. */
1603 remote_fork_event_p (struct remote_state *rs)
1605 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1608 /* Returns true if vfork events are supported. */
1611 remote_vfork_event_p (struct remote_state *rs)
1613 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1616 /* Returns true if exec events are supported. */
1619 remote_exec_event_p (struct remote_state *rs)
1621 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1624 /* Insert fork catchpoint target routine. If fork events are enabled
1625 then return success, nothing more to do. */
1628 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1630 struct remote_state *rs = get_remote_state ();
1632 return !remote_fork_event_p (rs);
1635 /* Remove fork catchpoint target routine. Nothing to do, just
1639 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1644 /* Insert vfork catchpoint target routine. If vfork events are enabled
1645 then return success, nothing more to do. */
1648 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1650 struct remote_state *rs = get_remote_state ();
1652 return !remote_vfork_event_p (rs);
1655 /* Remove vfork catchpoint target routine. Nothing to do, just
1659 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1664 /* Insert exec catchpoint target routine. If exec events are
1665 enabled, just return success. */
1668 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1670 struct remote_state *rs = get_remote_state ();
1672 return !remote_exec_event_p (rs);
1675 /* Remove exec catchpoint target routine. Nothing to do, just
1679 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1684 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1685 static struct async_signal_handler *async_sigint_remote_twice_token;
1686 static struct async_signal_handler *async_sigint_remote_token;
1689 /* Asynchronous signal handle registered as event loop source for
1690 when we have pending events ready to be passed to the core. */
1692 static struct async_event_handler *remote_async_inferior_event_token;
1696 static ptid_t magic_null_ptid;
1697 static ptid_t not_sent_ptid;
1698 static ptid_t any_thread_ptid;
1700 /* Find out if the stub attached to PID (and hence GDB should offer to
1701 detach instead of killing it when bailing out). */
1704 remote_query_attached (int pid)
1706 struct remote_state *rs = get_remote_state ();
1707 size_t size = get_remote_packet_size ();
1709 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1712 if (remote_multi_process_p (rs))
1713 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1715 xsnprintf (rs->buf, size, "qAttached");
1718 getpkt (&rs->buf, &rs->buf_size, 0);
1720 switch (packet_ok (rs->buf,
1721 &remote_protocol_packets[PACKET_qAttached]))
1724 if (strcmp (rs->buf, "1") == 0)
1728 warning (_("Remote failure reply: %s"), rs->buf);
1730 case PACKET_UNKNOWN:
1737 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1738 has been invented by GDB, instead of reported by the target. Since
1739 we can be connected to a remote system before before knowing about
1740 any inferior, mark the target with execution when we find the first
1741 inferior. If ATTACHED is 1, then we had just attached to this
1742 inferior. If it is 0, then we just created this inferior. If it
1743 is -1, then try querying the remote stub to find out if it had
1744 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1745 attempt to open this inferior's executable as the main executable
1746 if no main executable is open already. */
1748 static struct inferior *
1749 remote_add_inferior (int fake_pid_p, int pid, int attached,
1752 struct inferior *inf;
1754 /* Check whether this process we're learning about is to be
1755 considered attached, or if is to be considered to have been
1756 spawned by the stub. */
1758 attached = remote_query_attached (pid);
1760 if (gdbarch_has_global_solist (target_gdbarch ()))
1762 /* If the target shares code across all inferiors, then every
1763 attach adds a new inferior. */
1764 inf = add_inferior (pid);
1766 /* ... and every inferior is bound to the same program space.
1767 However, each inferior may still have its own address
1769 inf->aspace = maybe_new_address_space ();
1770 inf->pspace = current_program_space;
1774 /* In the traditional debugging scenario, there's a 1-1 match
1775 between program/address spaces. We simply bind the inferior
1776 to the program space's address space. */
1777 inf = current_inferior ();
1778 inferior_appeared (inf, pid);
1781 inf->attach_flag = attached;
1782 inf->fake_pid_p = fake_pid_p;
1784 /* If no main executable is currently open then attempt to
1785 open the file that was executed to create this inferior. */
1786 if (try_open_exec && get_exec_file (0) == NULL)
1787 exec_file_locate_attach (pid, 1);
1792 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1793 according to RUNNING. */
1796 remote_add_thread (ptid_t ptid, int running)
1798 struct remote_state *rs = get_remote_state ();
1800 /* GDB historically didn't pull threads in the initial connection
1801 setup. If the remote target doesn't even have a concept of
1802 threads (e.g., a bare-metal target), even if internally we
1803 consider that a single-threaded target, mentioning a new thread
1804 might be confusing to the user. Be silent then, preserving the
1805 age old behavior. */
1806 if (rs->starting_up)
1807 add_thread_silent (ptid);
1811 set_executing (ptid, running);
1812 set_running (ptid, running);
1815 /* Come here when we learn about a thread id from the remote target.
1816 It may be the first time we hear about such thread, so take the
1817 opportunity to add it to GDB's thread list. In case this is the
1818 first time we're noticing its corresponding inferior, add it to
1819 GDB's inferior list as well. */
1822 remote_notice_new_inferior (ptid_t currthread, int running)
1824 /* If this is a new thread, add it to GDB's thread list.
1825 If we leave it up to WFI to do this, bad things will happen. */
1827 if (in_thread_list (currthread) && is_exited (currthread))
1829 /* We're seeing an event on a thread id we knew had exited.
1830 This has to be a new thread reusing the old id. Add it. */
1831 remote_add_thread (currthread, running);
1835 if (!in_thread_list (currthread))
1837 struct inferior *inf = NULL;
1838 int pid = ptid_get_pid (currthread);
1840 if (ptid_is_pid (inferior_ptid)
1841 && pid == ptid_get_pid (inferior_ptid))
1843 /* inferior_ptid has no thread member yet. This can happen
1844 with the vAttach -> remote_wait,"TAAthread:" path if the
1845 stub doesn't support qC. This is the first stop reported
1846 after an attach, so this is the main thread. Update the
1847 ptid in the thread list. */
1848 if (in_thread_list (pid_to_ptid (pid)))
1849 thread_change_ptid (inferior_ptid, currthread);
1852 remote_add_thread (currthread, running);
1853 inferior_ptid = currthread;
1858 if (ptid_equal (magic_null_ptid, inferior_ptid))
1860 /* inferior_ptid is not set yet. This can happen with the
1861 vRun -> remote_wait,"TAAthread:" path if the stub
1862 doesn't support qC. This is the first stop reported
1863 after an attach, so this is the main thread. Update the
1864 ptid in the thread list. */
1865 thread_change_ptid (inferior_ptid, currthread);
1869 /* When connecting to a target remote, or to a target
1870 extended-remote which already was debugging an inferior, we
1871 may not know about it yet. Add it before adding its child
1872 thread, so notifications are emitted in a sensible order. */
1873 if (!in_inferior_list (ptid_get_pid (currthread)))
1875 struct remote_state *rs = get_remote_state ();
1876 int fake_pid_p = !remote_multi_process_p (rs);
1878 inf = remote_add_inferior (fake_pid_p,
1879 ptid_get_pid (currthread), -1, 1);
1882 /* This is really a new thread. Add it. */
1883 remote_add_thread (currthread, running);
1885 /* If we found a new inferior, let the common code do whatever
1886 it needs to with it (e.g., read shared libraries, insert
1887 breakpoints), unless we're just setting up an all-stop
1891 struct remote_state *rs = get_remote_state ();
1893 if (!rs->starting_up)
1894 notice_new_inferior (currthread, running, 0);
1899 /* Return the private thread data, creating it if necessary. */
1901 static struct private_thread_info *
1902 demand_private_info (ptid_t ptid)
1904 struct thread_info *info = find_thread_ptid (ptid);
1910 info->priv = XNEW (struct private_thread_info);
1911 info->private_dtor = free_private_thread_info;
1912 info->priv->core = -1;
1913 info->priv->extra = 0;
1919 /* Call this function as a result of
1920 1) A halt indication (T packet) containing a thread id
1921 2) A direct query of currthread
1922 3) Successful execution of set thread */
1925 record_currthread (struct remote_state *rs, ptid_t currthread)
1927 rs->general_thread = currthread;
1930 /* If 'QPassSignals' is supported, tell the remote stub what signals
1931 it can simply pass through to the inferior without reporting. */
1934 remote_pass_signals (struct target_ops *self,
1935 int numsigs, unsigned char *pass_signals)
1937 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1939 char *pass_packet, *p;
1941 struct remote_state *rs = get_remote_state ();
1943 gdb_assert (numsigs < 256);
1944 for (i = 0; i < numsigs; i++)
1946 if (pass_signals[i])
1949 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1950 strcpy (pass_packet, "QPassSignals:");
1951 p = pass_packet + strlen (pass_packet);
1952 for (i = 0; i < numsigs; i++)
1954 if (pass_signals[i])
1957 *p++ = tohex (i >> 4);
1958 *p++ = tohex (i & 15);
1967 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1969 putpkt (pass_packet);
1970 getpkt (&rs->buf, &rs->buf_size, 0);
1971 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1972 if (rs->last_pass_packet)
1973 xfree (rs->last_pass_packet);
1974 rs->last_pass_packet = pass_packet;
1977 xfree (pass_packet);
1981 /* If 'QProgramSignals' is supported, tell the remote stub what
1982 signals it should pass through to the inferior when detaching. */
1985 remote_program_signals (struct target_ops *self,
1986 int numsigs, unsigned char *signals)
1988 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1992 struct remote_state *rs = get_remote_state ();
1994 gdb_assert (numsigs < 256);
1995 for (i = 0; i < numsigs; i++)
2000 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2001 strcpy (packet, "QProgramSignals:");
2002 p = packet + strlen (packet);
2003 for (i = 0; i < numsigs; i++)
2005 if (signal_pass_state (i))
2008 *p++ = tohex (i >> 4);
2009 *p++ = tohex (i & 15);
2018 if (!rs->last_program_signals_packet
2019 || strcmp (rs->last_program_signals_packet, packet) != 0)
2022 getpkt (&rs->buf, &rs->buf_size, 0);
2023 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2024 xfree (rs->last_program_signals_packet);
2025 rs->last_program_signals_packet = packet;
2032 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2033 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2034 thread. If GEN is set, set the general thread, if not, then set
2035 the step/continue thread. */
2037 set_thread (struct ptid ptid, int gen)
2039 struct remote_state *rs = get_remote_state ();
2040 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2041 char *buf = rs->buf;
2042 char *endbuf = rs->buf + get_remote_packet_size ();
2044 if (ptid_equal (state, ptid))
2048 *buf++ = gen ? 'g' : 'c';
2049 if (ptid_equal (ptid, magic_null_ptid))
2050 xsnprintf (buf, endbuf - buf, "0");
2051 else if (ptid_equal (ptid, any_thread_ptid))
2052 xsnprintf (buf, endbuf - buf, "0");
2053 else if (ptid_equal (ptid, minus_one_ptid))
2054 xsnprintf (buf, endbuf - buf, "-1");
2056 write_ptid (buf, endbuf, ptid);
2058 getpkt (&rs->buf, &rs->buf_size, 0);
2060 rs->general_thread = ptid;
2062 rs->continue_thread = ptid;
2066 set_general_thread (struct ptid ptid)
2068 set_thread (ptid, 1);
2072 set_continue_thread (struct ptid ptid)
2074 set_thread (ptid, 0);
2077 /* Change the remote current process. Which thread within the process
2078 ends up selected isn't important, as long as it is the same process
2079 as what INFERIOR_PTID points to.
2081 This comes from that fact that there is no explicit notion of
2082 "selected process" in the protocol. The selected process for
2083 general operations is the process the selected general thread
2087 set_general_process (void)
2089 struct remote_state *rs = get_remote_state ();
2091 /* If the remote can't handle multiple processes, don't bother. */
2092 if (!rs->extended || !remote_multi_process_p (rs))
2095 /* We only need to change the remote current thread if it's pointing
2096 at some other process. */
2097 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2098 set_general_thread (inferior_ptid);
2102 /* Return nonzero if this is the main thread that we made up ourselves
2103 to model non-threaded targets as single-threaded. */
2106 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2108 struct remote_state *rs = get_remote_state ();
2111 if (ptid_equal (ptid, magic_null_ptid))
2112 /* The main thread is always alive. */
2115 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2116 /* The main thread is always alive. This can happen after a
2117 vAttach, if the remote side doesn't support
2124 /* Return nonzero if the thread PTID is still alive on the remote
2128 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2130 struct remote_state *rs = get_remote_state ();
2133 /* Check if this is a thread that we made up ourselves to model
2134 non-threaded targets as single-threaded. */
2135 if (remote_thread_always_alive (ops, ptid))
2139 endp = rs->buf + get_remote_packet_size ();
2142 write_ptid (p, endp, ptid);
2145 getpkt (&rs->buf, &rs->buf_size, 0);
2146 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2149 /* Return a pointer to a thread name if we know it and NULL otherwise.
2150 The thread_info object owns the memory for the name. */
2153 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2155 if (info->priv != NULL)
2156 return info->priv->name;
2161 /* About these extended threadlist and threadinfo packets. They are
2162 variable length packets but, the fields within them are often fixed
2163 length. They are redundent enough to send over UDP as is the
2164 remote protocol in general. There is a matching unit test module
2167 /* WARNING: This threadref data structure comes from the remote O.S.,
2168 libstub protocol encoding, and remote.c. It is not particularly
2171 /* Right now, the internal structure is int. We want it to be bigger.
2172 Plan to fix this. */
2174 typedef int gdb_threadref; /* Internal GDB thread reference. */
2176 /* gdb_ext_thread_info is an internal GDB data structure which is
2177 equivalent to the reply of the remote threadinfo packet. */
2179 struct gdb_ext_thread_info
2181 threadref threadid; /* External form of thread reference. */
2182 int active; /* Has state interesting to GDB?
2184 char display[256]; /* Brief state display, name,
2185 blocked/suspended. */
2186 char shortname[32]; /* To be used to name threads. */
2187 char more_display[256]; /* Long info, statistics, queue depth,
2191 /* The volume of remote transfers can be limited by submitting
2192 a mask containing bits specifying the desired information.
2193 Use a union of these values as the 'selection' parameter to
2194 get_thread_info. FIXME: Make these TAG names more thread specific. */
2196 #define TAG_THREADID 1
2197 #define TAG_EXISTS 2
2198 #define TAG_DISPLAY 4
2199 #define TAG_THREADNAME 8
2200 #define TAG_MOREDISPLAY 16
2202 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2204 static char *unpack_nibble (char *buf, int *val);
2206 static char *unpack_byte (char *buf, int *value);
2208 static char *pack_int (char *buf, int value);
2210 static char *unpack_int (char *buf, int *value);
2212 static char *unpack_string (char *src, char *dest, int length);
2214 static char *pack_threadid (char *pkt, threadref *id);
2216 static char *unpack_threadid (char *inbuf, threadref *id);
2218 void int_to_threadref (threadref *id, int value);
2220 static int threadref_to_int (threadref *ref);
2222 static void copy_threadref (threadref *dest, threadref *src);
2224 static int threadmatch (threadref *dest, threadref *src);
2226 static char *pack_threadinfo_request (char *pkt, int mode,
2229 static int remote_unpack_thread_info_response (char *pkt,
2230 threadref *expectedref,
2231 struct gdb_ext_thread_info
2235 static int remote_get_threadinfo (threadref *threadid,
2236 int fieldset, /*TAG mask */
2237 struct gdb_ext_thread_info *info);
2239 static char *pack_threadlist_request (char *pkt, int startflag,
2241 threadref *nextthread);
2243 static int parse_threadlist_response (char *pkt,
2245 threadref *original_echo,
2246 threadref *resultlist,
2249 static int remote_get_threadlist (int startflag,
2250 threadref *nextthread,
2254 threadref *threadlist);
2256 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2258 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2259 void *context, int looplimit);
2261 static int remote_newthread_step (threadref *ref, void *context);
2264 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2265 buffer we're allowed to write to. Returns
2266 BUF+CHARACTERS_WRITTEN. */
2269 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2272 struct remote_state *rs = get_remote_state ();
2274 if (remote_multi_process_p (rs))
2276 pid = ptid_get_pid (ptid);
2278 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2280 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2282 tid = ptid_get_lwp (ptid);
2284 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2286 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2291 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2292 passed the last parsed char. Returns null_ptid on error. */
2295 read_ptid (char *buf, char **obuf)
2299 ULONGEST pid = 0, tid = 0;
2303 /* Multi-process ptid. */
2304 pp = unpack_varlen_hex (p + 1, &pid);
2306 error (_("invalid remote ptid: %s"), p);
2309 pp = unpack_varlen_hex (p + 1, &tid);
2312 return ptid_build (pid, tid, 0);
2315 /* No multi-process. Just a tid. */
2316 pp = unpack_varlen_hex (p, &tid);
2318 /* Return null_ptid when no thread id is found. */
2326 /* Since the stub is not sending a process id, then default to
2327 what's in inferior_ptid, unless it's null at this point. If so,
2328 then since there's no way to know the pid of the reported
2329 threads, use the magic number. */
2330 if (ptid_equal (inferior_ptid, null_ptid))
2331 pid = ptid_get_pid (magic_null_ptid);
2333 pid = ptid_get_pid (inferior_ptid);
2337 return ptid_build (pid, tid, 0);
2343 if (ch >= 'a' && ch <= 'f')
2344 return ch - 'a' + 10;
2345 if (ch >= '0' && ch <= '9')
2347 if (ch >= 'A' && ch <= 'F')
2348 return ch - 'A' + 10;
2353 stub_unpack_int (char *buff, int fieldlength)
2360 nibble = stubhex (*buff++);
2364 retval = retval << 4;
2370 unpack_nibble (char *buf, int *val)
2372 *val = fromhex (*buf++);
2377 unpack_byte (char *buf, int *value)
2379 *value = stub_unpack_int (buf, 2);
2384 pack_int (char *buf, int value)
2386 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2387 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2388 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2389 buf = pack_hex_byte (buf, (value & 0xff));
2394 unpack_int (char *buf, int *value)
2396 *value = stub_unpack_int (buf, 8);
2400 #if 0 /* Currently unused, uncomment when needed. */
2401 static char *pack_string (char *pkt, char *string);
2404 pack_string (char *pkt, char *string)
2409 len = strlen (string);
2411 len = 200; /* Bigger than most GDB packets, junk??? */
2412 pkt = pack_hex_byte (pkt, len);
2416 if ((ch == '\0') || (ch == '#'))
2417 ch = '*'; /* Protect encapsulation. */
2422 #endif /* 0 (unused) */
2425 unpack_string (char *src, char *dest, int length)
2434 pack_threadid (char *pkt, threadref *id)
2437 unsigned char *altid;
2439 altid = (unsigned char *) id;
2440 limit = pkt + BUF_THREAD_ID_SIZE;
2442 pkt = pack_hex_byte (pkt, *altid++);
2448 unpack_threadid (char *inbuf, threadref *id)
2451 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2454 altref = (char *) id;
2456 while (inbuf < limit)
2458 x = stubhex (*inbuf++);
2459 y = stubhex (*inbuf++);
2460 *altref++ = (x << 4) | y;
2465 /* Externally, threadrefs are 64 bits but internally, they are still
2466 ints. This is due to a mismatch of specifications. We would like
2467 to use 64bit thread references internally. This is an adapter
2471 int_to_threadref (threadref *id, int value)
2473 unsigned char *scan;
2475 scan = (unsigned char *) id;
2481 *scan++ = (value >> 24) & 0xff;
2482 *scan++ = (value >> 16) & 0xff;
2483 *scan++ = (value >> 8) & 0xff;
2484 *scan++ = (value & 0xff);
2488 threadref_to_int (threadref *ref)
2491 unsigned char *scan;
2497 value = (value << 8) | ((*scan++) & 0xff);
2502 copy_threadref (threadref *dest, threadref *src)
2505 unsigned char *csrc, *cdest;
2507 csrc = (unsigned char *) src;
2508 cdest = (unsigned char *) dest;
2515 threadmatch (threadref *dest, threadref *src)
2517 /* Things are broken right now, so just assume we got a match. */
2519 unsigned char *srcp, *destp;
2521 srcp = (char *) src;
2522 destp = (char *) dest;
2526 result &= (*srcp++ == *destp++) ? 1 : 0;
2533 threadid:1, # always request threadid
2540 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2543 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2545 *pkt++ = 'q'; /* Info Query */
2546 *pkt++ = 'P'; /* process or thread info */
2547 pkt = pack_int (pkt, mode); /* mode */
2548 pkt = pack_threadid (pkt, id); /* threadid */
2549 *pkt = '\0'; /* terminate */
2553 /* These values tag the fields in a thread info response packet. */
2554 /* Tagging the fields allows us to request specific fields and to
2555 add more fields as time goes by. */
2557 #define TAG_THREADID 1 /* Echo the thread identifier. */
2558 #define TAG_EXISTS 2 /* Is this process defined enough to
2559 fetch registers and its stack? */
2560 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2561 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2562 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2566 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2567 struct gdb_ext_thread_info *info)
2569 struct remote_state *rs = get_remote_state ();
2573 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2576 /* info->threadid = 0; FIXME: implement zero_threadref. */
2578 info->display[0] = '\0';
2579 info->shortname[0] = '\0';
2580 info->more_display[0] = '\0';
2582 /* Assume the characters indicating the packet type have been
2584 pkt = unpack_int (pkt, &mask); /* arg mask */
2585 pkt = unpack_threadid (pkt, &ref);
2588 warning (_("Incomplete response to threadinfo request."));
2589 if (!threadmatch (&ref, expectedref))
2590 { /* This is an answer to a different request. */
2591 warning (_("ERROR RMT Thread info mismatch."));
2594 copy_threadref (&info->threadid, &ref);
2596 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2598 /* Packets are terminated with nulls. */
2599 while ((pkt < limit) && mask && *pkt)
2601 pkt = unpack_int (pkt, &tag); /* tag */
2602 pkt = unpack_byte (pkt, &length); /* length */
2603 if (!(tag & mask)) /* Tags out of synch with mask. */
2605 warning (_("ERROR RMT: threadinfo tag mismatch."));
2609 if (tag == TAG_THREADID)
2613 warning (_("ERROR RMT: length of threadid is not 16."));
2617 pkt = unpack_threadid (pkt, &ref);
2618 mask = mask & ~TAG_THREADID;
2621 if (tag == TAG_EXISTS)
2623 info->active = stub_unpack_int (pkt, length);
2625 mask = mask & ~(TAG_EXISTS);
2628 warning (_("ERROR RMT: 'exists' length too long."));
2634 if (tag == TAG_THREADNAME)
2636 pkt = unpack_string (pkt, &info->shortname[0], length);
2637 mask = mask & ~TAG_THREADNAME;
2640 if (tag == TAG_DISPLAY)
2642 pkt = unpack_string (pkt, &info->display[0], length);
2643 mask = mask & ~TAG_DISPLAY;
2646 if (tag == TAG_MOREDISPLAY)
2648 pkt = unpack_string (pkt, &info->more_display[0], length);
2649 mask = mask & ~TAG_MOREDISPLAY;
2652 warning (_("ERROR RMT: unknown thread info tag."));
2653 break; /* Not a tag we know about. */
2659 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2660 struct gdb_ext_thread_info *info)
2662 struct remote_state *rs = get_remote_state ();
2665 pack_threadinfo_request (rs->buf, fieldset, threadid);
2667 getpkt (&rs->buf, &rs->buf_size, 0);
2669 if (rs->buf[0] == '\0')
2672 result = remote_unpack_thread_info_response (rs->buf + 2,
2677 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2680 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2681 threadref *nextthread)
2683 *pkt++ = 'q'; /* info query packet */
2684 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2685 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2686 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2687 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2692 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2695 parse_threadlist_response (char *pkt, int result_limit,
2696 threadref *original_echo, threadref *resultlist,
2699 struct remote_state *rs = get_remote_state ();
2701 int count, resultcount, done;
2704 /* Assume the 'q' and 'M chars have been stripped. */
2705 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2706 /* done parse past here */
2707 pkt = unpack_byte (pkt, &count); /* count field */
2708 pkt = unpack_nibble (pkt, &done);
2709 /* The first threadid is the argument threadid. */
2710 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2711 while ((count-- > 0) && (pkt < limit))
2713 pkt = unpack_threadid (pkt, resultlist++);
2714 if (resultcount++ >= result_limit)
2722 /* Fetch the next batch of threads from the remote. Returns -1 if the
2723 qL packet is not supported, 0 on error and 1 on success. */
2726 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2727 int *done, int *result_count, threadref *threadlist)
2729 struct remote_state *rs = get_remote_state ();
2732 /* Trancate result limit to be smaller than the packet size. */
2733 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2734 >= get_remote_packet_size ())
2735 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2737 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2739 getpkt (&rs->buf, &rs->buf_size, 0);
2740 if (*rs->buf == '\0')
2742 /* Packet not supported. */
2747 parse_threadlist_response (rs->buf + 2, result_limit,
2748 &rs->echo_nextthread, threadlist, done);
2750 if (!threadmatch (&rs->echo_nextthread, nextthread))
2752 /* FIXME: This is a good reason to drop the packet. */
2753 /* Possably, there is a duplicate response. */
2755 retransmit immediatly - race conditions
2756 retransmit after timeout - yes
2758 wait for packet, then exit
2760 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2761 return 0; /* I choose simply exiting. */
2763 if (*result_count <= 0)
2767 warning (_("RMT ERROR : failed to get remote thread list."));
2770 return result; /* break; */
2772 if (*result_count > result_limit)
2775 warning (_("RMT ERROR: threadlist response longer than requested."));
2781 /* Fetch the list of remote threads, with the qL packet, and call
2782 STEPFUNCTION for each thread found. Stops iterating and returns 1
2783 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2784 STEPFUNCTION returns false. If the packet is not supported,
2788 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2791 struct remote_state *rs = get_remote_state ();
2792 int done, i, result_count;
2800 if (loopcount++ > looplimit)
2803 warning (_("Remote fetch threadlist -infinite loop-."));
2806 result = remote_get_threadlist (startflag, &rs->nextthread,
2807 MAXTHREADLISTRESULTS,
2808 &done, &result_count,
2809 rs->resultthreadlist);
2812 /* Clear for later iterations. */
2814 /* Setup to resume next batch of thread references, set nextthread. */
2815 if (result_count >= 1)
2816 copy_threadref (&rs->nextthread,
2817 &rs->resultthreadlist[result_count - 1]);
2819 while (result_count--)
2821 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2831 /* A thread found on the remote target. */
2833 typedef struct thread_item
2835 /* The thread's PTID. */
2838 /* The thread's extra info. May be NULL. */
2841 /* The thread's name. May be NULL. */
2844 /* The core the thread was running on. -1 if not known. */
2847 DEF_VEC_O(thread_item_t);
2849 /* Context passed around to the various methods listing remote
2850 threads. As new threads are found, they're added to the ITEMS
2853 struct threads_listing_context
2855 /* The threads found on the remote target. */
2856 VEC (thread_item_t) *items;
2859 /* Discard the contents of the constructed thread listing context. */
2862 clear_threads_listing_context (void *p)
2864 struct threads_listing_context *context
2865 = (struct threads_listing_context *) p;
2867 struct thread_item *item;
2869 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2871 xfree (item->extra);
2875 VEC_free (thread_item_t, context->items);
2878 /* Remove the thread specified as the related_pid field of WS
2879 from the CONTEXT list. */
2882 threads_listing_context_remove (struct target_waitstatus *ws,
2883 struct threads_listing_context *context)
2885 struct thread_item *item;
2887 ptid_t child_ptid = ws->value.related_pid;
2889 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2891 if (ptid_equal (item->ptid, child_ptid))
2893 VEC_ordered_remove (thread_item_t, context->items, i);
2900 remote_newthread_step (threadref *ref, void *data)
2902 struct threads_listing_context *context
2903 = (struct threads_listing_context *) data;
2904 struct thread_item item;
2905 int pid = ptid_get_pid (inferior_ptid);
2907 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2911 VEC_safe_push (thread_item_t, context->items, &item);
2913 return 1; /* continue iterator */
2916 #define CRAZY_MAX_THREADS 1000
2919 remote_current_thread (ptid_t oldpid)
2921 struct remote_state *rs = get_remote_state ();
2924 getpkt (&rs->buf, &rs->buf_size, 0);
2925 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2930 result = read_ptid (&rs->buf[2], &obuf);
2931 if (*obuf != '\0' && remote_debug)
2932 fprintf_unfiltered (gdb_stdlog,
2933 "warning: garbage in qC reply\n");
2941 /* List remote threads using the deprecated qL packet. */
2944 remote_get_threads_with_ql (struct target_ops *ops,
2945 struct threads_listing_context *context)
2947 if (remote_threadlist_iterator (remote_newthread_step, context,
2948 CRAZY_MAX_THREADS) >= 0)
2954 #if defined(HAVE_LIBEXPAT)
2957 start_thread (struct gdb_xml_parser *parser,
2958 const struct gdb_xml_element *element,
2959 void *user_data, VEC(gdb_xml_value_s) *attributes)
2961 struct threads_listing_context *data
2962 = (struct threads_listing_context *) user_data;
2964 struct thread_item item;
2966 struct gdb_xml_value *attr;
2968 id = (char *) xml_find_attribute (attributes, "id")->value;
2969 item.ptid = read_ptid (id, NULL);
2971 attr = xml_find_attribute (attributes, "core");
2973 item.core = *(ULONGEST *) attr->value;
2977 attr = xml_find_attribute (attributes, "name");
2978 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
2982 VEC_safe_push (thread_item_t, data->items, &item);
2986 end_thread (struct gdb_xml_parser *parser,
2987 const struct gdb_xml_element *element,
2988 void *user_data, const char *body_text)
2990 struct threads_listing_context *data
2991 = (struct threads_listing_context *) user_data;
2993 if (body_text && *body_text)
2994 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2997 const struct gdb_xml_attribute thread_attributes[] = {
2998 { "id", GDB_XML_AF_NONE, NULL, NULL },
2999 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3000 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3001 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3004 const struct gdb_xml_element thread_children[] = {
3005 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3008 const struct gdb_xml_element threads_children[] = {
3009 { "thread", thread_attributes, thread_children,
3010 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3011 start_thread, end_thread },
3012 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3015 const struct gdb_xml_element threads_elements[] = {
3016 { "threads", NULL, threads_children,
3017 GDB_XML_EF_NONE, NULL, NULL },
3018 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3023 /* List remote threads using qXfer:threads:read. */
3026 remote_get_threads_with_qxfer (struct target_ops *ops,
3027 struct threads_listing_context *context)
3029 #if defined(HAVE_LIBEXPAT)
3030 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3032 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3033 struct cleanup *back_to = make_cleanup (xfree, xml);
3035 if (xml != NULL && *xml != '\0')
3037 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3038 threads_elements, xml, context);
3041 do_cleanups (back_to);
3049 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3052 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3053 struct threads_listing_context *context)
3055 struct remote_state *rs = get_remote_state ();
3057 if (rs->use_threadinfo_query)
3061 putpkt ("qfThreadInfo");
3062 getpkt (&rs->buf, &rs->buf_size, 0);
3064 if (bufp[0] != '\0') /* q packet recognized */
3066 while (*bufp++ == 'm') /* reply contains one or more TID */
3070 struct thread_item item;
3072 item.ptid = read_ptid (bufp, &bufp);
3076 VEC_safe_push (thread_item_t, context->items, &item);
3078 while (*bufp++ == ','); /* comma-separated list */
3079 putpkt ("qsThreadInfo");
3080 getpkt (&rs->buf, &rs->buf_size, 0);
3087 /* Packet not recognized. */
3088 rs->use_threadinfo_query = 0;
3095 /* Implement the to_update_thread_list function for the remote
3099 remote_update_thread_list (struct target_ops *ops)
3101 struct remote_state *rs = get_remote_state ();
3102 struct threads_listing_context context;
3103 struct cleanup *old_chain;
3106 context.items = NULL;
3107 old_chain = make_cleanup (clear_threads_listing_context, &context);
3109 /* We have a few different mechanisms to fetch the thread list. Try
3110 them all, starting with the most preferred one first, falling
3111 back to older methods. */
3112 if (remote_get_threads_with_qxfer (ops, &context)
3113 || remote_get_threads_with_qthreadinfo (ops, &context)
3114 || remote_get_threads_with_ql (ops, &context))
3117 struct thread_item *item;
3118 struct thread_info *tp, *tmp;
3122 if (VEC_empty (thread_item_t, context.items)
3123 && remote_thread_always_alive (ops, inferior_ptid))
3125 /* Some targets don't really support threads, but still
3126 reply an (empty) thread list in response to the thread
3127 listing packets, instead of replying "packet not
3128 supported". Exit early so we don't delete the main
3130 do_cleanups (old_chain);
3134 /* CONTEXT now holds the current thread list on the remote
3135 target end. Delete GDB-side threads no longer found on the
3137 ALL_THREADS_SAFE (tp, tmp)
3140 VEC_iterate (thread_item_t, context.items, i, item);
3143 if (ptid_equal (item->ptid, tp->ptid))
3147 if (i == VEC_length (thread_item_t, context.items))
3150 delete_thread (tp->ptid);
3154 /* Remove any unreported fork child threads from CONTEXT so
3155 that we don't interfere with follow fork, which is where
3156 creation of such threads is handled. */
3157 remove_new_fork_children (&context);
3159 /* And now add threads we don't know about yet to our list. */
3161 VEC_iterate (thread_item_t, context.items, i, item);
3164 if (!ptid_equal (item->ptid, null_ptid))
3166 struct private_thread_info *info;
3167 /* In non-stop mode, we assume new found threads are
3168 running until proven otherwise with a stop reply. In
3169 all-stop, we can only get here if all threads are
3171 int running = target_is_non_stop_p () ? 1 : 0;
3173 remote_notice_new_inferior (item->ptid, running);
3175 info = demand_private_info (item->ptid);
3176 info->core = item->core;
3177 info->extra = item->extra;
3179 info->name = item->name;
3187 /* If no thread listing method is supported, then query whether
3188 each known thread is alive, one by one, with the T packet.
3189 If the target doesn't support threads at all, then this is a
3190 no-op. See remote_thread_alive. */
3194 do_cleanups (old_chain);
3198 * Collect a descriptive string about the given thread.
3199 * The target may say anything it wants to about the thread
3200 * (typically info about its blocked / runnable state, name, etc.).
3201 * This string will appear in the info threads display.
3203 * Optional: targets are not required to implement this function.
3207 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3209 struct remote_state *rs = get_remote_state ();
3213 struct gdb_ext_thread_info threadinfo;
3214 static char display_buf[100]; /* arbitrary... */
3215 int n = 0; /* position in display_buf */
3217 if (rs->remote_desc == 0) /* paranoia */
3218 internal_error (__FILE__, __LINE__,
3219 _("remote_threads_extra_info"));
3221 if (ptid_equal (tp->ptid, magic_null_ptid)
3222 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3223 /* This is the main thread which was added by GDB. The remote
3224 server doesn't know about it. */
3227 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3229 struct thread_info *info = find_thread_ptid (tp->ptid);
3231 if (info && info->priv)
3232 return info->priv->extra;
3237 if (rs->use_threadextra_query)
3240 char *endb = rs->buf + get_remote_packet_size ();
3242 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3244 write_ptid (b, endb, tp->ptid);
3247 getpkt (&rs->buf, &rs->buf_size, 0);
3248 if (rs->buf[0] != 0)
3250 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3251 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3252 display_buf [result] = '\0';
3257 /* If the above query fails, fall back to the old method. */
3258 rs->use_threadextra_query = 0;
3259 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3260 | TAG_MOREDISPLAY | TAG_DISPLAY;
3261 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3262 if (remote_get_threadinfo (&id, set, &threadinfo))
3263 if (threadinfo.active)
3265 if (*threadinfo.shortname)
3266 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3267 " Name: %s,", threadinfo.shortname);
3268 if (*threadinfo.display)
3269 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3270 " State: %s,", threadinfo.display);
3271 if (*threadinfo.more_display)
3272 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3273 " Priority: %s", threadinfo.more_display);
3277 /* For purely cosmetic reasons, clear up trailing commas. */
3278 if (',' == display_buf[n-1])
3279 display_buf[n-1] = ' ';
3288 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3289 struct static_tracepoint_marker *marker)
3291 struct remote_state *rs = get_remote_state ();
3294 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3296 p += hexnumstr (p, addr);
3298 getpkt (&rs->buf, &rs->buf_size, 0);
3302 error (_("Remote failure reply: %s"), p);
3306 parse_static_tracepoint_marker_definition (p, &p, marker);
3313 static VEC(static_tracepoint_marker_p) *
3314 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3317 struct remote_state *rs = get_remote_state ();
3318 VEC(static_tracepoint_marker_p) *markers = NULL;
3319 struct static_tracepoint_marker *marker = NULL;
3320 struct cleanup *old_chain;
3323 /* Ask for a first packet of static tracepoint marker
3326 getpkt (&rs->buf, &rs->buf_size, 0);
3329 error (_("Remote failure reply: %s"), p);
3331 old_chain = make_cleanup (free_current_marker, &marker);
3336 marker = XCNEW (struct static_tracepoint_marker);
3340 parse_static_tracepoint_marker_definition (p, &p, marker);
3342 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3344 VEC_safe_push (static_tracepoint_marker_p,
3350 release_static_tracepoint_marker (marker);
3351 memset (marker, 0, sizeof (*marker));
3354 while (*p++ == ','); /* comma-separated list */
3355 /* Ask for another packet of static tracepoint definition. */
3357 getpkt (&rs->buf, &rs->buf_size, 0);
3361 do_cleanups (old_chain);
3366 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3369 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3371 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3375 /* Restart the remote side; this is an extended protocol operation. */
3378 extended_remote_restart (void)
3380 struct remote_state *rs = get_remote_state ();
3382 /* Send the restart command; for reasons I don't understand the
3383 remote side really expects a number after the "R". */
3384 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3387 remote_fileio_reset ();
3390 /* Clean up connection to a remote debugger. */
3393 remote_close (struct target_ops *self)
3395 struct remote_state *rs = get_remote_state ();
3397 if (rs->remote_desc == NULL)
3398 return; /* already closed */
3400 /* Make sure we leave stdin registered in the event loop, and we
3401 don't leave the async SIGINT signal handler installed. */
3402 remote_terminal_ours (self);
3404 serial_close (rs->remote_desc);
3405 rs->remote_desc = NULL;
3407 /* We don't have a connection to the remote stub anymore. Get rid
3408 of all the inferiors and their threads we were controlling.
3409 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3410 will be unable to find the thread corresponding to (pid, 0, 0). */
3411 inferior_ptid = null_ptid;
3412 discard_all_inferiors ();
3414 /* We are closing the remote target, so we should discard
3415 everything of this target. */
3416 discard_pending_stop_replies_in_queue (rs);
3418 if (remote_async_inferior_event_token)
3419 delete_async_event_handler (&remote_async_inferior_event_token);
3421 remote_notif_state_xfree (rs->notif_state);
3423 trace_reset_local_state ();
3426 /* Query the remote side for the text, data and bss offsets. */
3431 struct remote_state *rs = get_remote_state ();
3434 int lose, num_segments = 0, do_sections, do_segments;
3435 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3436 struct section_offsets *offs;
3437 struct symfile_segment_data *data;
3439 if (symfile_objfile == NULL)
3442 putpkt ("qOffsets");
3443 getpkt (&rs->buf, &rs->buf_size, 0);
3446 if (buf[0] == '\000')
3447 return; /* Return silently. Stub doesn't support
3451 warning (_("Remote failure reply: %s"), buf);
3455 /* Pick up each field in turn. This used to be done with scanf, but
3456 scanf will make trouble if CORE_ADDR size doesn't match
3457 conversion directives correctly. The following code will work
3458 with any size of CORE_ADDR. */
3459 text_addr = data_addr = bss_addr = 0;
3463 if (startswith (ptr, "Text="))
3466 /* Don't use strtol, could lose on big values. */
3467 while (*ptr && *ptr != ';')
3468 text_addr = (text_addr << 4) + fromhex (*ptr++);
3470 if (startswith (ptr, ";Data="))
3473 while (*ptr && *ptr != ';')
3474 data_addr = (data_addr << 4) + fromhex (*ptr++);
3479 if (!lose && startswith (ptr, ";Bss="))
3482 while (*ptr && *ptr != ';')
3483 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3485 if (bss_addr != data_addr)
3486 warning (_("Target reported unsupported offsets: %s"), buf);
3491 else if (startswith (ptr, "TextSeg="))
3494 /* Don't use strtol, could lose on big values. */
3495 while (*ptr && *ptr != ';')
3496 text_addr = (text_addr << 4) + fromhex (*ptr++);
3499 if (startswith (ptr, ";DataSeg="))
3502 while (*ptr && *ptr != ';')
3503 data_addr = (data_addr << 4) + fromhex (*ptr++);
3511 error (_("Malformed response to offset query, %s"), buf);
3512 else if (*ptr != '\0')
3513 warning (_("Target reported unsupported offsets: %s"), buf);
3515 offs = ((struct section_offsets *)
3516 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3517 memcpy (offs, symfile_objfile->section_offsets,
3518 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3520 data = get_symfile_segment_data (symfile_objfile->obfd);
3521 do_segments = (data != NULL);
3522 do_sections = num_segments == 0;
3524 if (num_segments > 0)
3526 segments[0] = text_addr;
3527 segments[1] = data_addr;
3529 /* If we have two segments, we can still try to relocate everything
3530 by assuming that the .text and .data offsets apply to the whole
3531 text and data segments. Convert the offsets given in the packet
3532 to base addresses for symfile_map_offsets_to_segments. */
3533 else if (data && data->num_segments == 2)
3535 segments[0] = data->segment_bases[0] + text_addr;
3536 segments[1] = data->segment_bases[1] + data_addr;
3539 /* If the object file has only one segment, assume that it is text
3540 rather than data; main programs with no writable data are rare,
3541 but programs with no code are useless. Of course the code might
3542 have ended up in the data segment... to detect that we would need
3543 the permissions here. */
3544 else if (data && data->num_segments == 1)
3546 segments[0] = data->segment_bases[0] + text_addr;
3549 /* There's no way to relocate by segment. */
3555 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3556 offs, num_segments, segments);
3558 if (ret == 0 && !do_sections)
3559 error (_("Can not handle qOffsets TextSeg "
3560 "response with this symbol file"));
3567 free_symfile_segment_data (data);
3571 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3573 /* This is a temporary kludge to force data and bss to use the
3574 same offsets because that's what nlmconv does now. The real
3575 solution requires changes to the stub and remote.c that I
3576 don't have time to do right now. */
3578 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3579 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3582 objfile_relocate (symfile_objfile, offs);
3585 /* Send interrupt_sequence to remote target. */
3587 send_interrupt_sequence (void)
3589 struct remote_state *rs = get_remote_state ();
3591 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3592 remote_serial_write ("\x03", 1);
3593 else if (interrupt_sequence_mode == interrupt_sequence_break)
3594 serial_send_break (rs->remote_desc);
3595 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3597 serial_send_break (rs->remote_desc);
3598 remote_serial_write ("g", 1);
3601 internal_error (__FILE__, __LINE__,
3602 _("Invalid value for interrupt_sequence_mode: %s."),
3603 interrupt_sequence_mode);
3607 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3608 and extract the PTID. Returns NULL_PTID if not found. */
3611 stop_reply_extract_thread (char *stop_reply)
3613 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3617 /* Txx r:val ; r:val (...) */
3620 /* Look for "register" named "thread". */
3625 p1 = strchr (p, ':');
3629 if (strncmp (p, "thread", p1 - p) == 0)
3630 return read_ptid (++p1, &p);
3632 p1 = strchr (p, ';');
3644 /* Determine the remote side's current thread. If we have a stop
3645 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3646 "thread" register we can extract the current thread from. If not,
3647 ask the remote which is the current thread with qC. The former
3648 method avoids a roundtrip. */
3651 get_current_thread (char *wait_status)
3653 ptid_t ptid = null_ptid;
3655 /* Note we don't use remote_parse_stop_reply as that makes use of
3656 the target architecture, which we haven't yet fully determined at
3658 if (wait_status != NULL)
3659 ptid = stop_reply_extract_thread (wait_status);
3660 if (ptid_equal (ptid, null_ptid))
3661 ptid = remote_current_thread (inferior_ptid);
3666 /* Query the remote target for which is the current thread/process,
3667 add it to our tables, and update INFERIOR_PTID. The caller is
3668 responsible for setting the state such that the remote end is ready
3669 to return the current thread.
3671 This function is called after handling the '?' or 'vRun' packets,
3672 whose response is a stop reply from which we can also try
3673 extracting the thread. If the target doesn't support the explicit
3674 qC query, we infer the current thread from that stop reply, passed
3675 in in WAIT_STATUS, which may be NULL. */
3678 add_current_inferior_and_thread (char *wait_status)
3680 struct remote_state *rs = get_remote_state ();
3684 inferior_ptid = null_ptid;
3686 /* Now, if we have thread information, update inferior_ptid. */
3687 ptid = get_current_thread (wait_status);
3689 if (!ptid_equal (ptid, null_ptid))
3691 if (!remote_multi_process_p (rs))
3694 inferior_ptid = ptid;
3698 /* Without this, some commands which require an active target
3699 (such as kill) won't work. This variable serves (at least)
3700 double duty as both the pid of the target process (if it has
3701 such), and as a flag indicating that a target is active. */
3702 inferior_ptid = magic_null_ptid;
3706 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3708 /* Add the main thread. */
3709 add_thread_silent (inferior_ptid);
3712 /* Print info about a thread that was found already stopped on
3716 print_one_stopped_thread (struct thread_info *thread)
3718 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3720 switch_to_thread (thread->ptid);
3721 stop_pc = get_frame_pc (get_current_frame ());
3722 set_current_sal_from_frame (get_current_frame ());
3724 thread->suspend.waitstatus_pending_p = 0;
3726 if (ws->kind == TARGET_WAITKIND_STOPPED)
3728 enum gdb_signal sig = ws->value.sig;
3730 if (signal_print_state (sig))
3731 observer_notify_signal_received (sig);
3733 observer_notify_normal_stop (NULL, 1);
3736 /* Process all initial stop replies the remote side sent in response
3737 to the ? packet. These indicate threads that were already stopped
3738 on initial connection. We mark these threads as stopped and print
3739 their current frame before giving the user the prompt. */
3742 process_initial_stop_replies (int from_tty)
3744 int pending_stop_replies = stop_reply_queue_length ();
3745 struct inferior *inf;
3746 struct thread_info *thread;
3747 struct thread_info *selected = NULL;
3748 struct thread_info *lowest_stopped = NULL;
3749 struct thread_info *first = NULL;
3751 /* Consume the initial pending events. */
3752 while (pending_stop_replies-- > 0)
3754 ptid_t waiton_ptid = minus_one_ptid;
3756 struct target_waitstatus ws;
3757 int ignore_event = 0;
3758 struct thread_info *thread;
3760 memset (&ws, 0, sizeof (ws));
3761 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3763 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3767 case TARGET_WAITKIND_IGNORE:
3768 case TARGET_WAITKIND_NO_RESUMED:
3769 case TARGET_WAITKIND_SIGNALLED:
3770 case TARGET_WAITKIND_EXITED:
3771 /* We shouldn't see these, but if we do, just ignore. */
3773 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3777 case TARGET_WAITKIND_EXECD:
3778 xfree (ws.value.execd_pathname);
3787 thread = find_thread_ptid (event_ptid);
3789 if (ws.kind == TARGET_WAITKIND_STOPPED)
3791 enum gdb_signal sig = ws.value.sig;
3793 /* Stubs traditionally report SIGTRAP as initial signal,
3794 instead of signal 0. Suppress it. */
3795 if (sig == GDB_SIGNAL_TRAP)
3797 thread->suspend.stop_signal = sig;
3801 thread->suspend.waitstatus = ws;
3803 if (ws.kind != TARGET_WAITKIND_STOPPED
3804 || ws.value.sig != GDB_SIGNAL_0)
3805 thread->suspend.waitstatus_pending_p = 1;
3807 set_executing (event_ptid, 0);
3808 set_running (event_ptid, 0);
3811 /* "Notice" the new inferiors before anything related to
3812 registers/memory. */
3818 inf->needs_setup = 1;
3822 thread = any_live_thread_of_process (inf->pid);
3823 notice_new_inferior (thread->ptid,
3824 thread->state == THREAD_RUNNING,
3829 /* If all-stop on top of non-stop, pause all threads. Note this
3830 records the threads' stop pc, so must be done after "noticing"
3834 stop_all_threads ();
3836 /* If all threads of an inferior were already stopped, we
3837 haven't setup the inferior yet. */
3843 if (inf->needs_setup)
3845 thread = any_live_thread_of_process (inf->pid);
3846 switch_to_thread_no_regs (thread);
3852 /* Now go over all threads that are stopped, and print their current
3853 frame. If all-stop, then if there's a signalled thread, pick
3855 ALL_NON_EXITED_THREADS (thread)
3857 struct target_waitstatus *ws;
3863 set_running (thread->ptid, 0);
3864 else if (thread->state != THREAD_STOPPED)
3867 ws = &thread->suspend.waitstatus;
3869 if (selected == NULL
3870 && thread->suspend.waitstatus_pending_p)
3873 if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3874 lowest_stopped = thread;
3877 print_one_stopped_thread (thread);
3880 /* In all-stop, we only print the status of one thread, and leave
3881 others with their status pending. */
3886 thread = lowest_stopped;
3890 print_one_stopped_thread (thread);
3893 /* For "info program". */
3894 thread = inferior_thread ();
3895 if (thread->state == THREAD_STOPPED)
3896 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3900 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3902 struct remote_state *rs = get_remote_state ();
3903 struct packet_config *noack_config;
3904 char *wait_status = NULL;
3906 immediate_quit++; /* Allow user to interrupt it. */
3909 if (interrupt_on_connect)
3910 send_interrupt_sequence ();
3912 /* Ack any packet which the remote side has already sent. */
3913 serial_write (rs->remote_desc, "+", 1);
3915 /* Signal other parts that we're going through the initial setup,
3916 and so things may not be stable yet. */
3917 rs->starting_up = 1;
3919 /* The first packet we send to the target is the optional "supported
3920 packets" request. If the target can answer this, it will tell us
3921 which later probes to skip. */
3922 remote_query_supported ();
3924 /* If the stub wants to get a QAllow, compose one and send it. */
3925 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3926 remote_set_permissions (target);
3928 /* Next, we possibly activate noack mode.
3930 If the QStartNoAckMode packet configuration is set to AUTO,
3931 enable noack mode if the stub reported a wish for it with
3934 If set to TRUE, then enable noack mode even if the stub didn't
3935 report it in qSupported. If the stub doesn't reply OK, the
3936 session ends with an error.
3938 If FALSE, then don't activate noack mode, regardless of what the
3939 stub claimed should be the default with qSupported. */
3941 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3942 if (packet_config_support (noack_config) != PACKET_DISABLE)
3944 putpkt ("QStartNoAckMode");
3945 getpkt (&rs->buf, &rs->buf_size, 0);
3946 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3952 /* Tell the remote that we are using the extended protocol. */
3954 getpkt (&rs->buf, &rs->buf_size, 0);
3957 /* Let the target know which signals it is allowed to pass down to
3959 update_signals_program_target ();
3961 /* Next, if the target can specify a description, read it. We do
3962 this before anything involving memory or registers. */
3963 target_find_description ();
3965 /* Next, now that we know something about the target, update the
3966 address spaces in the program spaces. */
3967 update_address_spaces ();
3969 /* On OSs where the list of libraries is global to all
3970 processes, we fetch them early. */
3971 if (gdbarch_has_global_solist (target_gdbarch ()))
3972 solib_add (NULL, from_tty, target, auto_solib_add);
3974 if (target_is_non_stop_p ())
3976 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3977 error (_("Non-stop mode requested, but remote "
3978 "does not support non-stop"));
3980 putpkt ("QNonStop:1");
3981 getpkt (&rs->buf, &rs->buf_size, 0);
3983 if (strcmp (rs->buf, "OK") != 0)
3984 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3986 /* Find about threads and processes the stub is already
3987 controlling. We default to adding them in the running state.
3988 The '?' query below will then tell us about which threads are
3990 remote_update_thread_list (target);
3992 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3994 /* Don't assume that the stub can operate in all-stop mode.
3995 Request it explicitly. */
3996 putpkt ("QNonStop:0");
3997 getpkt (&rs->buf, &rs->buf_size, 0);
3999 if (strcmp (rs->buf, "OK") != 0)
4000 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4003 /* Upload TSVs regardless of whether the target is running or not. The
4004 remote stub, such as GDBserver, may have some predefined or builtin
4005 TSVs, even if the target is not running. */
4006 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4008 struct uploaded_tsv *uploaded_tsvs = NULL;
4010 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4011 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4014 /* Check whether the target is running now. */
4016 getpkt (&rs->buf, &rs->buf_size, 0);
4018 if (!target_is_non_stop_p ())
4022 struct inferior *inf;
4024 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4027 error (_("The target is not running (try extended-remote?)"));
4029 /* We're connected, but not running. Drop out before we
4030 call start_remote. */
4031 rs->starting_up = 0;
4036 /* Save the reply for later. */
4037 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4038 strcpy (wait_status, rs->buf);
4041 /* Fetch thread list. */
4042 target_update_thread_list ();
4044 /* Let the stub know that we want it to return the thread. */
4045 set_continue_thread (minus_one_ptid);
4047 if (thread_count () == 0)
4049 /* Target has no concept of threads at all. GDB treats
4050 non-threaded target as single-threaded; add a main
4052 add_current_inferior_and_thread (wait_status);
4056 /* We have thread information; select the thread the target
4057 says should be current. If we're reconnecting to a
4058 multi-threaded program, this will ideally be the thread
4059 that last reported an event before GDB disconnected. */
4060 inferior_ptid = get_current_thread (wait_status);
4061 if (ptid_equal (inferior_ptid, null_ptid))
4063 /* Odd... The target was able to list threads, but not
4064 tell us which thread was current (no "thread"
4065 register in T stop reply?). Just pick the first
4066 thread in the thread list then. */
4069 fprintf_unfiltered (gdb_stdlog,
4070 "warning: couldn't determine remote "
4071 "current thread; picking first in list.\n");
4073 inferior_ptid = thread_list->ptid;
4077 /* init_wait_for_inferior should be called before get_offsets in order
4078 to manage `inserted' flag in bp loc in a correct state.
4079 breakpoint_init_inferior, called from init_wait_for_inferior, set
4080 `inserted' flag to 0, while before breakpoint_re_set, called from
4081 start_remote, set `inserted' flag to 1. In the initialization of
4082 inferior, breakpoint_init_inferior should be called first, and then
4083 breakpoint_re_set can be called. If this order is broken, state of
4084 `inserted' flag is wrong, and cause some problems on breakpoint
4086 init_wait_for_inferior ();
4088 get_offsets (); /* Get text, data & bss offsets. */
4090 /* If we could not find a description using qXfer, and we know
4091 how to do it some other way, try again. This is not
4092 supported for non-stop; it could be, but it is tricky if
4093 there are no stopped threads when we connect. */
4094 if (remote_read_description_p (target)
4095 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4097 target_clear_description ();
4098 target_find_description ();
4101 /* Use the previously fetched status. */
4102 gdb_assert (wait_status != NULL);
4103 strcpy (rs->buf, wait_status);
4104 rs->cached_wait_status = 1;
4107 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4111 /* Clear WFI global state. Do this before finding about new
4112 threads and inferiors, and setting the current inferior.
4113 Otherwise we would clear the proceed status of the current
4114 inferior when we want its stop_soon state to be preserved
4115 (see notice_new_inferior). */
4116 init_wait_for_inferior ();
4118 /* In non-stop, we will either get an "OK", meaning that there
4119 are no stopped threads at this time; or, a regular stop
4120 reply. In the latter case, there may be more than one thread
4121 stopped --- we pull them all out using the vStopped
4123 if (strcmp (rs->buf, "OK") != 0)
4125 struct notif_client *notif = ¬if_client_stop;
4127 /* remote_notif_get_pending_replies acks this one, and gets
4129 rs->notif_state->pending_event[notif_client_stop.id]
4130 = remote_notif_parse (notif, rs->buf);
4131 remote_notif_get_pending_events (notif);
4134 if (thread_count () == 0)
4137 error (_("The target is not running (try extended-remote?)"));
4139 /* We're connected, but not running. Drop out before we
4140 call start_remote. */
4141 rs->starting_up = 0;
4145 /* In non-stop mode, any cached wait status will be stored in
4146 the stop reply queue. */
4147 gdb_assert (wait_status == NULL);
4149 /* Report all signals during attach/startup. */
4150 remote_pass_signals (target, 0, NULL);
4152 /* If there are already stopped threads, mark them stopped and
4153 report their stops before giving the prompt to the user. */
4154 process_initial_stop_replies (from_tty);
4156 if (target_can_async_p ())
4160 /* If we connected to a live target, do some additional setup. */
4161 if (target_has_execution)
4163 if (symfile_objfile) /* No use without a symbol-file. */
4164 remote_check_symbols ();
4167 /* Possibly the target has been engaged in a trace run started
4168 previously; find out where things are at. */
4169 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4171 struct uploaded_tp *uploaded_tps = NULL;
4173 if (current_trace_status ()->running)
4174 printf_filtered (_("Trace is already running on the target.\n"));
4176 remote_upload_tracepoints (target, &uploaded_tps);
4178 merge_uploaded_tracepoints (&uploaded_tps);
4181 /* The thread and inferior lists are now synchronized with the
4182 target, our symbols have been relocated, and we're merged the
4183 target's tracepoints with ours. We're done with basic start
4185 rs->starting_up = 0;
4187 /* Maybe breakpoints are global and need to be inserted now. */
4188 if (breakpoints_should_be_inserted_now ())
4189 insert_breakpoints ();
4192 /* Open a connection to a remote debugger.
4193 NAME is the filename used for communication. */
4196 remote_open (const char *name, int from_tty)
4198 remote_open_1 (name, from_tty, &remote_ops, 0);
4201 /* Open a connection to a remote debugger using the extended
4202 remote gdb protocol. NAME is the filename used for communication. */
4205 extended_remote_open (const char *name, int from_tty)
4207 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4210 /* Reset all packets back to "unknown support". Called when opening a
4211 new connection to a remote target. */
4214 reset_all_packet_configs_support (void)
4218 for (i = 0; i < PACKET_MAX; i++)
4219 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4222 /* Initialize all packet configs. */
4225 init_all_packet_configs (void)
4229 for (i = 0; i < PACKET_MAX; i++)
4231 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4232 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4236 /* Symbol look-up. */
4239 remote_check_symbols (void)
4241 struct remote_state *rs = get_remote_state ();
4242 char *msg, *reply, *tmp;
4243 struct bound_minimal_symbol sym;
4245 struct cleanup *old_chain;
4247 /* The remote side has no concept of inferiors that aren't running
4248 yet, it only knows about running processes. If we're connected
4249 but our current inferior is not running, we should not invite the
4250 remote target to request symbol lookups related to its
4251 (unrelated) current process. */
4252 if (!target_has_execution)
4255 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4258 /* Make sure the remote is pointing at the right process. Note
4259 there's no way to select "no process". */
4260 set_general_process ();
4262 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4263 because we need both at the same time. */
4264 msg = (char *) xmalloc (get_remote_packet_size ());
4265 old_chain = make_cleanup (xfree, msg);
4267 /* Invite target to request symbol lookups. */
4269 putpkt ("qSymbol::");
4270 getpkt (&rs->buf, &rs->buf_size, 0);
4271 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
4274 while (startswith (reply, "qSymbol:"))
4276 struct bound_minimal_symbol sym;
4279 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4281 sym = lookup_minimal_symbol (msg, NULL, NULL);
4282 if (sym.minsym == NULL)
4283 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4286 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4287 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4289 /* If this is a function address, return the start of code
4290 instead of any data function descriptor. */
4291 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4295 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4296 phex_nz (sym_addr, addr_size), &reply[8]);
4300 getpkt (&rs->buf, &rs->buf_size, 0);
4304 do_cleanups (old_chain);
4307 static struct serial *
4308 remote_serial_open (const char *name)
4310 static int udp_warning = 0;
4312 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4313 of in ser-tcp.c, because it is the remote protocol assuming that the
4314 serial connection is reliable and not the serial connection promising
4316 if (!udp_warning && startswith (name, "udp:"))
4318 warning (_("The remote protocol may be unreliable over UDP.\n"
4319 "Some events may be lost, rendering further debugging "
4324 return serial_open (name);
4327 /* Inform the target of our permission settings. The permission flags
4328 work without this, but if the target knows the settings, it can do
4329 a couple things. First, it can add its own check, to catch cases
4330 that somehow manage to get by the permissions checks in target
4331 methods. Second, if the target is wired to disallow particular
4332 settings (for instance, a system in the field that is not set up to
4333 be able to stop at a breakpoint), it can object to any unavailable
4337 remote_set_permissions (struct target_ops *self)
4339 struct remote_state *rs = get_remote_state ();
4341 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4342 "WriteReg:%x;WriteMem:%x;"
4343 "InsertBreak:%x;InsertTrace:%x;"
4344 "InsertFastTrace:%x;Stop:%x",
4345 may_write_registers, may_write_memory,
4346 may_insert_breakpoints, may_insert_tracepoints,
4347 may_insert_fast_tracepoints, may_stop);
4349 getpkt (&rs->buf, &rs->buf_size, 0);
4351 /* If the target didn't like the packet, warn the user. Do not try
4352 to undo the user's settings, that would just be maddening. */
4353 if (strcmp (rs->buf, "OK") != 0)
4354 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4357 /* This type describes each known response to the qSupported
4359 struct protocol_feature
4361 /* The name of this protocol feature. */
4364 /* The default for this protocol feature. */
4365 enum packet_support default_support;
4367 /* The function to call when this feature is reported, or after
4368 qSupported processing if the feature is not supported.
4369 The first argument points to this structure. The second
4370 argument indicates whether the packet requested support be
4371 enabled, disabled, or probed (or the default, if this function
4372 is being called at the end of processing and this feature was
4373 not reported). The third argument may be NULL; if not NULL, it
4374 is a NUL-terminated string taken from the packet following
4375 this feature's name and an equals sign. */
4376 void (*func) (const struct protocol_feature *, enum packet_support,
4379 /* The corresponding packet for this feature. Only used if
4380 FUNC is remote_supported_packet. */
4385 remote_supported_packet (const struct protocol_feature *feature,
4386 enum packet_support support,
4387 const char *argument)
4391 warning (_("Remote qSupported response supplied an unexpected value for"
4392 " \"%s\"."), feature->name);
4396 remote_protocol_packets[feature->packet].support = support;
4400 remote_packet_size (const struct protocol_feature *feature,
4401 enum packet_support support, const char *value)
4403 struct remote_state *rs = get_remote_state ();
4408 if (support != PACKET_ENABLE)
4411 if (value == NULL || *value == '\0')
4413 warning (_("Remote target reported \"%s\" without a size."),
4419 packet_size = strtol (value, &value_end, 16);
4420 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4422 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4423 feature->name, value);
4427 /* Record the new maximum packet size. */
4428 rs->explicit_packet_size = packet_size;
4431 static const struct protocol_feature remote_protocol_features[] = {
4432 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4433 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4434 PACKET_qXfer_auxv },
4435 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4436 PACKET_qXfer_exec_file },
4437 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4438 PACKET_qXfer_features },
4439 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4440 PACKET_qXfer_libraries },
4441 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4442 PACKET_qXfer_libraries_svr4 },
4443 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4444 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4445 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4446 PACKET_qXfer_memory_map },
4447 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4448 PACKET_qXfer_spu_read },
4449 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4450 PACKET_qXfer_spu_write },
4451 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4452 PACKET_qXfer_osdata },
4453 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4454 PACKET_qXfer_threads },
4455 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4456 PACKET_qXfer_traceframe_info },
4457 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4458 PACKET_QPassSignals },
4459 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4460 PACKET_QProgramSignals },
4461 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4462 PACKET_QStartNoAckMode },
4463 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4464 PACKET_multiprocess_feature },
4465 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4466 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4467 PACKET_qXfer_siginfo_read },
4468 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4469 PACKET_qXfer_siginfo_write },
4470 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4471 PACKET_ConditionalTracepoints },
4472 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4473 PACKET_ConditionalBreakpoints },
4474 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4475 PACKET_BreakpointCommands },
4476 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4477 PACKET_FastTracepoints },
4478 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4479 PACKET_StaticTracepoints },
4480 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4481 PACKET_InstallInTrace},
4482 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4483 PACKET_DisconnectedTracing_feature },
4484 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4486 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4488 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4489 PACKET_TracepointSource },
4490 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4492 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4493 PACKET_EnableDisableTracepoints_feature },
4494 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4495 PACKET_qXfer_fdpic },
4496 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4498 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4499 PACKET_QDisableRandomization },
4500 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4501 { "QTBuffer:size", PACKET_DISABLE,
4502 remote_supported_packet, PACKET_QTBuffer_size},
4503 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4504 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4505 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4506 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4507 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4508 PACKET_qXfer_btrace },
4509 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4510 PACKET_qXfer_btrace_conf },
4511 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4512 PACKET_Qbtrace_conf_bts_size },
4513 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4514 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4515 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4516 PACKET_fork_event_feature },
4517 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4518 PACKET_vfork_event_feature },
4519 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4520 PACKET_exec_event_feature },
4521 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4522 PACKET_Qbtrace_conf_pt_size },
4523 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported }
4526 static char *remote_support_xml;
4528 /* Register string appended to "xmlRegisters=" in qSupported query. */
4531 register_remote_support_xml (const char *xml)
4533 #if defined(HAVE_LIBEXPAT)
4534 if (remote_support_xml == NULL)
4535 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4538 char *copy = xstrdup (remote_support_xml + 13);
4539 char *p = strtok (copy, ",");
4543 if (strcmp (p, xml) == 0)
4550 while ((p = strtok (NULL, ",")) != NULL);
4553 remote_support_xml = reconcat (remote_support_xml,
4554 remote_support_xml, ",", xml,
4561 remote_query_supported_append (char *msg, const char *append)
4564 return reconcat (msg, msg, ";", append, (char *) NULL);
4566 return xstrdup (append);
4570 remote_query_supported (void)
4572 struct remote_state *rs = get_remote_state ();
4575 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4577 /* The packet support flags are handled differently for this packet
4578 than for most others. We treat an error, a disabled packet, and
4579 an empty response identically: any features which must be reported
4580 to be used will be automatically disabled. An empty buffer
4581 accomplishes this, since that is also the representation for a list
4582 containing no features. */
4585 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4588 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4590 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4591 q = remote_query_supported_append (q, "multiprocess+");
4593 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4594 q = remote_query_supported_append (q, "swbreak+");
4595 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4596 q = remote_query_supported_append (q, "hwbreak+");
4598 q = remote_query_supported_append (q, "qRelocInsn+");
4602 if (packet_set_cmd_state (PACKET_fork_event_feature)
4603 != AUTO_BOOLEAN_FALSE)
4604 q = remote_query_supported_append (q, "fork-events+");
4605 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4606 != AUTO_BOOLEAN_FALSE)
4607 q = remote_query_supported_append (q, "vfork-events+");
4608 if (packet_set_cmd_state (PACKET_exec_event_feature)
4609 != AUTO_BOOLEAN_FALSE)
4610 q = remote_query_supported_append (q, "exec-events+");
4613 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4614 q = remote_query_supported_append (q, "vContSupported+");
4616 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4617 the qSupported:xmlRegisters=i386 handling. */
4618 if (remote_support_xml != NULL)
4619 q = remote_query_supported_append (q, remote_support_xml);
4621 q = reconcat (q, "qSupported:", q, (char *) NULL);
4624 do_cleanups (old_chain);
4626 getpkt (&rs->buf, &rs->buf_size, 0);
4628 /* If an error occured, warn, but do not return - just reset the
4629 buffer to empty and go on to disable features. */
4630 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4633 warning (_("Remote failure reply: %s"), rs->buf);
4638 memset (seen, 0, sizeof (seen));
4643 enum packet_support is_supported;
4644 char *p, *end, *name_end, *value;
4646 /* First separate out this item from the rest of the packet. If
4647 there's another item after this, we overwrite the separator
4648 (terminated strings are much easier to work with). */
4650 end = strchr (p, ';');
4653 end = p + strlen (p);
4663 warning (_("empty item in \"qSupported\" response"));
4668 name_end = strchr (p, '=');
4671 /* This is a name=value entry. */
4672 is_supported = PACKET_ENABLE;
4673 value = name_end + 1;
4682 is_supported = PACKET_ENABLE;
4686 is_supported = PACKET_DISABLE;
4690 is_supported = PACKET_SUPPORT_UNKNOWN;
4694 warning (_("unrecognized item \"%s\" "
4695 "in \"qSupported\" response"), p);
4701 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4702 if (strcmp (remote_protocol_features[i].name, p) == 0)
4704 const struct protocol_feature *feature;
4707 feature = &remote_protocol_features[i];
4708 feature->func (feature, is_supported, value);
4713 /* If we increased the packet size, make sure to increase the global
4714 buffer size also. We delay this until after parsing the entire
4715 qSupported packet, because this is the same buffer we were
4717 if (rs->buf_size < rs->explicit_packet_size)
4719 rs->buf_size = rs->explicit_packet_size;
4720 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4723 /* Handle the defaults for unmentioned features. */
4724 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4727 const struct protocol_feature *feature;
4729 feature = &remote_protocol_features[i];
4730 feature->func (feature, feature->default_support, NULL);
4734 /* Remove any of the remote.c targets from target stack. Upper targets depend
4735 on it so remove them first. */
4738 remote_unpush_target (void)
4740 pop_all_targets_at_and_above (process_stratum);
4744 remote_open_1 (const char *name, int from_tty,
4745 struct target_ops *target, int extended_p)
4747 struct remote_state *rs = get_remote_state ();
4750 error (_("To open a remote debug connection, you need to specify what\n"
4751 "serial device is attached to the remote system\n"
4752 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4754 /* See FIXME above. */
4755 if (!target_async_permitted)
4756 wait_forever_enabled_p = 1;
4758 /* If we're connected to a running target, target_preopen will kill it.
4759 Ask this question first, before target_preopen has a chance to kill
4761 if (rs->remote_desc != NULL && !have_inferiors ())
4764 && !query (_("Already connected to a remote target. Disconnect? ")))
4765 error (_("Still connected."));
4768 /* Here the possibly existing remote target gets unpushed. */
4769 target_preopen (from_tty);
4771 /* Make sure we send the passed signals list the next time we resume. */
4772 xfree (rs->last_pass_packet);
4773 rs->last_pass_packet = NULL;
4775 /* Make sure we send the program signals list the next time we
4777 xfree (rs->last_program_signals_packet);
4778 rs->last_program_signals_packet = NULL;
4780 remote_fileio_reset ();
4781 reopen_exec_file ();
4784 rs->remote_desc = remote_serial_open (name);
4785 if (!rs->remote_desc)
4786 perror_with_name (name);
4788 if (baud_rate != -1)
4790 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4792 /* The requested speed could not be set. Error out to
4793 top level after closing remote_desc. Take care to
4794 set remote_desc to NULL to avoid closing remote_desc
4796 serial_close (rs->remote_desc);
4797 rs->remote_desc = NULL;
4798 perror_with_name (name);
4802 serial_setparity (rs->remote_desc, serial_parity);
4803 serial_raw (rs->remote_desc);
4805 /* If there is something sitting in the buffer we might take it as a
4806 response to a command, which would be bad. */
4807 serial_flush_input (rs->remote_desc);
4811 puts_filtered ("Remote debugging using ");
4812 puts_filtered (name);
4813 puts_filtered ("\n");
4815 push_target (target); /* Switch to using remote target now. */
4817 /* Register extra event sources in the event loop. */
4818 remote_async_inferior_event_token
4819 = create_async_event_handler (remote_async_inferior_event_handler,
4821 rs->notif_state = remote_notif_state_allocate ();
4823 /* Reset the target state; these things will be queried either by
4824 remote_query_supported or as they are needed. */
4825 reset_all_packet_configs_support ();
4826 rs->cached_wait_status = 0;
4827 rs->explicit_packet_size = 0;
4829 rs->extended = extended_p;
4830 rs->waiting_for_stop_reply = 0;
4831 rs->ctrlc_pending_p = 0;
4833 rs->general_thread = not_sent_ptid;
4834 rs->continue_thread = not_sent_ptid;
4835 rs->remote_traceframe_number = -1;
4837 /* Probe for ability to use "ThreadInfo" query, as required. */
4838 rs->use_threadinfo_query = 1;
4839 rs->use_threadextra_query = 1;
4841 readahead_cache_invalidate ();
4843 if (target_async_permitted)
4845 /* With this target we start out by owning the terminal. */
4846 remote_async_terminal_ours_p = 1;
4848 /* FIXME: cagney/1999-09-23: During the initial connection it is
4849 assumed that the target is already ready and able to respond to
4850 requests. Unfortunately remote_start_remote() eventually calls
4851 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4852 around this. Eventually a mechanism that allows
4853 wait_for_inferior() to expect/get timeouts will be
4855 wait_forever_enabled_p = 0;
4858 /* First delete any symbols previously loaded from shared libraries. */
4859 no_shared_libraries (NULL, 0);
4862 init_thread_list ();
4864 /* Start the remote connection. If error() or QUIT, discard this
4865 target (we'd otherwise be in an inconsistent state) and then
4866 propogate the error on up the exception chain. This ensures that
4867 the caller doesn't stumble along blindly assuming that the
4868 function succeeded. The CLI doesn't have this problem but other
4869 UI's, such as MI do.
4871 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4872 this function should return an error indication letting the
4873 caller restore the previous state. Unfortunately the command
4874 ``target remote'' is directly wired to this function making that
4875 impossible. On a positive note, the CLI side of this problem has
4876 been fixed - the function set_cmd_context() makes it possible for
4877 all the ``target ....'' commands to share a common callback
4878 function. See cli-dump.c. */
4883 remote_start_remote (from_tty, target, extended_p);
4885 CATCH (ex, RETURN_MASK_ALL)
4887 /* Pop the partially set up target - unless something else did
4888 already before throwing the exception. */
4889 if (rs->remote_desc != NULL)
4890 remote_unpush_target ();
4891 if (target_async_permitted)
4892 wait_forever_enabled_p = 1;
4893 throw_exception (ex);
4898 remote_btrace_reset ();
4900 if (target_async_permitted)
4901 wait_forever_enabled_p = 1;
4904 /* Detach the specified process. */
4907 remote_detach_pid (int pid)
4909 struct remote_state *rs = get_remote_state ();
4911 if (remote_multi_process_p (rs))
4912 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4914 strcpy (rs->buf, "D");
4917 getpkt (&rs->buf, &rs->buf_size, 0);
4919 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4921 else if (rs->buf[0] == '\0')
4922 error (_("Remote doesn't know how to detach"));
4924 error (_("Can't detach process."));
4927 /* This detaches a program to which we previously attached, using
4928 inferior_ptid to identify the process. After this is done, GDB
4929 can be used to debug some other program. We better not have left
4930 any breakpoints in the target program or it'll die when it hits
4934 remote_detach_1 (const char *args, int from_tty)
4936 int pid = ptid_get_pid (inferior_ptid);
4937 struct remote_state *rs = get_remote_state ();
4938 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4942 error (_("Argument given to \"detach\" when remotely debugging."));
4944 if (!target_has_execution)
4945 error (_("No process to detach from."));
4949 char *exec_file = get_exec_file (0);
4950 if (exec_file == NULL)
4952 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4953 target_pid_to_str (pid_to_ptid (pid)));
4954 gdb_flush (gdb_stdout);
4957 /* Tell the remote target to detach. */
4958 remote_detach_pid (pid);
4960 if (from_tty && !rs->extended)
4961 puts_filtered (_("Ending remote debugging.\n"));
4963 /* Check to see if we are detaching a fork parent. Note that if we
4964 are detaching a fork child, tp == NULL. */
4965 is_fork_parent = (tp != NULL
4966 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4968 /* If doing detach-on-fork, we don't mourn, because that will delete
4969 breakpoints that should be available for the followed inferior. */
4970 if (!is_fork_parent)
4971 target_mourn_inferior ();
4974 inferior_ptid = null_ptid;
4975 detach_inferior (pid);
4980 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4982 remote_detach_1 (args, from_tty);
4986 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4988 remote_detach_1 (args, from_tty);
4991 /* Target follow-fork function for remote targets. On entry, and
4992 at return, the current inferior is the fork parent.
4994 Note that although this is currently only used for extended-remote,
4995 it is named remote_follow_fork in anticipation of using it for the
4996 remote target as well. */
4999 remote_follow_fork (struct target_ops *ops, int follow_child,
5002 struct remote_state *rs = get_remote_state ();
5003 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5005 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5006 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5008 /* When following the parent and detaching the child, we detach
5009 the child here. For the case of following the child and
5010 detaching the parent, the detach is done in the target-
5011 independent follow fork code in infrun.c. We can't use
5012 target_detach when detaching an unfollowed child because
5013 the client side doesn't know anything about the child. */
5014 if (detach_fork && !follow_child)
5016 /* Detach the fork child. */
5020 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5021 child_pid = ptid_get_pid (child_ptid);
5023 remote_detach_pid (child_pid);
5024 detach_inferior (child_pid);
5030 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5031 in the program space of the new inferior. On entry and at return the
5032 current inferior is the exec'ing inferior. INF is the new exec'd
5033 inferior, which may be the same as the exec'ing inferior unless
5034 follow-exec-mode is "new". */
5037 remote_follow_exec (struct target_ops *ops,
5038 struct inferior *inf, char *execd_pathname)
5040 /* We know that this is a target file name, so if it has the "target:"
5041 prefix we strip it off before saving it in the program space. */
5042 if (is_target_filename (execd_pathname))
5043 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5045 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5048 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5051 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5054 error (_("Argument given to \"disconnect\" when remotely debugging."));
5056 /* Make sure we unpush even the extended remote targets; mourn
5057 won't do it. So call remote_mourn directly instead of
5058 target_mourn_inferior. */
5059 remote_mourn (target);
5062 puts_filtered ("Ending remote debugging.\n");
5065 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5066 be chatty about it. */
5069 extended_remote_attach (struct target_ops *target, const char *args,
5072 struct remote_state *rs = get_remote_state ();
5074 char *wait_status = NULL;
5076 pid = parse_pid_to_attach (args);
5078 /* Remote PID can be freely equal to getpid, do not check it here the same
5079 way as in other targets. */
5081 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5082 error (_("This target does not support attaching to a process"));
5086 char *exec_file = get_exec_file (0);
5089 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5090 target_pid_to_str (pid_to_ptid (pid)));
5092 printf_unfiltered (_("Attaching to %s\n"),
5093 target_pid_to_str (pid_to_ptid (pid)));
5095 gdb_flush (gdb_stdout);
5098 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5100 getpkt (&rs->buf, &rs->buf_size, 0);
5102 switch (packet_ok (rs->buf,
5103 &remote_protocol_packets[PACKET_vAttach]))
5106 if (!target_is_non_stop_p ())
5108 /* Save the reply for later. */
5109 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5110 strcpy (wait_status, rs->buf);
5112 else if (strcmp (rs->buf, "OK") != 0)
5113 error (_("Attaching to %s failed with: %s"),
5114 target_pid_to_str (pid_to_ptid (pid)),
5117 case PACKET_UNKNOWN:
5118 error (_("This target does not support attaching to a process"));
5120 error (_("Attaching to %s failed"),
5121 target_pid_to_str (pid_to_ptid (pid)));
5124 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5126 inferior_ptid = pid_to_ptid (pid);
5128 if (target_is_non_stop_p ())
5130 struct thread_info *thread;
5132 /* Get list of threads. */
5133 remote_update_thread_list (target);
5135 thread = first_thread_of_process (pid);
5137 inferior_ptid = thread->ptid;
5139 inferior_ptid = pid_to_ptid (pid);
5141 /* Invalidate our notion of the remote current thread. */
5142 record_currthread (rs, minus_one_ptid);
5146 /* Now, if we have thread information, update inferior_ptid. */
5147 inferior_ptid = remote_current_thread (inferior_ptid);
5149 /* Add the main thread to the thread list. */
5150 add_thread_silent (inferior_ptid);
5153 /* Next, if the target can specify a description, read it. We do
5154 this before anything involving memory or registers. */
5155 target_find_description ();
5157 if (!target_is_non_stop_p ())
5159 /* Use the previously fetched status. */
5160 gdb_assert (wait_status != NULL);
5162 if (target_can_async_p ())
5164 struct notif_event *reply
5165 = remote_notif_parse (¬if_client_stop, wait_status);
5167 push_stop_reply ((struct stop_reply *) reply);
5173 gdb_assert (wait_status != NULL);
5174 strcpy (rs->buf, wait_status);
5175 rs->cached_wait_status = 1;
5179 gdb_assert (wait_status == NULL);
5182 /* Implementation of the to_post_attach method. */
5185 extended_remote_post_attach (struct target_ops *ops, int pid)
5187 /* Get text, data & bss offsets. */
5190 /* In certain cases GDB might not have had the chance to start
5191 symbol lookup up until now. This could happen if the debugged
5192 binary is not using shared libraries, the vsyscall page is not
5193 present (on Linux) and the binary itself hadn't changed since the
5194 debugging process was started. */
5195 if (symfile_objfile != NULL)
5196 remote_check_symbols();
5200 /* Check for the availability of vCont. This function should also check
5204 remote_vcont_probe (struct remote_state *rs)
5208 strcpy (rs->buf, "vCont?");
5210 getpkt (&rs->buf, &rs->buf_size, 0);
5213 /* Make sure that the features we assume are supported. */
5214 if (startswith (buf, "vCont"))
5217 int support_c, support_C;
5219 rs->supports_vCont.s = 0;
5220 rs->supports_vCont.S = 0;
5223 rs->supports_vCont.t = 0;
5224 rs->supports_vCont.r = 0;
5225 while (p && *p == ';')
5228 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5229 rs->supports_vCont.s = 1;
5230 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5231 rs->supports_vCont.S = 1;
5232 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5234 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5236 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5237 rs->supports_vCont.t = 1;
5238 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5239 rs->supports_vCont.r = 1;
5241 p = strchr (p, ';');
5244 /* If c, and C are not all supported, we can't use vCont. Clearing
5245 BUF will make packet_ok disable the packet. */
5246 if (!support_c || !support_C)
5250 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5253 /* Helper function for building "vCont" resumptions. Write a
5254 resumption to P. ENDP points to one-passed-the-end of the buffer
5255 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5256 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5257 resumed thread should be single-stepped and/or signalled. If PTID
5258 equals minus_one_ptid, then all threads are resumed; if PTID
5259 represents a process, then all threads of the process are resumed;
5260 the thread to be stepped and/or signalled is given in the global
5264 append_resumption (char *p, char *endp,
5265 ptid_t ptid, int step, enum gdb_signal siggnal)
5267 struct remote_state *rs = get_remote_state ();
5269 if (step && siggnal != GDB_SIGNAL_0)
5270 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5272 /* GDB is willing to range step. */
5273 && use_range_stepping
5274 /* Target supports range stepping. */
5275 && rs->supports_vCont.r
5276 /* We don't currently support range stepping multiple
5277 threads with a wildcard (though the protocol allows it,
5278 so stubs shouldn't make an active effort to forbid
5280 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5282 struct thread_info *tp;
5284 if (ptid_equal (ptid, minus_one_ptid))
5286 /* If we don't know about the target thread's tid, then
5287 we're resuming magic_null_ptid (see caller). */
5288 tp = find_thread_ptid (magic_null_ptid);
5291 tp = find_thread_ptid (ptid);
5292 gdb_assert (tp != NULL);
5294 if (tp->control.may_range_step)
5296 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5298 p += xsnprintf (p, endp - p, ";r%s,%s",
5299 phex_nz (tp->control.step_range_start,
5301 phex_nz (tp->control.step_range_end,
5305 p += xsnprintf (p, endp - p, ";s");
5308 p += xsnprintf (p, endp - p, ";s");
5309 else if (siggnal != GDB_SIGNAL_0)
5310 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5312 p += xsnprintf (p, endp - p, ";c");
5314 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5318 /* All (-1) threads of process. */
5319 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5321 p += xsnprintf (p, endp - p, ":");
5322 p = write_ptid (p, endp, nptid);
5324 else if (!ptid_equal (ptid, minus_one_ptid))
5326 p += xsnprintf (p, endp - p, ":");
5327 p = write_ptid (p, endp, ptid);
5333 /* Clear the thread's private info on resume. */
5336 resume_clear_thread_private_info (struct thread_info *thread)
5338 if (thread->priv != NULL)
5340 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5341 thread->priv->watch_data_address = 0;
5345 /* Append a vCont continue-with-signal action for threads that have a
5346 non-zero stop signal. */
5349 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5351 struct thread_info *thread;
5353 ALL_NON_EXITED_THREADS (thread)
5354 if (ptid_match (thread->ptid, ptid)
5355 && !ptid_equal (inferior_ptid, thread->ptid)
5356 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5358 p = append_resumption (p, endp, thread->ptid,
5359 0, thread->suspend.stop_signal);
5360 thread->suspend.stop_signal = GDB_SIGNAL_0;
5361 resume_clear_thread_private_info (thread);
5367 /* Resume the remote inferior by using a "vCont" packet. The thread
5368 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5369 resumed thread should be single-stepped and/or signalled. If PTID
5370 equals minus_one_ptid, then all threads are resumed; the thread to
5371 be stepped and/or signalled is given in the global INFERIOR_PTID.
5372 This function returns non-zero iff it resumes the inferior.
5374 This function issues a strict subset of all possible vCont commands at the
5378 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5380 struct remote_state *rs = get_remote_state ();
5384 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5385 remote_vcont_probe (rs);
5387 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5391 endp = rs->buf + get_remote_packet_size ();
5393 /* If we could generate a wider range of packets, we'd have to worry
5394 about overflowing BUF. Should there be a generic
5395 "multi-part-packet" packet? */
5397 p += xsnprintf (p, endp - p, "vCont");
5399 if (ptid_equal (ptid, magic_null_ptid))
5401 /* MAGIC_NULL_PTID means that we don't have any active threads,
5402 so we don't have any TID numbers the inferior will
5403 understand. Make sure to only send forms that do not specify
5405 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5407 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5409 /* Resume all threads (of all processes, or of a single
5410 process), with preference for INFERIOR_PTID. This assumes
5411 inferior_ptid belongs to the set of all threads we are about
5413 if (step || siggnal != GDB_SIGNAL_0)
5415 /* Step inferior_ptid, with or without signal. */
5416 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5419 /* Also pass down any pending signaled resumption for other
5420 threads not the current. */
5421 p = append_pending_thread_resumptions (p, endp, ptid);
5423 /* And continue others without a signal. */
5424 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5428 /* Scheduler locking; resume only PTID. */
5429 append_resumption (p, endp, ptid, step, siggnal);
5432 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5435 if (target_is_non_stop_p ())
5437 /* In non-stop, the stub replies to vCont with "OK". The stop
5438 reply will be reported asynchronously by means of a `%Stop'
5440 getpkt (&rs->buf, &rs->buf_size, 0);
5441 if (strcmp (rs->buf, "OK") != 0)
5442 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5448 /* Tell the remote machine to resume. */
5451 remote_resume (struct target_ops *ops,
5452 ptid_t ptid, int step, enum gdb_signal siggnal)
5454 struct remote_state *rs = get_remote_state ();
5456 struct thread_info *thread;
5458 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5459 (explained in remote-notif.c:handle_notification) so
5460 remote_notif_process is not called. We need find a place where
5461 it is safe to start a 'vNotif' sequence. It is good to do it
5462 before resuming inferior, because inferior was stopped and no RSP
5463 traffic at that moment. */
5464 if (!target_is_non_stop_p ())
5465 remote_notif_process (rs->notif_state, ¬if_client_stop);
5467 rs->last_sent_signal = siggnal;
5468 rs->last_sent_step = step;
5470 /* The vCont packet doesn't need to specify threads via Hc. */
5471 /* No reverse support (yet) for vCont. */
5472 if (execution_direction != EXEC_REVERSE)
5473 if (remote_vcont_resume (ptid, step, siggnal))
5476 /* All other supported resume packets do use Hc, so set the continue
5478 if (ptid_equal (ptid, minus_one_ptid))
5479 set_continue_thread (any_thread_ptid);
5481 set_continue_thread (ptid);
5483 ALL_NON_EXITED_THREADS (thread)
5484 resume_clear_thread_private_info (thread);
5487 if (execution_direction == EXEC_REVERSE)
5489 /* We don't pass signals to the target in reverse exec mode. */
5490 if (info_verbose && siggnal != GDB_SIGNAL_0)
5491 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5494 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5495 error (_("Remote reverse-step not supported."));
5496 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5497 error (_("Remote reverse-continue not supported."));
5499 strcpy (buf, step ? "bs" : "bc");
5501 else if (siggnal != GDB_SIGNAL_0)
5503 buf[0] = step ? 'S' : 'C';
5504 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5505 buf[2] = tohex (((int) siggnal) & 0xf);
5509 strcpy (buf, step ? "s" : "c");
5514 /* We are about to start executing the inferior, let's register it
5515 with the event loop. NOTE: this is the one place where all the
5516 execution commands end up. We could alternatively do this in each
5517 of the execution commands in infcmd.c. */
5518 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5519 into infcmd.c in order to allow inferior function calls to work
5520 NOT asynchronously. */
5521 if (target_can_async_p ())
5524 /* We've just told the target to resume. The remote server will
5525 wait for the inferior to stop, and then send a stop reply. In
5526 the mean time, we can't start another command/query ourselves
5527 because the stub wouldn't be ready to process it. This applies
5528 only to the base all-stop protocol, however. In non-stop (which
5529 only supports vCont), the stub replies with an "OK", and is
5530 immediate able to process further serial input. */
5531 if (!target_is_non_stop_p ())
5532 rs->waiting_for_stop_reply = 1;
5536 /* Set up the signal handler for SIGINT, while the target is
5537 executing, ovewriting the 'regular' SIGINT signal handler. */
5539 async_initialize_sigint_signal_handler (void)
5541 signal (SIGINT, async_handle_remote_sigint);
5544 /* Signal handler for SIGINT, while the target is executing. */
5546 async_handle_remote_sigint (int sig)
5548 signal (sig, async_handle_remote_sigint_twice);
5549 /* Note we need to go through gdb_call_async_signal_handler in order
5550 to wake up the event loop on Windows. */
5551 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5554 /* Signal handler for SIGINT, installed after SIGINT has already been
5555 sent once. It will take effect the second time that the user sends
5558 async_handle_remote_sigint_twice (int sig)
5560 signal (sig, async_handle_remote_sigint);
5561 /* See note in async_handle_remote_sigint. */
5562 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5565 /* Implementation of to_check_pending_interrupt. */
5568 remote_check_pending_interrupt (struct target_ops *self)
5570 struct async_signal_handler *token = async_sigint_remote_twice_token;
5572 if (async_signal_handler_is_marked (token))
5574 clear_async_signal_handler (token);
5575 call_async_signal_handler (token);
5579 /* Perform the real interruption of the target execution, in response
5582 async_remote_interrupt (gdb_client_data arg)
5585 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5587 target_interrupt (inferior_ptid);
5590 /* Perform interrupt, if the first attempt did not succeed. Just give
5591 up on the target alltogether. */
5593 async_remote_interrupt_twice (gdb_client_data arg)
5596 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5601 /* Reinstall the usual SIGINT handlers, after the target has
5604 async_cleanup_sigint_signal_handler (void *dummy)
5606 signal (SIGINT, handle_sigint);
5609 /* Send ^C to target to halt it. Target will respond, and send us a
5611 static void (*ofunc) (int);
5613 /* The command line interface's interrupt routine. This function is installed
5614 as a signal handler for SIGINT. The first time a user requests an
5615 interrupt, we call remote_interrupt to send a break or ^C. If there is no
5616 response from the target (it didn't stop when the user requested it),
5617 we ask the user if he'd like to detach from the target. */
5620 sync_remote_interrupt (int signo)
5622 /* If this doesn't work, try more severe steps. */
5623 signal (signo, sync_remote_interrupt_twice);
5625 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5628 /* The user typed ^C twice. */
5631 sync_remote_interrupt_twice (int signo)
5633 signal (signo, ofunc);
5634 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5635 signal (signo, sync_remote_interrupt);
5638 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5639 thread, all threads of a remote process, or all threads of all
5643 remote_stop_ns (ptid_t ptid)
5645 struct remote_state *rs = get_remote_state ();
5647 char *endp = rs->buf + get_remote_packet_size ();
5649 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5650 remote_vcont_probe (rs);
5652 if (!rs->supports_vCont.t)
5653 error (_("Remote server does not support stopping threads"));
5655 if (ptid_equal (ptid, minus_one_ptid)
5656 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5657 p += xsnprintf (p, endp - p, "vCont;t");
5662 p += xsnprintf (p, endp - p, "vCont;t:");
5664 if (ptid_is_pid (ptid))
5665 /* All (-1) threads of process. */
5666 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5669 /* Small optimization: if we already have a stop reply for
5670 this thread, no use in telling the stub we want this
5672 if (peek_stop_reply (ptid))
5678 write_ptid (p, endp, nptid);
5681 /* In non-stop, we get an immediate OK reply. The stop reply will
5682 come in asynchronously by notification. */
5684 getpkt (&rs->buf, &rs->buf_size, 0);
5685 if (strcmp (rs->buf, "OK") != 0)
5686 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5689 /* All-stop version of target_interrupt. Sends a break or a ^C to
5690 interrupt the remote target. It is undefined which thread of which
5691 process reports the interrupt. */
5694 remote_interrupt_as (void)
5696 struct remote_state *rs = get_remote_state ();
5698 rs->ctrlc_pending_p = 1;
5700 /* If the inferior is stopped already, but the core didn't know
5701 about it yet, just ignore the request. The cached wait status
5702 will be collected in remote_wait. */
5703 if (rs->cached_wait_status)
5706 /* Send interrupt_sequence to remote target. */
5707 send_interrupt_sequence ();
5710 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5711 the remote target. It is undefined which thread of which process
5712 reports the interrupt. Returns true if the packet is supported by
5713 the server, false otherwise. */
5716 remote_interrupt_ns (void)
5718 struct remote_state *rs = get_remote_state ();
5720 char *endp = rs->buf + get_remote_packet_size ();
5722 xsnprintf (p, endp - p, "vCtrlC");
5724 /* In non-stop, we get an immediate OK reply. The stop reply will
5725 come in asynchronously by notification. */
5727 getpkt (&rs->buf, &rs->buf_size, 0);
5729 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5733 case PACKET_UNKNOWN:
5736 error (_("Interrupting target failed: %s"), rs->buf);
5742 /* Implement the to_stop function for the remote targets. */
5745 remote_stop (struct target_ops *self, ptid_t ptid)
5748 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5750 if (target_is_non_stop_p ())
5751 remote_stop_ns (ptid);
5754 /* We don't currently have a way to transparently pause the
5755 remote target in all-stop mode. Interrupt it instead. */
5756 remote_interrupt_as ();
5760 /* Implement the to_interrupt function for the remote targets. */
5763 remote_interrupt (struct target_ops *self, ptid_t ptid)
5766 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5770 /* In non-stop mode, we always stop with no signal instead. */
5771 remote_stop_ns (ptid);
5775 /* In all-stop, we emulate ^C-ing the remote target's
5777 if (target_is_non_stop_p ())
5779 if (!remote_interrupt_ns ())
5781 /* No support for ^C-ing the remote target. Stop it
5782 (with no signal) instead. */
5783 remote_stop_ns (ptid);
5787 remote_interrupt_as ();
5791 /* Ask the user what to do when an interrupt is received. */
5794 interrupt_query (void)
5796 struct remote_state *rs = get_remote_state ();
5797 struct cleanup *old_chain;
5799 old_chain = make_cleanup_restore_target_terminal ();
5800 target_terminal_ours ();
5802 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
5804 if (query (_("The target is not responding to interrupt requests.\n"
5805 "Stop debugging it? ")))
5807 remote_unpush_target ();
5808 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5813 if (query (_("Interrupted while waiting for the program.\n"
5814 "Give up waiting? ")))
5818 do_cleanups (old_chain);
5821 /* Enable/disable target terminal ownership. Most targets can use
5822 terminal groups to control terminal ownership. Remote targets are
5823 different in that explicit transfer of ownership to/from GDB/target
5827 remote_terminal_inferior (struct target_ops *self)
5829 if (!target_async_permitted)
5830 /* Nothing to do. */
5833 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5834 idempotent. The event-loop GDB talking to an asynchronous target
5835 with a synchronous command calls this function from both
5836 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5837 transfer the terminal to the target when it shouldn't this guard
5839 if (!remote_async_terminal_ours_p)
5841 delete_file_handler (input_fd);
5842 remote_async_terminal_ours_p = 0;
5843 async_initialize_sigint_signal_handler ();
5844 /* NOTE: At this point we could also register our selves as the
5845 recipient of all input. Any characters typed could then be
5846 passed on down to the target. */
5850 remote_terminal_ours (struct target_ops *self)
5852 if (!target_async_permitted)
5853 /* Nothing to do. */
5856 /* See FIXME in remote_terminal_inferior. */
5857 if (remote_async_terminal_ours_p)
5859 async_cleanup_sigint_signal_handler (NULL);
5860 add_file_handler (input_fd, stdin_event_handler, 0);
5861 remote_async_terminal_ours_p = 1;
5865 remote_console_output (char *msg)
5869 for (p = msg; p[0] && p[1]; p += 2)
5872 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5876 fputs_unfiltered (tb, gdb_stdtarg);
5878 gdb_flush (gdb_stdtarg);
5881 typedef struct cached_reg
5884 gdb_byte data[MAX_REGISTER_SIZE];
5887 DEF_VEC_O(cached_reg_t);
5889 typedef struct stop_reply
5891 struct notif_event base;
5893 /* The identifier of the thread about this event */
5896 /* The remote state this event is associated with. When the remote
5897 connection, represented by a remote_state object, is closed,
5898 all the associated stop_reply events should be released. */
5899 struct remote_state *rs;
5901 struct target_waitstatus ws;
5903 /* Expedited registers. This makes remote debugging a bit more
5904 efficient for those targets that provide critical registers as
5905 part of their normal status mechanism (as another roundtrip to
5906 fetch them is avoided). */
5907 VEC(cached_reg_t) *regcache;
5909 enum target_stop_reason stop_reason;
5911 CORE_ADDR watch_data_address;
5916 DECLARE_QUEUE_P (stop_reply_p);
5917 DEFINE_QUEUE_P (stop_reply_p);
5918 /* The list of already fetched and acknowledged stop events. This
5919 queue is used for notification Stop, and other notifications
5920 don't need queue for their events, because the notification events
5921 of Stop can't be consumed immediately, so that events should be
5922 queued first, and be consumed by remote_wait_{ns,as} one per
5923 time. Other notifications can consume their events immediately,
5924 so queue is not needed for them. */
5925 static QUEUE (stop_reply_p) *stop_reply_queue;
5928 stop_reply_xfree (struct stop_reply *r)
5930 notif_event_xfree ((struct notif_event *) r);
5933 /* Return the length of the stop reply queue. */
5936 stop_reply_queue_length (void)
5938 return QUEUE_length (stop_reply_p, stop_reply_queue);
5942 remote_notif_stop_parse (struct notif_client *self, char *buf,
5943 struct notif_event *event)
5945 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5949 remote_notif_stop_ack (struct notif_client *self, char *buf,
5950 struct notif_event *event)
5952 struct stop_reply *stop_reply = (struct stop_reply *) event;
5955 putpkt ((char *) self->ack_command);
5957 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5958 /* We got an unknown stop reply. */
5959 error (_("Unknown stop reply"));
5961 push_stop_reply (stop_reply);
5965 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5967 /* We can't get pending events in remote_notif_process for
5968 notification stop, and we have to do this in remote_wait_ns
5969 instead. If we fetch all queued events from stub, remote stub
5970 may exit and we have no chance to process them back in
5972 mark_async_event_handler (remote_async_inferior_event_token);
5977 stop_reply_dtr (struct notif_event *event)
5979 struct stop_reply *r = (struct stop_reply *) event;
5981 VEC_free (cached_reg_t, r->regcache);
5984 static struct notif_event *
5985 remote_notif_stop_alloc_reply (void)
5987 /* We cast to a pointer to the "base class". */
5988 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
5990 r->dtr = stop_reply_dtr;
5995 /* A client of notification Stop. */
5997 struct notif_client notif_client_stop =
6001 remote_notif_stop_parse,
6002 remote_notif_stop_ack,
6003 remote_notif_stop_can_get_pending_events,
6004 remote_notif_stop_alloc_reply,
6008 /* A parameter to pass data in and out. */
6010 struct queue_iter_param
6013 struct stop_reply *output;
6016 /* Determine if THREAD is a pending fork parent thread. ARG contains
6017 the pid of the process that owns the threads we want to check, or
6018 -1 if we want to check all threads. */
6021 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6024 if (ws->kind == TARGET_WAITKIND_FORKED
6025 || ws->kind == TARGET_WAITKIND_VFORKED)
6027 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6034 /* Check whether EVENT is a fork event, and if it is, remove the
6035 fork child from the context list passed in DATA. */
6038 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6039 QUEUE_ITER (stop_reply_p) *iter,
6043 struct queue_iter_param *param = (struct queue_iter_param *) data;
6044 struct threads_listing_context *context
6045 = (struct threads_listing_context *) param->input;
6047 if (event->ws.kind == TARGET_WAITKIND_FORKED
6048 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6050 threads_listing_context_remove (&event->ws, context);
6056 /* If CONTEXT contains any fork child threads that have not been
6057 reported yet, remove them from the CONTEXT list. If such a
6058 thread exists it is because we are stopped at a fork catchpoint
6059 and have not yet called follow_fork, which will set up the
6060 host-side data structures for the new process. */
6063 remove_new_fork_children (struct threads_listing_context *context)
6065 struct thread_info * thread;
6067 struct notif_client *notif = ¬if_client_stop;
6068 struct queue_iter_param param;
6070 /* For any threads stopped at a fork event, remove the corresponding
6071 fork child threads from the CONTEXT list. */
6072 ALL_NON_EXITED_THREADS (thread)
6074 struct target_waitstatus *ws = &thread->pending_follow;
6076 if (is_pending_fork_parent (ws, pid, thread->ptid))
6078 threads_listing_context_remove (ws, context);
6082 /* Check for any pending fork events (not reported or processed yet)
6083 in process PID and remove those fork child threads from the
6084 CONTEXT list as well. */
6085 remote_notif_get_pending_events (notif);
6086 param.input = context;
6087 param.output = NULL;
6088 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6089 remove_child_of_pending_fork, ¶m);
6092 /* Remove stop replies in the queue if its pid is equal to the given
6096 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6097 QUEUE_ITER (stop_reply_p) *iter,
6101 struct queue_iter_param *param = (struct queue_iter_param *) data;
6102 struct inferior *inf = (struct inferior *) param->input;
6104 if (ptid_get_pid (event->ptid) == inf->pid)
6106 stop_reply_xfree (event);
6107 QUEUE_remove_elem (stop_reply_p, q, iter);
6113 /* Discard all pending stop replies of inferior INF. */
6116 discard_pending_stop_replies (struct inferior *inf)
6119 struct queue_iter_param param;
6120 struct stop_reply *reply;
6121 struct remote_state *rs = get_remote_state ();
6122 struct remote_notif_state *rns = rs->notif_state;
6124 /* This function can be notified when an inferior exists. When the
6125 target is not remote, the notification state is NULL. */
6126 if (rs->remote_desc == NULL)
6129 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6131 /* Discard the in-flight notification. */
6132 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6134 stop_reply_xfree (reply);
6135 rns->pending_event[notif_client_stop.id] = NULL;
6139 param.output = NULL;
6140 /* Discard the stop replies we have already pulled with
6142 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6143 remove_stop_reply_for_inferior, ¶m);
6146 /* If its remote state is equal to the given remote state,
6147 remove EVENT from the stop reply queue. */
6150 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6151 QUEUE_ITER (stop_reply_p) *iter,
6155 struct queue_iter_param *param = (struct queue_iter_param *) data;
6156 struct remote_state *rs = (struct remote_state *) param->input;
6158 if (event->rs == rs)
6160 stop_reply_xfree (event);
6161 QUEUE_remove_elem (stop_reply_p, q, iter);
6167 /* Discard the stop replies for RS in stop_reply_queue. */
6170 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6172 struct queue_iter_param param;
6175 param.output = NULL;
6176 /* Discard the stop replies we have already pulled with
6178 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6179 remove_stop_reply_of_remote_state, ¶m);
6182 /* A parameter to pass data in and out. */
6185 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6186 QUEUE_ITER (stop_reply_p) *iter,
6190 struct queue_iter_param *param = (struct queue_iter_param *) data;
6191 ptid_t *ptid = (ptid_t *) param->input;
6193 if (ptid_match (event->ptid, *ptid))
6195 param->output = event;
6196 QUEUE_remove_elem (stop_reply_p, q, iter);
6203 /* Remove the first reply in 'stop_reply_queue' which matches
6206 static struct stop_reply *
6207 remote_notif_remove_queued_reply (ptid_t ptid)
6209 struct queue_iter_param param;
6211 param.input = &ptid;
6212 param.output = NULL;
6214 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6215 remote_notif_remove_once_on_match, ¶m);
6217 fprintf_unfiltered (gdb_stdlog,
6218 "notif: discard queued event: 'Stop' in %s\n",
6219 target_pid_to_str (ptid));
6221 return param.output;
6224 /* Look for a queued stop reply belonging to PTID. If one is found,
6225 remove it from the queue, and return it. Returns NULL if none is
6226 found. If there are still queued events left to process, tell the
6227 event loop to get back to target_wait soon. */
6229 static struct stop_reply *
6230 queued_stop_reply (ptid_t ptid)
6232 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6234 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6235 /* There's still at least an event left. */
6236 mark_async_event_handler (remote_async_inferior_event_token);
6241 /* Push a fully parsed stop reply in the stop reply queue. Since we
6242 know that we now have at least one queued event left to pass to the
6243 core side, tell the event loop to get back to target_wait soon. */
6246 push_stop_reply (struct stop_reply *new_event)
6248 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6251 fprintf_unfiltered (gdb_stdlog,
6252 "notif: push 'Stop' %s to queue %d\n",
6253 target_pid_to_str (new_event->ptid),
6254 QUEUE_length (stop_reply_p,
6257 mark_async_event_handler (remote_async_inferior_event_token);
6261 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6262 QUEUE_ITER (stop_reply_p) *iter,
6263 struct stop_reply *event,
6266 ptid_t *ptid = (ptid_t *) data;
6268 return !(ptid_equal (*ptid, event->ptid)
6269 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6272 /* Returns true if we have a stop reply for PTID. */
6275 peek_stop_reply (ptid_t ptid)
6277 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6278 stop_reply_match_ptid_and_ws, &ptid);
6281 /* Skip PACKET until the next semi-colon (or end of string). */
6284 skip_to_semicolon (char *p)
6286 while (*p != '\0' && *p != ';')
6291 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6292 starting with P and ending with PEND matches PREFIX. */
6295 strprefix (const char *p, const char *pend, const char *prefix)
6297 for ( ; p < pend; p++, prefix++)
6300 return *prefix == '\0';
6303 /* Parse the stop reply in BUF. Either the function succeeds, and the
6304 result is stored in EVENT, or throws an error. */
6307 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6309 struct remote_arch_state *rsa = get_remote_arch_state ();
6314 event->ptid = null_ptid;
6315 event->rs = get_remote_state ();
6316 event->ws.kind = TARGET_WAITKIND_IGNORE;
6317 event->ws.value.integer = 0;
6318 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6319 event->regcache = NULL;
6324 case 'T': /* Status with PC, SP, FP, ... */
6325 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6326 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6328 n... = register number
6329 r... = register contents
6332 p = &buf[3]; /* after Txx */
6338 p1 = strchr (p, ':');
6340 error (_("Malformed packet(a) (missing colon): %s\n\
6344 error (_("Malformed packet(a) (missing register number): %s\n\
6348 /* Some "registers" are actually extended stop information.
6349 Note if you're adding a new entry here: GDB 7.9 and
6350 earlier assume that all register "numbers" that start
6351 with an hex digit are real register numbers. Make sure
6352 the server only sends such a packet if it knows the
6353 client understands it. */
6355 if (strprefix (p, p1, "thread"))
6356 event->ptid = read_ptid (++p1, &p);
6357 else if (strprefix (p, p1, "watch")
6358 || strprefix (p, p1, "rwatch")
6359 || strprefix (p, p1, "awatch"))
6361 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6362 p = unpack_varlen_hex (++p1, &addr);
6363 event->watch_data_address = (CORE_ADDR) addr;
6365 else if (strprefix (p, p1, "swbreak"))
6367 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6369 /* Make sure the stub doesn't forget to indicate support
6371 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6372 error (_("Unexpected swbreak stop reason"));
6374 /* The value part is documented as "must be empty",
6375 though we ignore it, in case we ever decide to make
6376 use of it in a backward compatible way. */
6377 p = skip_to_semicolon (p1 + 1);
6379 else if (strprefix (p, p1, "hwbreak"))
6381 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6383 /* Make sure the stub doesn't forget to indicate support
6385 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6386 error (_("Unexpected hwbreak stop reason"));
6389 p = skip_to_semicolon (p1 + 1);
6391 else if (strprefix (p, p1, "library"))
6393 event->ws.kind = TARGET_WAITKIND_LOADED;
6394 p = skip_to_semicolon (p1 + 1);
6396 else if (strprefix (p, p1, "replaylog"))
6398 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6399 /* p1 will indicate "begin" or "end", but it makes
6400 no difference for now, so ignore it. */
6401 p = skip_to_semicolon (p1 + 1);
6403 else if (strprefix (p, p1, "core"))
6407 p = unpack_varlen_hex (++p1, &c);
6410 else if (strprefix (p, p1, "fork"))
6412 event->ws.value.related_pid = read_ptid (++p1, &p);
6413 event->ws.kind = TARGET_WAITKIND_FORKED;
6415 else if (strprefix (p, p1, "vfork"))
6417 event->ws.value.related_pid = read_ptid (++p1, &p);
6418 event->ws.kind = TARGET_WAITKIND_VFORKED;
6420 else if (strprefix (p, p1, "vforkdone"))
6422 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6423 p = skip_to_semicolon (p1 + 1);
6425 else if (strprefix (p, p1, "exec"))
6428 char pathname[PATH_MAX];
6431 /* Determine the length of the execd pathname. */
6432 p = unpack_varlen_hex (++p1, &ignored);
6433 pathlen = (p - p1) / 2;
6435 /* Save the pathname for event reporting and for
6436 the next run command. */
6437 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6438 pathname[pathlen] = '\0';
6440 /* This is freed during event handling. */
6441 event->ws.value.execd_pathname = xstrdup (pathname);
6442 event->ws.kind = TARGET_WAITKIND_EXECD;
6444 /* Skip the registers included in this packet, since
6445 they may be for an architecture different from the
6446 one used by the original program. */
6456 p = skip_to_semicolon (p1 + 1);
6461 /* Maybe a real ``P'' register number. */
6462 p_temp = unpack_varlen_hex (p, &pnum);
6463 /* If the first invalid character is the colon, we got a
6464 register number. Otherwise, it's an unknown stop
6468 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6469 cached_reg_t cached_reg;
6472 error (_("Remote sent bad register number %s: %s\n\
6474 hex_string (pnum), p, buf);
6476 cached_reg.num = reg->regnum;
6479 fieldsize = hex2bin (p, cached_reg.data,
6480 register_size (target_gdbarch (),
6483 if (fieldsize < register_size (target_gdbarch (),
6485 warning (_("Remote reply is too short: %s"), buf);
6487 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6491 /* Not a number. Silently skip unknown optional
6493 p = skip_to_semicolon (p1 + 1);
6498 error (_("Remote register badly formatted: %s\nhere: %s"),
6503 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6507 case 'S': /* Old style status, just signal only. */
6511 event->ws.kind = TARGET_WAITKIND_STOPPED;
6512 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6513 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6514 event->ws.value.sig = (enum gdb_signal) sig;
6516 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6519 case 'W': /* Target exited. */
6526 /* GDB used to accept only 2 hex chars here. Stubs should
6527 only send more if they detect GDB supports multi-process
6529 p = unpack_varlen_hex (&buf[1], &value);
6533 /* The remote process exited. */
6534 event->ws.kind = TARGET_WAITKIND_EXITED;
6535 event->ws.value.integer = value;
6539 /* The remote process exited with a signal. */
6540 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
6541 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6542 event->ws.value.sig = (enum gdb_signal) value;
6544 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6547 /* If no process is specified, assume inferior_ptid. */
6548 pid = ptid_get_pid (inferior_ptid);
6557 else if (startswith (p, "process:"))
6561 p += sizeof ("process:") - 1;
6562 unpack_varlen_hex (p, &upid);
6566 error (_("unknown stop reply packet: %s"), buf);
6569 error (_("unknown stop reply packet: %s"), buf);
6570 event->ptid = pid_to_ptid (pid);
6575 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
6576 error (_("No process or thread specified in stop reply: %s"), buf);
6579 /* When the stub wants to tell GDB about a new notification reply, it
6580 sends a notification (%Stop, for example). Those can come it at
6581 any time, hence, we have to make sure that any pending
6582 putpkt/getpkt sequence we're making is finished, before querying
6583 the stub for more events with the corresponding ack command
6584 (vStopped, for example). E.g., if we started a vStopped sequence
6585 immediately upon receiving the notification, something like this
6593 1.6) <-- (registers reply to step #1.3)
6595 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6598 To solve this, whenever we parse a %Stop notification successfully,
6599 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6600 doing whatever we were doing:
6606 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6607 2.5) <-- (registers reply to step #2.3)
6609 Eventualy after step #2.5, we return to the event loop, which
6610 notices there's an event on the
6611 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6612 associated callback --- the function below. At this point, we're
6613 always safe to start a vStopped sequence. :
6616 2.7) <-- T05 thread:2
6622 remote_notif_get_pending_events (struct notif_client *nc)
6624 struct remote_state *rs = get_remote_state ();
6626 if (rs->notif_state->pending_event[nc->id] != NULL)
6629 fprintf_unfiltered (gdb_stdlog,
6630 "notif: process: '%s' ack pending event\n",
6634 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6635 rs->notif_state->pending_event[nc->id] = NULL;
6639 getpkt (&rs->buf, &rs->buf_size, 0);
6640 if (strcmp (rs->buf, "OK") == 0)
6643 remote_notif_ack (nc, rs->buf);
6649 fprintf_unfiltered (gdb_stdlog,
6650 "notif: process: '%s' no pending reply\n",
6655 /* Called when it is decided that STOP_REPLY holds the info of the
6656 event that is to be returned to the core. This function always
6657 destroys STOP_REPLY. */
6660 process_stop_reply (struct stop_reply *stop_reply,
6661 struct target_waitstatus *status)
6665 *status = stop_reply->ws;
6666 ptid = stop_reply->ptid;
6668 /* If no thread/process was reported by the stub, assume the current
6670 if (ptid_equal (ptid, null_ptid))
6671 ptid = inferior_ptid;
6673 if (status->kind != TARGET_WAITKIND_EXITED
6674 && status->kind != TARGET_WAITKIND_SIGNALLED)
6676 struct remote_state *rs = get_remote_state ();
6677 struct private_thread_info *remote_thr;
6679 /* Expedited registers. */
6680 if (stop_reply->regcache)
6682 struct regcache *regcache
6683 = get_thread_arch_regcache (ptid, target_gdbarch ());
6688 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6690 regcache_raw_supply (regcache, reg->num, reg->data);
6691 VEC_free (cached_reg_t, stop_reply->regcache);
6694 remote_notice_new_inferior (ptid, 0);
6695 remote_thr = demand_private_info (ptid);
6696 remote_thr->core = stop_reply->core;
6697 remote_thr->stop_reason = stop_reply->stop_reason;
6698 remote_thr->watch_data_address = stop_reply->watch_data_address;
6701 stop_reply_xfree (stop_reply);
6705 /* The non-stop mode version of target_wait. */
6708 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6710 struct remote_state *rs = get_remote_state ();
6711 struct stop_reply *stop_reply;
6715 /* If in non-stop mode, get out of getpkt even if a
6716 notification is received. */
6718 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6719 0 /* forever */, &is_notif);
6722 if (ret != -1 && !is_notif)
6725 case 'E': /* Error of some sort. */
6726 /* We're out of sync with the target now. Did it continue
6727 or not? We can't tell which thread it was in non-stop,
6728 so just ignore this. */
6729 warning (_("Remote failure reply: %s"), rs->buf);
6731 case 'O': /* Console output. */
6732 remote_console_output (rs->buf + 1);
6735 warning (_("Invalid remote reply: %s"), rs->buf);
6739 /* Acknowledge a pending stop reply that may have arrived in the
6741 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6742 remote_notif_get_pending_events (¬if_client_stop);
6744 /* If indeed we noticed a stop reply, we're done. */
6745 stop_reply = queued_stop_reply (ptid);
6746 if (stop_reply != NULL)
6747 return process_stop_reply (stop_reply, status);
6749 /* Still no event. If we're just polling for an event, then
6750 return to the event loop. */
6751 if (options & TARGET_WNOHANG)
6753 status->kind = TARGET_WAITKIND_IGNORE;
6754 return minus_one_ptid;
6757 /* Otherwise do a blocking wait. */
6758 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6759 1 /* forever */, &is_notif);
6763 /* Wait until the remote machine stops, then return, storing status in
6764 STATUS just as `wait' would. */
6767 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6769 struct remote_state *rs = get_remote_state ();
6770 ptid_t event_ptid = null_ptid;
6772 struct stop_reply *stop_reply;
6776 status->kind = TARGET_WAITKIND_IGNORE;
6777 status->value.integer = 0;
6779 stop_reply = queued_stop_reply (ptid);
6780 if (stop_reply != NULL)
6781 return process_stop_reply (stop_reply, status);
6783 if (rs->cached_wait_status)
6784 /* Use the cached wait status, but only once. */
6785 rs->cached_wait_status = 0;
6790 int forever = ((options & TARGET_WNOHANG) == 0
6791 && wait_forever_enabled_p);
6793 if (!rs->waiting_for_stop_reply)
6795 status->kind = TARGET_WAITKIND_NO_RESUMED;
6796 return minus_one_ptid;
6799 if (!target_is_async_p ())
6801 ofunc = signal (SIGINT, sync_remote_interrupt);
6802 /* If the user hit C-c before this packet, or between packets,
6803 pretend that it was hit right here. */
6804 if (check_quit_flag ())
6807 sync_remote_interrupt (SIGINT);
6811 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6812 _never_ wait for ever -> test on target_is_async_p().
6813 However, before we do that we need to ensure that the caller
6814 knows how to take the target into/out of async mode. */
6815 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6816 forever, &is_notif);
6818 if (!target_is_async_p ())
6819 signal (SIGINT, ofunc);
6821 /* GDB gets a notification. Return to core as this event is
6823 if (ret != -1 && is_notif)
6824 return minus_one_ptid;
6826 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6827 return minus_one_ptid;
6832 /* Assume that the target has acknowledged Ctrl-C unless we receive
6833 an 'F' or 'O' packet. */
6834 if (buf[0] != 'F' && buf[0] != 'O')
6835 rs->ctrlc_pending_p = 0;
6839 case 'E': /* Error of some sort. */
6840 /* We're out of sync with the target now. Did it continue or
6841 not? Not is more likely, so report a stop. */
6842 rs->waiting_for_stop_reply = 0;
6844 warning (_("Remote failure reply: %s"), buf);
6845 status->kind = TARGET_WAITKIND_STOPPED;
6846 status->value.sig = GDB_SIGNAL_0;
6848 case 'F': /* File-I/O request. */
6849 remote_fileio_request (buf, rs->ctrlc_pending_p);
6850 rs->ctrlc_pending_p = 0;
6852 case 'T': case 'S': case 'X': case 'W':
6854 struct stop_reply *stop_reply;
6856 /* There is a stop reply to handle. */
6857 rs->waiting_for_stop_reply = 0;
6860 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6863 event_ptid = process_stop_reply (stop_reply, status);
6866 case 'O': /* Console output. */
6867 remote_console_output (buf + 1);
6870 if (rs->last_sent_signal != GDB_SIGNAL_0)
6872 /* Zero length reply means that we tried 'S' or 'C' and the
6873 remote system doesn't support it. */
6874 target_terminal_ours_for_output ();
6876 ("Can't send signals to this remote system. %s not sent.\n",
6877 gdb_signal_to_name (rs->last_sent_signal));
6878 rs->last_sent_signal = GDB_SIGNAL_0;
6879 target_terminal_inferior ();
6881 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6882 putpkt ((char *) buf);
6885 /* else fallthrough */
6887 warning (_("Invalid remote reply: %s"), buf);
6891 if (status->kind == TARGET_WAITKIND_IGNORE)
6893 /* Nothing interesting happened. If we're doing a non-blocking
6894 poll, we're done. Otherwise, go back to waiting. */
6895 if (options & TARGET_WNOHANG)
6896 return minus_one_ptid;
6900 else if (status->kind != TARGET_WAITKIND_EXITED
6901 && status->kind != TARGET_WAITKIND_SIGNALLED)
6903 if (!ptid_equal (event_ptid, null_ptid))
6904 record_currthread (rs, event_ptid);
6906 event_ptid = inferior_ptid;
6909 /* A process exit. Invalidate our notion of current thread. */
6910 record_currthread (rs, minus_one_ptid);
6915 /* Wait until the remote machine stops, then return, storing status in
6916 STATUS just as `wait' would. */
6919 remote_wait (struct target_ops *ops,
6920 ptid_t ptid, struct target_waitstatus *status, int options)
6924 if (target_is_non_stop_p ())
6925 event_ptid = remote_wait_ns (ptid, status, options);
6927 event_ptid = remote_wait_as (ptid, status, options);
6929 if (target_is_async_p ())
6931 /* If there are are events left in the queue tell the event loop
6933 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6934 mark_async_event_handler (remote_async_inferior_event_token);
6940 /* Fetch a single register using a 'p' packet. */
6943 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6945 struct remote_state *rs = get_remote_state ();
6947 char regp[MAX_REGISTER_SIZE];
6950 if (packet_support (PACKET_p) == PACKET_DISABLE)
6953 if (reg->pnum == -1)
6958 p += hexnumstr (p, reg->pnum);
6961 getpkt (&rs->buf, &rs->buf_size, 0);
6965 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6969 case PACKET_UNKNOWN:
6972 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6973 gdbarch_register_name (get_regcache_arch (regcache),
6978 /* If this register is unfetchable, tell the regcache. */
6981 regcache_raw_supply (regcache, reg->regnum, NULL);
6985 /* Otherwise, parse and supply the value. */
6991 error (_("fetch_register_using_p: early buf termination"));
6993 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6996 regcache_raw_supply (regcache, reg->regnum, regp);
7000 /* Fetch the registers included in the target's 'g' packet. */
7003 send_g_packet (void)
7005 struct remote_state *rs = get_remote_state ();
7008 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7009 remote_send (&rs->buf, &rs->buf_size);
7011 /* We can get out of synch in various cases. If the first character
7012 in the buffer is not a hex character, assume that has happened
7013 and try to fetch another packet to read. */
7014 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7015 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7016 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7017 && rs->buf[0] != 'x') /* New: unavailable register value. */
7020 fprintf_unfiltered (gdb_stdlog,
7021 "Bad register packet; fetching a new packet\n");
7022 getpkt (&rs->buf, &rs->buf_size, 0);
7025 buf_len = strlen (rs->buf);
7027 /* Sanity check the received packet. */
7028 if (buf_len % 2 != 0)
7029 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7035 process_g_packet (struct regcache *regcache)
7037 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7038 struct remote_state *rs = get_remote_state ();
7039 struct remote_arch_state *rsa = get_remote_arch_state ();
7044 buf_len = strlen (rs->buf);
7046 /* Further sanity checks, with knowledge of the architecture. */
7047 if (buf_len > 2 * rsa->sizeof_g_packet)
7048 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7050 /* Save the size of the packet sent to us by the target. It is used
7051 as a heuristic when determining the max size of packets that the
7052 target can safely receive. */
7053 if (rsa->actual_register_packet_size == 0)
7054 rsa->actual_register_packet_size = buf_len;
7056 /* If this is smaller than we guessed the 'g' packet would be,
7057 update our records. A 'g' reply that doesn't include a register's
7058 value implies either that the register is not available, or that
7059 the 'p' packet must be used. */
7060 if (buf_len < 2 * rsa->sizeof_g_packet)
7062 rsa->sizeof_g_packet = buf_len / 2;
7064 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7066 if (rsa->regs[i].pnum == -1)
7069 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7070 rsa->regs[i].in_g_packet = 0;
7072 rsa->regs[i].in_g_packet = 1;
7076 regs = (char *) alloca (rsa->sizeof_g_packet);
7078 /* Unimplemented registers read as all bits zero. */
7079 memset (regs, 0, rsa->sizeof_g_packet);
7081 /* Reply describes registers byte by byte, each byte encoded as two
7082 hex characters. Suck them all up, then supply them to the
7083 register cacheing/storage mechanism. */
7086 for (i = 0; i < rsa->sizeof_g_packet; i++)
7088 if (p[0] == 0 || p[1] == 0)
7089 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7090 internal_error (__FILE__, __LINE__,
7091 _("unexpected end of 'g' packet reply"));
7093 if (p[0] == 'x' && p[1] == 'x')
7094 regs[i] = 0; /* 'x' */
7096 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7100 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7102 struct packet_reg *r = &rsa->regs[i];
7106 if (r->offset * 2 >= strlen (rs->buf))
7107 /* This shouldn't happen - we adjusted in_g_packet above. */
7108 internal_error (__FILE__, __LINE__,
7109 _("unexpected end of 'g' packet reply"));
7110 else if (rs->buf[r->offset * 2] == 'x')
7112 gdb_assert (r->offset * 2 < strlen (rs->buf));
7113 /* The register isn't available, mark it as such (at
7114 the same time setting the value to zero). */
7115 regcache_raw_supply (regcache, r->regnum, NULL);
7118 regcache_raw_supply (regcache, r->regnum,
7125 fetch_registers_using_g (struct regcache *regcache)
7128 process_g_packet (regcache);
7131 /* Make the remote selected traceframe match GDB's selected
7135 set_remote_traceframe (void)
7138 struct remote_state *rs = get_remote_state ();
7140 if (rs->remote_traceframe_number == get_traceframe_number ())
7143 /* Avoid recursion, remote_trace_find calls us again. */
7144 rs->remote_traceframe_number = get_traceframe_number ();
7146 newnum = target_trace_find (tfind_number,
7147 get_traceframe_number (), 0, 0, NULL);
7149 /* Should not happen. If it does, all bets are off. */
7150 if (newnum != get_traceframe_number ())
7151 warning (_("could not set remote traceframe"));
7155 remote_fetch_registers (struct target_ops *ops,
7156 struct regcache *regcache, int regnum)
7158 struct remote_arch_state *rsa = get_remote_arch_state ();
7161 set_remote_traceframe ();
7162 set_general_thread (inferior_ptid);
7166 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7168 gdb_assert (reg != NULL);
7170 /* If this register might be in the 'g' packet, try that first -
7171 we are likely to read more than one register. If this is the
7172 first 'g' packet, we might be overly optimistic about its
7173 contents, so fall back to 'p'. */
7174 if (reg->in_g_packet)
7176 fetch_registers_using_g (regcache);
7177 if (reg->in_g_packet)
7181 if (fetch_register_using_p (regcache, reg))
7184 /* This register is not available. */
7185 regcache_raw_supply (regcache, reg->regnum, NULL);
7190 fetch_registers_using_g (regcache);
7192 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7193 if (!rsa->regs[i].in_g_packet)
7194 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7196 /* This register is not available. */
7197 regcache_raw_supply (regcache, i, NULL);
7201 /* Prepare to store registers. Since we may send them all (using a
7202 'G' request), we have to read out the ones we don't want to change
7206 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7208 struct remote_arch_state *rsa = get_remote_arch_state ();
7210 gdb_byte buf[MAX_REGISTER_SIZE];
7212 /* Make sure the entire registers array is valid. */
7213 switch (packet_support (PACKET_P))
7215 case PACKET_DISABLE:
7216 case PACKET_SUPPORT_UNKNOWN:
7217 /* Make sure all the necessary registers are cached. */
7218 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7219 if (rsa->regs[i].in_g_packet)
7220 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
7227 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7228 packet was not recognized. */
7231 store_register_using_P (const struct regcache *regcache,
7232 struct packet_reg *reg)
7234 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7235 struct remote_state *rs = get_remote_state ();
7236 /* Try storing a single register. */
7237 char *buf = rs->buf;
7238 gdb_byte regp[MAX_REGISTER_SIZE];
7241 if (packet_support (PACKET_P) == PACKET_DISABLE)
7244 if (reg->pnum == -1)
7247 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7248 p = buf + strlen (buf);
7249 regcache_raw_collect (regcache, reg->regnum, regp);
7250 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7252 getpkt (&rs->buf, &rs->buf_size, 0);
7254 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7259 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7260 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7261 case PACKET_UNKNOWN:
7264 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7268 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7269 contents of the register cache buffer. FIXME: ignores errors. */
7272 store_registers_using_G (const struct regcache *regcache)
7274 struct remote_state *rs = get_remote_state ();
7275 struct remote_arch_state *rsa = get_remote_arch_state ();
7279 /* Extract all the registers in the regcache copying them into a
7284 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7285 memset (regs, 0, rsa->sizeof_g_packet);
7286 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7288 struct packet_reg *r = &rsa->regs[i];
7291 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7295 /* Command describes registers byte by byte,
7296 each byte encoded as two hex characters. */
7299 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7301 bin2hex (regs, p, rsa->sizeof_g_packet);
7303 getpkt (&rs->buf, &rs->buf_size, 0);
7304 if (packet_check_result (rs->buf) == PACKET_ERROR)
7305 error (_("Could not write registers; remote failure reply '%s'"),
7309 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7310 of the register cache buffer. FIXME: ignores errors. */
7313 remote_store_registers (struct target_ops *ops,
7314 struct regcache *regcache, int regnum)
7316 struct remote_arch_state *rsa = get_remote_arch_state ();
7319 set_remote_traceframe ();
7320 set_general_thread (inferior_ptid);
7324 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7326 gdb_assert (reg != NULL);
7328 /* Always prefer to store registers using the 'P' packet if
7329 possible; we often change only a small number of registers.
7330 Sometimes we change a larger number; we'd need help from a
7331 higher layer to know to use 'G'. */
7332 if (store_register_using_P (regcache, reg))
7335 /* For now, don't complain if we have no way to write the
7336 register. GDB loses track of unavailable registers too
7337 easily. Some day, this may be an error. We don't have
7338 any way to read the register, either... */
7339 if (!reg->in_g_packet)
7342 store_registers_using_G (regcache);
7346 store_registers_using_G (regcache);
7348 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7349 if (!rsa->regs[i].in_g_packet)
7350 if (!store_register_using_P (regcache, &rsa->regs[i]))
7351 /* See above for why we do not issue an error here. */
7356 /* Return the number of hex digits in num. */
7359 hexnumlen (ULONGEST num)
7363 for (i = 0; num != 0; i++)
7369 /* Set BUF to the minimum number of hex digits representing NUM. */
7372 hexnumstr (char *buf, ULONGEST num)
7374 int len = hexnumlen (num);
7376 return hexnumnstr (buf, num, len);
7380 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7383 hexnumnstr (char *buf, ULONGEST num, int width)
7389 for (i = width - 1; i >= 0; i--)
7391 buf[i] = "0123456789abcdef"[(num & 0xf)];
7398 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7401 remote_address_masked (CORE_ADDR addr)
7403 unsigned int address_size = remote_address_size;
7405 /* If "remoteaddresssize" was not set, default to target address size. */
7407 address_size = gdbarch_addr_bit (target_gdbarch ());
7409 if (address_size > 0
7410 && address_size < (sizeof (ULONGEST) * 8))
7412 /* Only create a mask when that mask can safely be constructed
7413 in a ULONGEST variable. */
7416 mask = (mask << address_size) - 1;
7422 /* Determine whether the remote target supports binary downloading.
7423 This is accomplished by sending a no-op memory write of zero length
7424 to the target at the specified address. It does not suffice to send
7425 the whole packet, since many stubs strip the eighth bit and
7426 subsequently compute a wrong checksum, which causes real havoc with
7429 NOTE: This can still lose if the serial line is not eight-bit
7430 clean. In cases like this, the user should clear "remote
7434 check_binary_download (CORE_ADDR addr)
7436 struct remote_state *rs = get_remote_state ();
7438 switch (packet_support (PACKET_X))
7440 case PACKET_DISABLE:
7444 case PACKET_SUPPORT_UNKNOWN:
7450 p += hexnumstr (p, (ULONGEST) addr);
7452 p += hexnumstr (p, (ULONGEST) 0);
7456 putpkt_binary (rs->buf, (int) (p - rs->buf));
7457 getpkt (&rs->buf, &rs->buf_size, 0);
7459 if (rs->buf[0] == '\0')
7462 fprintf_unfiltered (gdb_stdlog,
7463 "binary downloading NOT "
7464 "supported by target\n");
7465 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
7470 fprintf_unfiltered (gdb_stdlog,
7471 "binary downloading supported by target\n");
7472 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
7479 /* Helper function to resize the payload in order to try to get a good
7480 alignment. We try to write an amount of data such that the next write will
7481 start on an address aligned on REMOTE_ALIGN_WRITES. */
7484 align_for_efficient_write (int todo, CORE_ADDR memaddr)
7486 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7489 /* Write memory data directly to the remote machine.
7490 This does not inform the data cache; the data cache uses this.
7491 HEADER is the starting part of the packet.
7492 MEMADDR is the address in the remote memory space.
7493 MYADDR is the address of the buffer in our space.
7494 LEN_UNITS is the number of addressable units to write.
7495 UNIT_SIZE is the length in bytes of an addressable unit.
7496 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7497 should send data as binary ('X'), or hex-encoded ('M').
7499 The function creates packet of the form
7500 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7502 where encoding of <DATA> is terminated by PACKET_FORMAT.
7504 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7507 Return the transferred status, error or OK (an
7508 'enum target_xfer_status' value). Save the number of addressable units
7509 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7511 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7512 exchange between gdb and the stub could look like (?? in place of the
7518 -> $M1000,3:eeeeffffeeee#??
7522 <- eeeeffffeeeedddd */
7524 static enum target_xfer_status
7525 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
7526 const gdb_byte *myaddr, ULONGEST len_units,
7527 int unit_size, ULONGEST *xfered_len_units,
7528 char packet_format, int use_length)
7530 struct remote_state *rs = get_remote_state ();
7536 int payload_capacity_bytes;
7537 int payload_length_bytes;
7539 if (packet_format != 'X' && packet_format != 'M')
7540 internal_error (__FILE__, __LINE__,
7541 _("remote_write_bytes_aux: bad packet format"));
7544 return TARGET_XFER_EOF;
7546 payload_capacity_bytes = get_memory_write_packet_size ();
7548 /* The packet buffer will be large enough for the payload;
7549 get_memory_packet_size ensures this. */
7552 /* Compute the size of the actual payload by subtracting out the
7553 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7555 payload_capacity_bytes -= strlen ("$,:#NN");
7557 /* The comma won't be used. */
7558 payload_capacity_bytes += 1;
7559 payload_capacity_bytes -= strlen (header);
7560 payload_capacity_bytes -= hexnumlen (memaddr);
7562 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
7564 strcat (rs->buf, header);
7565 p = rs->buf + strlen (header);
7567 /* Compute a best guess of the number of bytes actually transfered. */
7568 if (packet_format == 'X')
7570 /* Best guess at number of bytes that will fit. */
7571 todo_units = min (len_units, payload_capacity_bytes / unit_size);
7573 payload_capacity_bytes -= hexnumlen (todo_units);
7574 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
7578 /* Number of bytes that will fit. */
7579 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
7581 payload_capacity_bytes -= hexnumlen (todo_units);
7582 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
7585 if (todo_units <= 0)
7586 internal_error (__FILE__, __LINE__,
7587 _("minimum packet size too small to write data"));
7589 /* If we already need another packet, then try to align the end
7590 of this packet to a useful boundary. */
7591 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7592 todo_units = align_for_efficient_write (todo_units, memaddr);
7594 /* Append "<memaddr>". */
7595 memaddr = remote_address_masked (memaddr);
7596 p += hexnumstr (p, (ULONGEST) memaddr);
7603 /* Append the length and retain its location and size. It may need to be
7604 adjusted once the packet body has been created. */
7606 plenlen = hexnumstr (p, (ULONGEST) todo_units);
7614 /* Append the packet body. */
7615 if (packet_format == 'X')
7617 /* Binary mode. Send target system values byte by byte, in
7618 increasing byte addresses. Only escape certain critical
7620 payload_length_bytes =
7621 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7622 &units_written, payload_capacity_bytes);
7624 /* If not all TODO units fit, then we'll need another packet. Make
7625 a second try to keep the end of the packet aligned. Don't do
7626 this if the packet is tiny. */
7627 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
7631 new_todo_units = align_for_efficient_write (units_written, memaddr);
7633 if (new_todo_units != units_written)
7634 payload_length_bytes =
7635 remote_escape_output (myaddr, new_todo_units, unit_size,
7636 (gdb_byte *) p, &units_written,
7637 payload_capacity_bytes);
7640 p += payload_length_bytes;
7641 if (use_length && units_written < todo_units)
7643 /* Escape chars have filled up the buffer prematurely,
7644 and we have actually sent fewer units than planned.
7645 Fix-up the length field of the packet. Use the same
7646 number of characters as before. */
7647 plen += hexnumnstr (plen, (ULONGEST) units_written,
7649 *plen = ':'; /* overwrite \0 from hexnumnstr() */
7654 /* Normal mode: Send target system values byte by byte, in
7655 increasing byte addresses. Each byte is encoded as a two hex
7657 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7658 units_written = todo_units;
7661 putpkt_binary (rs->buf, (int) (p - rs->buf));
7662 getpkt (&rs->buf, &rs->buf_size, 0);
7664 if (rs->buf[0] == 'E')
7665 return TARGET_XFER_E_IO;
7667 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7668 send fewer units than we'd planned. */
7669 *xfered_len_units = (ULONGEST) units_written;
7670 return TARGET_XFER_OK;
7673 /* Write memory data directly to the remote machine.
7674 This does not inform the data cache; the data cache uses this.
7675 MEMADDR is the address in the remote memory space.
7676 MYADDR is the address of the buffer in our space.
7677 LEN is the number of bytes.
7679 Return the transferred status, error or OK (an
7680 'enum target_xfer_status' value). Save the number of bytes
7681 transferred in *XFERED_LEN. Only transfer a single packet. */
7683 static enum target_xfer_status
7684 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7685 int unit_size, ULONGEST *xfered_len)
7687 char *packet_format = 0;
7689 /* Check whether the target supports binary download. */
7690 check_binary_download (memaddr);
7692 switch (packet_support (PACKET_X))
7695 packet_format = "X";
7697 case PACKET_DISABLE:
7698 packet_format = "M";
7700 case PACKET_SUPPORT_UNKNOWN:
7701 internal_error (__FILE__, __LINE__,
7702 _("remote_write_bytes: bad internal state"));
7704 internal_error (__FILE__, __LINE__, _("bad switch"));
7707 return remote_write_bytes_aux (packet_format,
7708 memaddr, myaddr, len, unit_size, xfered_len,
7709 packet_format[0], 1);
7712 /* Read memory data directly from the remote machine.
7713 This does not use the data cache; the data cache uses this.
7714 MEMADDR is the address in the remote memory space.
7715 MYADDR is the address of the buffer in our space.
7716 LEN_UNITS is the number of addressable memory units to read..
7717 UNIT_SIZE is the length in bytes of an addressable unit.
7719 Return the transferred status, error or OK (an
7720 'enum target_xfer_status' value). Save the number of bytes
7721 transferred in *XFERED_LEN_UNITS.
7723 See the comment of remote_write_bytes_aux for an example of
7724 memory read/write exchange between gdb and the stub. */
7726 static enum target_xfer_status
7727 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7728 int unit_size, ULONGEST *xfered_len_units)
7730 struct remote_state *rs = get_remote_state ();
7731 int buf_size_bytes; /* Max size of packet output buffer. */
7736 buf_size_bytes = get_memory_read_packet_size ();
7737 /* The packet buffer will be large enough for the payload;
7738 get_memory_packet_size ensures this. */
7740 /* Number of units that will fit. */
7741 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
7743 /* Construct "m"<memaddr>","<len>". */
7744 memaddr = remote_address_masked (memaddr);
7747 p += hexnumstr (p, (ULONGEST) memaddr);
7749 p += hexnumstr (p, (ULONGEST) todo_units);
7752 getpkt (&rs->buf, &rs->buf_size, 0);
7753 if (rs->buf[0] == 'E'
7754 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7755 && rs->buf[3] == '\0')
7756 return TARGET_XFER_E_IO;
7757 /* Reply describes memory byte by byte, each byte encoded as two hex
7760 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
7761 /* Return what we have. Let higher layers handle partial reads. */
7762 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
7763 return TARGET_XFER_OK;
7766 /* Using the set of read-only target sections of remote, read live
7769 For interface/parameters/return description see target.h,
7772 static enum target_xfer_status
7773 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7774 ULONGEST memaddr, ULONGEST len,
7775 int unit_size, ULONGEST *xfered_len)
7777 struct target_section *secp;
7778 struct target_section_table *table;
7780 secp = target_section_by_addr (ops, memaddr);
7782 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7783 secp->the_bfd_section)
7786 struct target_section *p;
7787 ULONGEST memend = memaddr + len;
7789 table = target_get_section_table (ops);
7791 for (p = table->sections; p < table->sections_end; p++)
7793 if (memaddr >= p->addr)
7795 if (memend <= p->endaddr)
7797 /* Entire transfer is within this section. */
7798 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7801 else if (memaddr >= p->endaddr)
7803 /* This section ends before the transfer starts. */
7808 /* This section overlaps the transfer. Just do half. */
7809 len = p->endaddr - memaddr;
7810 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
7817 return TARGET_XFER_EOF;
7820 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7821 first if the requested memory is unavailable in traceframe.
7822 Otherwise, fall back to remote_read_bytes_1. */
7824 static enum target_xfer_status
7825 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7826 gdb_byte *myaddr, ULONGEST len, int unit_size,
7827 ULONGEST *xfered_len)
7830 return TARGET_XFER_EOF;
7832 if (get_traceframe_number () != -1)
7834 VEC(mem_range_s) *available;
7836 /* If we fail to get the set of available memory, then the
7837 target does not support querying traceframe info, and so we
7838 attempt reading from the traceframe anyway (assuming the
7839 target implements the old QTro packet then). */
7840 if (traceframe_available_memory (&available, memaddr, len))
7842 struct cleanup *old_chain;
7844 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7846 if (VEC_empty (mem_range_s, available)
7847 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7849 enum target_xfer_status res;
7851 /* Don't read into the traceframe's available
7853 if (!VEC_empty (mem_range_s, available))
7855 LONGEST oldlen = len;
7857 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7858 gdb_assert (len <= oldlen);
7861 do_cleanups (old_chain);
7863 /* This goes through the topmost target again. */
7864 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7865 len, unit_size, xfered_len);
7866 if (res == TARGET_XFER_OK)
7867 return TARGET_XFER_OK;
7870 /* No use trying further, we know some memory starting
7871 at MEMADDR isn't available. */
7873 return TARGET_XFER_UNAVAILABLE;
7877 /* Don't try to read more than how much is available, in
7878 case the target implements the deprecated QTro packet to
7879 cater for older GDBs (the target's knowledge of read-only
7880 sections may be outdated by now). */
7881 len = VEC_index (mem_range_s, available, 0)->length;
7883 do_cleanups (old_chain);
7887 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
7892 /* Sends a packet with content determined by the printf format string
7893 FORMAT and the remaining arguments, then gets the reply. Returns
7894 whether the packet was a success, a failure, or unknown. */
7896 static enum packet_result remote_send_printf (const char *format, ...)
7897 ATTRIBUTE_PRINTF (1, 2);
7899 static enum packet_result
7900 remote_send_printf (const char *format, ...)
7902 struct remote_state *rs = get_remote_state ();
7903 int max_size = get_remote_packet_size ();
7906 va_start (ap, format);
7909 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7910 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7912 if (putpkt (rs->buf) < 0)
7913 error (_("Communication problem with target."));
7916 getpkt (&rs->buf, &rs->buf_size, 0);
7918 return packet_check_result (rs->buf);
7922 restore_remote_timeout (void *p)
7924 int value = *(int *)p;
7926 remote_timeout = value;
7929 /* Flash writing can take quite some time. We'll set
7930 effectively infinite timeout for flash operations.
7931 In future, we'll need to decide on a better approach. */
7932 static const int remote_flash_timeout = 1000;
7935 remote_flash_erase (struct target_ops *ops,
7936 ULONGEST address, LONGEST length)
7938 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7939 int saved_remote_timeout = remote_timeout;
7940 enum packet_result ret;
7941 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7942 &saved_remote_timeout);
7944 remote_timeout = remote_flash_timeout;
7946 ret = remote_send_printf ("vFlashErase:%s,%s",
7947 phex (address, addr_size),
7951 case PACKET_UNKNOWN:
7952 error (_("Remote target does not support flash erase"));
7954 error (_("Error erasing flash with vFlashErase packet"));
7959 do_cleanups (back_to);
7962 static enum target_xfer_status
7963 remote_flash_write (struct target_ops *ops, ULONGEST address,
7964 ULONGEST length, ULONGEST *xfered_len,
7965 const gdb_byte *data)
7967 int saved_remote_timeout = remote_timeout;
7968 enum target_xfer_status ret;
7969 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7970 &saved_remote_timeout);
7972 remote_timeout = remote_flash_timeout;
7973 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
7975 do_cleanups (back_to);
7981 remote_flash_done (struct target_ops *ops)
7983 int saved_remote_timeout = remote_timeout;
7985 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7986 &saved_remote_timeout);
7988 remote_timeout = remote_flash_timeout;
7989 ret = remote_send_printf ("vFlashDone");
7990 do_cleanups (back_to);
7994 case PACKET_UNKNOWN:
7995 error (_("Remote target does not support vFlashDone"));
7997 error (_("Error finishing flash operation"));
8004 remote_files_info (struct target_ops *ignore)
8006 puts_filtered ("Debugging a target over a serial line.\n");
8009 /* Stuff for dealing with the packets which are part of this protocol.
8010 See comment at top of file for details. */
8012 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8013 error to higher layers. Called when a serial error is detected.
8014 The exception message is STRING, followed by a colon and a blank,
8015 the system error message for errno at function entry and final dot
8016 for output compatibility with throw_perror_with_name. */
8019 unpush_and_perror (const char *string)
8021 int saved_errno = errno;
8023 remote_unpush_target ();
8024 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8025 safe_strerror (saved_errno));
8028 /* Read a single character from the remote end. */
8031 readchar (int timeout)
8034 struct remote_state *rs = get_remote_state ();
8036 ch = serial_readchar (rs->remote_desc, timeout);
8041 switch ((enum serial_rc) ch)
8044 remote_unpush_target ();
8045 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8048 unpush_and_perror (_("Remote communication error. "
8049 "Target disconnected."));
8051 case SERIAL_TIMEOUT:
8057 /* Wrapper for serial_write that closes the target and throws if
8061 remote_serial_write (const char *str, int len)
8063 struct remote_state *rs = get_remote_state ();
8065 if (serial_write (rs->remote_desc, str, len))
8067 unpush_and_perror (_("Remote communication error. "
8068 "Target disconnected."));
8072 /* Send the command in *BUF to the remote machine, and read the reply
8073 into *BUF. Report an error if we get an error reply. Resize
8074 *BUF using xrealloc if necessary to hold the result, and update
8078 remote_send (char **buf,
8082 getpkt (buf, sizeof_buf, 0);
8084 if ((*buf)[0] == 'E')
8085 error (_("Remote failure reply: %s"), *buf);
8088 /* Return a pointer to an xmalloc'ed string representing an escaped
8089 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8090 etc. The caller is responsible for releasing the returned
8094 escape_buffer (const char *buf, int n)
8096 struct cleanup *old_chain;
8097 struct ui_file *stb;
8100 stb = mem_fileopen ();
8101 old_chain = make_cleanup_ui_file_delete (stb);
8103 fputstrn_unfiltered (buf, n, '\\', stb);
8104 str = ui_file_xstrdup (stb, NULL);
8105 do_cleanups (old_chain);
8109 /* Display a null-terminated packet on stdout, for debugging, using C
8113 print_packet (const char *buf)
8115 puts_filtered ("\"");
8116 fputstr_filtered (buf, '"', gdb_stdout);
8117 puts_filtered ("\"");
8121 putpkt (const char *buf)
8123 return putpkt_binary (buf, strlen (buf));
8126 /* Send a packet to the remote machine, with error checking. The data
8127 of the packet is in BUF. The string in BUF can be at most
8128 get_remote_packet_size () - 5 to account for the $, # and checksum,
8129 and for a possible /0 if we are debugging (remote_debug) and want
8130 to print the sent packet as a string. */
8133 putpkt_binary (const char *buf, int cnt)
8135 struct remote_state *rs = get_remote_state ();
8137 unsigned char csum = 0;
8138 char *buf2 = (char *) xmalloc (cnt + 6);
8139 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8146 /* Catch cases like trying to read memory or listing threads while
8147 we're waiting for a stop reply. The remote server wouldn't be
8148 ready to handle this request, so we'd hang and timeout. We don't
8149 have to worry about this in synchronous mode, because in that
8150 case it's not possible to issue a command while the target is
8151 running. This is not a problem in non-stop mode, because in that
8152 case, the stub is always ready to process serial input. */
8153 if (!target_is_non_stop_p ()
8154 && target_is_async_p ()
8155 && rs->waiting_for_stop_reply)
8157 error (_("Cannot execute this command while the target is running.\n"
8158 "Use the \"interrupt\" command to stop the target\n"
8159 "and then try again."));
8162 /* We're sending out a new packet. Make sure we don't look at a
8163 stale cached response. */
8164 rs->cached_wait_status = 0;
8166 /* Copy the packet into buffer BUF2, encapsulating it
8167 and giving it a checksum. */
8172 for (i = 0; i < cnt; i++)
8178 *p++ = tohex ((csum >> 4) & 0xf);
8179 *p++ = tohex (csum & 0xf);
8181 /* Send it over and over until we get a positive ack. */
8185 int started_error_output = 0;
8189 struct cleanup *old_chain;
8193 str = escape_buffer (buf2, p - buf2);
8194 old_chain = make_cleanup (xfree, str);
8195 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
8196 gdb_flush (gdb_stdlog);
8197 do_cleanups (old_chain);
8199 remote_serial_write (buf2, p - buf2);
8201 /* If this is a no acks version of the remote protocol, send the
8202 packet and move on. */
8206 /* Read until either a timeout occurs (-2) or '+' is read.
8207 Handle any notification that arrives in the mean time. */
8210 ch = readchar (remote_timeout);
8218 case SERIAL_TIMEOUT:
8221 if (started_error_output)
8223 putchar_unfiltered ('\n');
8224 started_error_output = 0;
8233 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8234 do_cleanups (old_chain);
8238 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8240 case SERIAL_TIMEOUT:
8244 do_cleanups (old_chain);
8247 break; /* Retransmit buffer. */
8251 fprintf_unfiltered (gdb_stdlog,
8252 "Packet instead of Ack, ignoring it\n");
8253 /* It's probably an old response sent because an ACK
8254 was lost. Gobble up the packet and ack it so it
8255 doesn't get retransmitted when we resend this
8258 remote_serial_write ("+", 1);
8259 continue; /* Now, go look for +. */
8266 /* If we got a notification, handle it, and go back to looking
8268 /* We've found the start of a notification. Now
8269 collect the data. */
8270 val = read_frame (&rs->buf, &rs->buf_size);
8275 struct cleanup *old_chain;
8278 str = escape_buffer (rs->buf, val);
8279 old_chain = make_cleanup (xfree, str);
8280 fprintf_unfiltered (gdb_stdlog,
8281 " Notification received: %s\n",
8283 do_cleanups (old_chain);
8285 handle_notification (rs->notif_state, rs->buf);
8286 /* We're in sync now, rewait for the ack. */
8293 if (!started_error_output)
8295 started_error_output = 1;
8296 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8298 fputc_unfiltered (ch & 0177, gdb_stdlog);
8299 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8308 if (!started_error_output)
8310 started_error_output = 1;
8311 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8313 fputc_unfiltered (ch & 0177, gdb_stdlog);
8317 break; /* Here to retransmit. */
8321 /* This is wrong. If doing a long backtrace, the user should be
8322 able to get out next time we call QUIT, without anything as
8323 violent as interrupt_query. If we want to provide a way out of
8324 here without getting to the next QUIT, it should be based on
8325 hitting ^C twice as in remote_wait. */
8334 do_cleanups (old_chain);
8338 /* Come here after finding the start of a frame when we expected an
8339 ack. Do our best to discard the rest of this packet. */
8348 c = readchar (remote_timeout);
8351 case SERIAL_TIMEOUT:
8352 /* Nothing we can do. */
8355 /* Discard the two bytes of checksum and stop. */
8356 c = readchar (remote_timeout);
8358 c = readchar (remote_timeout);
8361 case '*': /* Run length encoding. */
8362 /* Discard the repeat count. */
8363 c = readchar (remote_timeout);
8368 /* A regular character. */
8374 /* Come here after finding the start of the frame. Collect the rest
8375 into *BUF, verifying the checksum, length, and handling run-length
8376 compression. NUL terminate the buffer. If there is not enough room,
8377 expand *BUF using xrealloc.
8379 Returns -1 on error, number of characters in buffer (ignoring the
8380 trailing NULL) on success. (could be extended to return one of the
8381 SERIAL status indications). */
8384 read_frame (char **buf_p,
8391 struct remote_state *rs = get_remote_state ();
8398 c = readchar (remote_timeout);
8401 case SERIAL_TIMEOUT:
8403 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8407 fputs_filtered ("Saw new packet start in middle of old one\n",
8409 return -1; /* Start a new packet, count retries. */
8412 unsigned char pktcsum;
8418 check_0 = readchar (remote_timeout);
8420 check_1 = readchar (remote_timeout);
8422 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8425 fputs_filtered ("Timeout in checksum, retrying\n",
8429 else if (check_0 < 0 || check_1 < 0)
8432 fputs_filtered ("Communication error in checksum\n",
8437 /* Don't recompute the checksum; with no ack packets we
8438 don't have any way to indicate a packet retransmission
8443 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8444 if (csum == pktcsum)
8449 struct cleanup *old_chain;
8452 str = escape_buffer (buf, bc);
8453 old_chain = make_cleanup (xfree, str);
8454 fprintf_unfiltered (gdb_stdlog,
8455 "Bad checksum, sentsum=0x%x, "
8456 "csum=0x%x, buf=%s\n",
8457 pktcsum, csum, str);
8458 do_cleanups (old_chain);
8460 /* Number of characters in buffer ignoring trailing
8464 case '*': /* Run length encoding. */
8469 c = readchar (remote_timeout);
8471 repeat = c - ' ' + 3; /* Compute repeat count. */
8473 /* The character before ``*'' is repeated. */
8475 if (repeat > 0 && repeat <= 255 && bc > 0)
8477 if (bc + repeat - 1 >= *sizeof_buf - 1)
8479 /* Make some more room in the buffer. */
8480 *sizeof_buf += repeat;
8481 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8485 memset (&buf[bc], buf[bc - 1], repeat);
8491 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8495 if (bc >= *sizeof_buf - 1)
8497 /* Make some more room in the buffer. */
8499 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8510 /* Read a packet from the remote machine, with error checking, and
8511 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8512 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8513 rather than timing out; this is used (in synchronous mode) to wait
8514 for a target that is is executing user code to stop. */
8515 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8516 don't have to change all the calls to getpkt to deal with the
8517 return value, because at the moment I don't know what the right
8518 thing to do it for those. */
8526 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8530 /* Read a packet from the remote machine, with error checking, and
8531 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8532 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8533 rather than timing out; this is used (in synchronous mode) to wait
8534 for a target that is is executing user code to stop. If FOREVER ==
8535 0, this function is allowed to time out gracefully and return an
8536 indication of this to the caller. Otherwise return the number of
8537 bytes read. If EXPECTING_NOTIF, consider receiving a notification
8538 enough reason to return to the caller. *IS_NOTIF is an output
8539 boolean that indicates whether *BUF holds a notification or not
8540 (a regular packet). */
8543 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
8544 int expecting_notif, int *is_notif)
8546 struct remote_state *rs = get_remote_state ();
8552 /* We're reading a new response. Make sure we don't look at a
8553 previously cached response. */
8554 rs->cached_wait_status = 0;
8556 strcpy (*buf, "timeout");
8559 timeout = watchdog > 0 ? watchdog : -1;
8560 else if (expecting_notif)
8561 timeout = 0; /* There should already be a char in the buffer. If
8564 timeout = remote_timeout;
8568 /* Process any number of notifications, and then return when
8572 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
8574 for (tries = 1; tries <= MAX_TRIES; tries++)
8576 /* This can loop forever if the remote side sends us
8577 characters continuously, but if it pauses, we'll get
8578 SERIAL_TIMEOUT from readchar because of timeout. Then
8579 we'll count that as a retry.
8581 Note that even when forever is set, we will only wait
8582 forever prior to the start of a packet. After that, we
8583 expect characters to arrive at a brisk pace. They should
8584 show up within remote_timeout intervals. */
8586 c = readchar (timeout);
8587 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
8589 if (c == SERIAL_TIMEOUT)
8591 if (expecting_notif)
8592 return -1; /* Don't complain, it's normal to not get
8593 anything in this case. */
8595 if (forever) /* Watchdog went off? Kill the target. */
8598 remote_unpush_target ();
8599 throw_error (TARGET_CLOSE_ERROR,
8600 _("Watchdog timeout has expired. "
8601 "Target detached."));
8604 fputs_filtered ("Timed out.\n", gdb_stdlog);
8608 /* We've found the start of a packet or notification.
8609 Now collect the data. */
8610 val = read_frame (buf, sizeof_buf);
8615 remote_serial_write ("-", 1);
8618 if (tries > MAX_TRIES)
8620 /* We have tried hard enough, and just can't receive the
8621 packet/notification. Give up. */
8622 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8624 /* Skip the ack char if we're in no-ack mode. */
8625 if (!rs->noack_mode)
8626 remote_serial_write ("+", 1);
8630 /* If we got an ordinary packet, return that to our caller. */
8635 struct cleanup *old_chain;
8638 str = escape_buffer (*buf, val);
8639 old_chain = make_cleanup (xfree, str);
8640 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8641 do_cleanups (old_chain);
8644 /* Skip the ack char if we're in no-ack mode. */
8645 if (!rs->noack_mode)
8646 remote_serial_write ("+", 1);
8647 if (is_notif != NULL)
8652 /* If we got a notification, handle it, and go back to looking
8656 gdb_assert (c == '%');
8660 struct cleanup *old_chain;
8663 str = escape_buffer (*buf, val);
8664 old_chain = make_cleanup (xfree, str);
8665 fprintf_unfiltered (gdb_stdlog,
8666 " Notification received: %s\n",
8668 do_cleanups (old_chain);
8670 if (is_notif != NULL)
8673 handle_notification (rs->notif_state, *buf);
8675 /* Notifications require no acknowledgement. */
8677 if (expecting_notif)
8684 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8686 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8690 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8693 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8697 /* Check whether EVENT is a fork event for the process specified
8698 by the pid passed in DATA, and if it is, kill the fork child. */
8701 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8702 QUEUE_ITER (stop_reply_p) *iter,
8706 struct queue_iter_param *param = (struct queue_iter_param *) data;
8707 int parent_pid = *(int *) param->input;
8709 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8711 struct remote_state *rs = get_remote_state ();
8712 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8715 res = remote_vkill (child_pid, rs);
8717 error (_("Can't kill fork child process %d"), child_pid);
8723 /* Kill any new fork children of process PID that haven't been
8724 processed by follow_fork. */
8727 kill_new_fork_children (int pid, struct remote_state *rs)
8729 struct thread_info *thread;
8730 struct notif_client *notif = ¬if_client_stop;
8731 struct queue_iter_param param;
8733 /* Kill the fork child threads of any threads in process PID
8734 that are stopped at a fork event. */
8735 ALL_NON_EXITED_THREADS (thread)
8737 struct target_waitstatus *ws = &thread->pending_follow;
8739 if (is_pending_fork_parent (ws, pid, thread->ptid))
8741 struct remote_state *rs = get_remote_state ();
8742 int child_pid = ptid_get_pid (ws->value.related_pid);
8745 res = remote_vkill (child_pid, rs);
8747 error (_("Can't kill fork child process %d"), child_pid);
8751 /* Check for any pending fork events (not reported or processed yet)
8752 in process PID and kill those fork child threads as well. */
8753 remote_notif_get_pending_events (notif);
8755 param.output = NULL;
8756 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8757 kill_child_of_pending_fork, ¶m);
8762 remote_kill (struct target_ops *ops)
8765 /* Catch errors so the user can quit from gdb even when we
8766 aren't on speaking terms with the remote system. */
8771 CATCH (ex, RETURN_MASK_ERROR)
8773 if (ex.error == TARGET_CLOSE_ERROR)
8775 /* If we got an (EOF) error that caused the target
8776 to go away, then we're done, that's what we wanted.
8777 "k" is susceptible to cause a premature EOF, given
8778 that the remote server isn't actually required to
8779 reply to "k", and it can happen that it doesn't
8780 even get to reply ACK to the "k". */
8784 /* Otherwise, something went wrong. We didn't actually kill
8785 the target. Just propagate the exception, and let the
8786 user or higher layers decide what to do. */
8787 throw_exception (ex);
8791 /* We've killed the remote end, we get to mourn it. Since this is
8792 target remote, single-process, mourning the inferior also
8793 unpushes remote_ops. */
8794 target_mourn_inferior ();
8798 remote_vkill (int pid, struct remote_state *rs)
8800 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8803 /* Tell the remote target to detach. */
8804 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8806 getpkt (&rs->buf, &rs->buf_size, 0);
8808 switch (packet_ok (rs->buf,
8809 &remote_protocol_packets[PACKET_vKill]))
8815 case PACKET_UNKNOWN:
8818 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8823 extended_remote_kill (struct target_ops *ops)
8826 int pid = ptid_get_pid (inferior_ptid);
8827 struct remote_state *rs = get_remote_state ();
8829 /* If we're stopped while forking and we haven't followed yet, kill the
8830 child task. We need to do this before killing the parent task
8831 because if this is a vfork then the parent will be sleeping. */
8832 kill_new_fork_children (pid, rs);
8834 res = remote_vkill (pid, rs);
8835 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8837 /* Don't try 'k' on a multi-process aware stub -- it has no way
8838 to specify the pid. */
8842 getpkt (&rs->buf, &rs->buf_size, 0);
8843 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8846 /* Don't wait for it to die. I'm not really sure it matters whether
8847 we do or not. For the existing stubs, kill is a noop. */
8853 error (_("Can't kill process"));
8855 target_mourn_inferior ();
8859 remote_mourn (struct target_ops *target)
8861 unpush_target (target);
8863 /* remote_close takes care of doing most of the clean up. */
8864 generic_mourn_inferior ();
8868 extended_remote_mourn (struct target_ops *target)
8870 struct remote_state *rs = get_remote_state ();
8872 /* In case we got here due to an error, but we're going to stay
8874 rs->waiting_for_stop_reply = 0;
8876 /* If the current general thread belonged to the process we just
8877 detached from or has exited, the remote side current general
8878 thread becomes undefined. Considering a case like this:
8880 - We just got here due to a detach.
8881 - The process that we're detaching from happens to immediately
8882 report a global breakpoint being hit in non-stop mode, in the
8883 same thread we had selected before.
8884 - GDB attaches to this process again.
8885 - This event happens to be the next event we handle.
8887 GDB would consider that the current general thread didn't need to
8888 be set on the stub side (with Hg), since for all it knew,
8889 GENERAL_THREAD hadn't changed.
8891 Notice that although in all-stop mode, the remote server always
8892 sets the current thread to the thread reporting the stop event,
8893 that doesn't happen in non-stop mode; in non-stop, the stub *must
8894 not* change the current thread when reporting a breakpoint hit,
8895 due to the decoupling of event reporting and event handling.
8897 To keep things simple, we always invalidate our notion of the
8899 record_currthread (rs, minus_one_ptid);
8901 /* Unlike "target remote", we do not want to unpush the target; then
8902 the next time the user says "run", we won't be connected. */
8904 /* Call common code to mark the inferior as not running. */
8905 generic_mourn_inferior ();
8907 if (!have_inferiors ())
8909 if (!remote_multi_process_p (rs))
8911 /* Check whether the target is running now - some remote stubs
8912 automatically restart after kill. */
8914 getpkt (&rs->buf, &rs->buf_size, 0);
8916 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8918 /* Assume that the target has been restarted. Set
8919 inferior_ptid so that bits of core GDB realizes
8920 there's something here, e.g., so that the user can
8921 say "kill" again. */
8922 inferior_ptid = magic_null_ptid;
8929 extended_remote_supports_disable_randomization (struct target_ops *self)
8931 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8935 extended_remote_disable_randomization (int val)
8937 struct remote_state *rs = get_remote_state ();
8940 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8943 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8945 error (_("Target does not support QDisableRandomization."));
8946 if (strcmp (reply, "OK") != 0)
8947 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8951 extended_remote_run (char *args)
8953 struct remote_state *rs = get_remote_state ();
8955 const char *remote_exec_file = get_remote_exec_file ();
8957 /* If the user has disabled vRun support, or we have detected that
8958 support is not available, do not try it. */
8959 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8962 strcpy (rs->buf, "vRun;");
8963 len = strlen (rs->buf);
8965 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8966 error (_("Remote file name too long for run packet"));
8967 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8968 strlen (remote_exec_file));
8970 gdb_assert (args != NULL);
8973 struct cleanup *back_to;
8977 argv = gdb_buildargv (args);
8978 back_to = make_cleanup_freeargv (argv);
8979 for (i = 0; argv[i] != NULL; i++)
8981 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8982 error (_("Argument list too long for run packet"));
8983 rs->buf[len++] = ';';
8984 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8987 do_cleanups (back_to);
8990 rs->buf[len++] = '\0';
8993 getpkt (&rs->buf, &rs->buf_size, 0);
8995 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8998 /* We have a wait response. All is well. */
9000 case PACKET_UNKNOWN:
9003 if (remote_exec_file[0] == '\0')
9004 error (_("Running the default executable on the remote target failed; "
9005 "try \"set remote exec-file\"?"));
9007 error (_("Running \"%s\" on the remote target failed"),
9010 gdb_assert_not_reached (_("bad switch"));
9014 /* In the extended protocol we want to be able to do things like
9015 "run" and have them basically work as expected. So we need
9016 a special create_inferior function. We support changing the
9017 executable file and the command line arguments, but not the
9021 extended_remote_create_inferior (struct target_ops *ops,
9022 char *exec_file, char *args,
9023 char **env, int from_tty)
9027 struct remote_state *rs = get_remote_state ();
9028 const char *remote_exec_file = get_remote_exec_file ();
9030 /* If running asynchronously, register the target file descriptor
9031 with the event loop. */
9032 if (target_can_async_p ())
9035 /* Disable address space randomization if requested (and supported). */
9036 if (extended_remote_supports_disable_randomization (ops))
9037 extended_remote_disable_randomization (disable_randomization);
9039 /* Now restart the remote server. */
9040 run_worked = extended_remote_run (args) != -1;
9043 /* vRun was not supported. Fail if we need it to do what the
9045 if (remote_exec_file[0])
9046 error (_("Remote target does not support \"set remote exec-file\""));
9048 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9050 /* Fall back to "R". */
9051 extended_remote_restart ();
9054 if (!have_inferiors ())
9056 /* Clean up from the last time we ran, before we mark the target
9057 running again. This will mark breakpoints uninserted, and
9058 get_offsets may insert breakpoints. */
9059 init_thread_list ();
9060 init_wait_for_inferior ();
9063 /* vRun's success return is a stop reply. */
9064 stop_reply = run_worked ? rs->buf : NULL;
9065 add_current_inferior_and_thread (stop_reply);
9067 /* Get updated offsets, if the stub uses qOffsets. */
9072 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9073 the list of conditions (in agent expression bytecode format), if any, the
9074 target needs to evaluate. The output is placed into the packet buffer
9075 started from BUF and ended at BUF_END. */
9078 remote_add_target_side_condition (struct gdbarch *gdbarch,
9079 struct bp_target_info *bp_tgt, char *buf,
9082 struct agent_expr *aexpr = NULL;
9085 char *buf_start = buf;
9087 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9090 buf += strlen (buf);
9091 xsnprintf (buf, buf_end - buf, "%s", ";");
9094 /* Send conditions to the target and free the vector. */
9096 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9099 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9100 buf += strlen (buf);
9101 for (i = 0; i < aexpr->len; ++i)
9102 buf = pack_hex_byte (buf, aexpr->buf[i]);
9109 remote_add_target_side_commands (struct gdbarch *gdbarch,
9110 struct bp_target_info *bp_tgt, char *buf)
9112 struct agent_expr *aexpr = NULL;
9115 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9118 buf += strlen (buf);
9120 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9121 buf += strlen (buf);
9123 /* Concatenate all the agent expressions that are commands into the
9126 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9129 sprintf (buf, "X%x,", aexpr->len);
9130 buf += strlen (buf);
9131 for (i = 0; i < aexpr->len; ++i)
9132 buf = pack_hex_byte (buf, aexpr->buf[i]);
9137 /* Insert a breakpoint. On targets that have software breakpoint
9138 support, we ask the remote target to do the work; on targets
9139 which don't, we insert a traditional memory breakpoint. */
9142 remote_insert_breakpoint (struct target_ops *ops,
9143 struct gdbarch *gdbarch,
9144 struct bp_target_info *bp_tgt)
9146 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9147 If it succeeds, then set the support to PACKET_ENABLE. If it
9148 fails, and the user has explicitly requested the Z support then
9149 report an error, otherwise, mark it disabled and go on. */
9151 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9153 CORE_ADDR addr = bp_tgt->reqstd_address;
9154 struct remote_state *rs;
9157 struct condition_list *cond = NULL;
9159 /* Make sure the remote is pointing at the right process, if
9161 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9162 set_general_process ();
9164 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9166 rs = get_remote_state ();
9168 endbuf = rs->buf + get_remote_packet_size ();
9173 addr = (ULONGEST) remote_address_masked (addr);
9174 p += hexnumstr (p, addr);
9175 xsnprintf (p, endbuf - p, ",%d", bpsize);
9177 if (remote_supports_cond_breakpoints (ops))
9178 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9180 if (remote_can_run_breakpoint_commands (ops))
9181 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9184 getpkt (&rs->buf, &rs->buf_size, 0);
9186 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9191 bp_tgt->placed_address = addr;
9192 bp_tgt->placed_size = bpsize;
9194 case PACKET_UNKNOWN:
9199 /* If this breakpoint has target-side commands but this stub doesn't
9200 support Z0 packets, throw error. */
9201 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9202 throw_error (NOT_SUPPORTED_ERROR, _("\
9203 Target doesn't support breakpoints that have target side commands."));
9205 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9209 remote_remove_breakpoint (struct target_ops *ops,
9210 struct gdbarch *gdbarch,
9211 struct bp_target_info *bp_tgt)
9213 CORE_ADDR addr = bp_tgt->placed_address;
9214 struct remote_state *rs = get_remote_state ();
9216 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9219 char *endbuf = rs->buf + get_remote_packet_size ();
9221 /* Make sure the remote is pointing at the right process, if
9223 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9224 set_general_process ();
9230 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9231 p += hexnumstr (p, addr);
9232 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
9235 getpkt (&rs->buf, &rs->buf_size, 0);
9237 return (rs->buf[0] == 'E');
9240 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
9243 static enum Z_packet_type
9244 watchpoint_to_Z_packet (int type)
9249 return Z_PACKET_WRITE_WP;
9252 return Z_PACKET_READ_WP;
9255 return Z_PACKET_ACCESS_WP;
9258 internal_error (__FILE__, __LINE__,
9259 _("hw_bp_to_z: bad watchpoint type %d"), type);
9264 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9265 enum target_hw_bp_type type, struct expression *cond)
9267 struct remote_state *rs = get_remote_state ();
9268 char *endbuf = rs->buf + get_remote_packet_size ();
9270 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9272 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9275 /* Make sure the remote is pointing at the right process, if
9277 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9278 set_general_process ();
9280 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9281 p = strchr (rs->buf, '\0');
9282 addr = remote_address_masked (addr);
9283 p += hexnumstr (p, (ULONGEST) addr);
9284 xsnprintf (p, endbuf - p, ",%x", len);
9287 getpkt (&rs->buf, &rs->buf_size, 0);
9289 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9293 case PACKET_UNKNOWN:
9298 internal_error (__FILE__, __LINE__,
9299 _("remote_insert_watchpoint: reached end of function"));
9303 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9304 CORE_ADDR start, int length)
9306 CORE_ADDR diff = remote_address_masked (addr - start);
9308 return diff < length;
9313 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9314 enum target_hw_bp_type type, struct expression *cond)
9316 struct remote_state *rs = get_remote_state ();
9317 char *endbuf = rs->buf + get_remote_packet_size ();
9319 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9321 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9324 /* Make sure the remote is pointing at the right process, if
9326 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9327 set_general_process ();
9329 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9330 p = strchr (rs->buf, '\0');
9331 addr = remote_address_masked (addr);
9332 p += hexnumstr (p, (ULONGEST) addr);
9333 xsnprintf (p, endbuf - p, ",%x", len);
9335 getpkt (&rs->buf, &rs->buf_size, 0);
9337 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9340 case PACKET_UNKNOWN:
9345 internal_error (__FILE__, __LINE__,
9346 _("remote_remove_watchpoint: reached end of function"));
9350 int remote_hw_watchpoint_limit = -1;
9351 int remote_hw_watchpoint_length_limit = -1;
9352 int remote_hw_breakpoint_limit = -1;
9355 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9356 CORE_ADDR addr, int len)
9358 if (remote_hw_watchpoint_length_limit == 0)
9360 else if (remote_hw_watchpoint_length_limit < 0)
9362 else if (len <= remote_hw_watchpoint_length_limit)
9369 remote_check_watch_resources (struct target_ops *self,
9370 enum bptype type, int cnt, int ot)
9372 if (type == bp_hardware_breakpoint)
9374 if (remote_hw_breakpoint_limit == 0)
9376 else if (remote_hw_breakpoint_limit < 0)
9378 else if (cnt <= remote_hw_breakpoint_limit)
9383 if (remote_hw_watchpoint_limit == 0)
9385 else if (remote_hw_watchpoint_limit < 0)
9389 else if (cnt <= remote_hw_watchpoint_limit)
9395 /* The to_stopped_by_sw_breakpoint method of target remote. */
9398 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9400 struct thread_info *thread = inferior_thread ();
9402 return (thread->priv != NULL
9403 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
9406 /* The to_supports_stopped_by_sw_breakpoint method of target
9410 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9412 struct remote_state *rs = get_remote_state ();
9414 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9417 /* The to_stopped_by_hw_breakpoint method of target remote. */
9420 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9422 struct thread_info *thread = inferior_thread ();
9424 return (thread->priv != NULL
9425 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
9428 /* The to_supports_stopped_by_hw_breakpoint method of target
9432 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9434 struct remote_state *rs = get_remote_state ();
9436 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9440 remote_stopped_by_watchpoint (struct target_ops *ops)
9442 struct thread_info *thread = inferior_thread ();
9444 return (thread->priv != NULL
9445 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
9449 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
9451 struct thread_info *thread = inferior_thread ();
9453 if (thread->priv != NULL
9454 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
9456 *addr_p = thread->priv->watch_data_address;
9465 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9466 struct bp_target_info *bp_tgt)
9468 CORE_ADDR addr = bp_tgt->reqstd_address;
9469 struct remote_state *rs;
9474 /* The length field should be set to the size of a breakpoint
9475 instruction, even though we aren't inserting one ourselves. */
9477 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
9479 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9482 /* Make sure the remote is pointing at the right process, if
9484 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9485 set_general_process ();
9487 rs = get_remote_state ();
9489 endbuf = rs->buf + get_remote_packet_size ();
9495 addr = remote_address_masked (addr);
9496 p += hexnumstr (p, (ULONGEST) addr);
9497 xsnprintf (p, endbuf - p, ",%x", bpsize);
9499 if (remote_supports_cond_breakpoints (self))
9500 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9502 if (remote_can_run_breakpoint_commands (self))
9503 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9506 getpkt (&rs->buf, &rs->buf_size, 0);
9508 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9511 if (rs->buf[1] == '.')
9513 message = strchr (rs->buf + 2, '.');
9515 error (_("Remote failure reply: %s"), message + 1);
9518 case PACKET_UNKNOWN:
9521 bp_tgt->placed_address = addr;
9522 bp_tgt->placed_size = bpsize;
9525 internal_error (__FILE__, __LINE__,
9526 _("remote_insert_hw_breakpoint: reached end of function"));
9531 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
9532 struct bp_target_info *bp_tgt)
9535 struct remote_state *rs = get_remote_state ();
9537 char *endbuf = rs->buf + get_remote_packet_size ();
9539 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
9542 /* Make sure the remote is pointing at the right process, if
9544 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9545 set_general_process ();
9551 addr = remote_address_masked (bp_tgt->placed_address);
9552 p += hexnumstr (p, (ULONGEST) addr);
9553 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
9556 getpkt (&rs->buf, &rs->buf_size, 0);
9558 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
9561 case PACKET_UNKNOWN:
9566 internal_error (__FILE__, __LINE__,
9567 _("remote_remove_hw_breakpoint: reached end of function"));
9570 /* Verify memory using the "qCRC:" request. */
9573 remote_verify_memory (struct target_ops *ops,
9574 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9576 struct remote_state *rs = get_remote_state ();
9577 unsigned long host_crc, target_crc;
9580 /* It doesn't make sense to use qCRC if the remote target is
9581 connected but not running. */
9582 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9584 enum packet_result result;
9586 /* Make sure the remote is pointing at the right process. */
9587 set_general_process ();
9589 /* FIXME: assumes lma can fit into long. */
9590 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9591 (long) lma, (long) size);
9594 /* Be clever; compute the host_crc before waiting for target
9596 host_crc = xcrc32 (data, size, 0xffffffff);
9598 getpkt (&rs->buf, &rs->buf_size, 0);
9600 result = packet_ok (rs->buf,
9601 &remote_protocol_packets[PACKET_qCRC]);
9602 if (result == PACKET_ERROR)
9604 else if (result == PACKET_OK)
9606 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9607 target_crc = target_crc * 16 + fromhex (*tmp);
9609 return (host_crc == target_crc);
9613 return simple_verify_memory (ops, data, lma, size);
9616 /* compare-sections command
9618 With no arguments, compares each loadable section in the exec bfd
9619 with the same memory range on the target, and reports mismatches.
9620 Useful for verifying the image on the target against the exec file. */
9623 compare_sections_command (char *args, int from_tty)
9626 struct cleanup *old_chain;
9628 const char *sectname;
9637 error (_("command cannot be used without an exec file"));
9639 /* Make sure the remote is pointing at the right process. */
9640 set_general_process ();
9642 if (args != NULL && strcmp (args, "-r") == 0)
9648 for (s = exec_bfd->sections; s; s = s->next)
9650 if (!(s->flags & SEC_LOAD))
9651 continue; /* Skip non-loadable section. */
9653 if (read_only && (s->flags & SEC_READONLY) == 0)
9654 continue; /* Skip writeable sections */
9656 size = bfd_get_section_size (s);
9658 continue; /* Skip zero-length section. */
9660 sectname = bfd_get_section_name (exec_bfd, s);
9661 if (args && strcmp (args, sectname) != 0)
9662 continue; /* Not the section selected by user. */
9664 matched = 1; /* Do this section. */
9667 sectdata = (gdb_byte *) xmalloc (size);
9668 old_chain = make_cleanup (xfree, sectdata);
9669 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9671 res = target_verify_memory (sectdata, lma, size);
9674 error (_("target memory fault, section %s, range %s -- %s"), sectname,
9675 paddress (target_gdbarch (), lma),
9676 paddress (target_gdbarch (), lma + size));
9678 printf_filtered ("Section %s, range %s -- %s: ", sectname,
9679 paddress (target_gdbarch (), lma),
9680 paddress (target_gdbarch (), lma + size));
9682 printf_filtered ("matched.\n");
9685 printf_filtered ("MIS-MATCHED!\n");
9689 do_cleanups (old_chain);
9692 warning (_("One or more sections of the target image does not match\n\
9693 the loaded file\n"));
9694 if (args && !matched)
9695 printf_filtered (_("No loaded section named '%s'.\n"), args);
9698 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9699 into remote target. The number of bytes written to the remote
9700 target is returned, or -1 for error. */
9702 static enum target_xfer_status
9703 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9704 const char *annex, const gdb_byte *writebuf,
9705 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9706 struct packet_config *packet)
9710 struct remote_state *rs = get_remote_state ();
9711 int max_size = get_memory_write_packet_size ();
9713 if (packet->support == PACKET_DISABLE)
9714 return TARGET_XFER_E_IO;
9716 /* Insert header. */
9717 i = snprintf (rs->buf, max_size,
9718 "qXfer:%s:write:%s:%s:",
9719 object_name, annex ? annex : "",
9720 phex_nz (offset, sizeof offset));
9721 max_size -= (i + 1);
9723 /* Escape as much data as fits into rs->buf. */
9724 buf_len = remote_escape_output
9725 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
9727 if (putpkt_binary (rs->buf, i + buf_len) < 0
9728 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9729 || packet_ok (rs->buf, packet) != PACKET_OK)
9730 return TARGET_XFER_E_IO;
9732 unpack_varlen_hex (rs->buf, &n);
9735 return TARGET_XFER_OK;
9738 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9739 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9740 number of bytes read is returned, or 0 for EOF, or -1 for error.
9741 The number of bytes read may be less than LEN without indicating an
9742 EOF. PACKET is checked and updated to indicate whether the remote
9743 target supports this object. */
9745 static enum target_xfer_status
9746 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9748 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9749 ULONGEST *xfered_len,
9750 struct packet_config *packet)
9752 struct remote_state *rs = get_remote_state ();
9753 LONGEST i, n, packet_len;
9755 if (packet->support == PACKET_DISABLE)
9756 return TARGET_XFER_E_IO;
9758 /* Check whether we've cached an end-of-object packet that matches
9760 if (rs->finished_object)
9762 if (strcmp (object_name, rs->finished_object) == 0
9763 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9764 && offset == rs->finished_offset)
9765 return TARGET_XFER_EOF;
9768 /* Otherwise, we're now reading something different. Discard
9770 xfree (rs->finished_object);
9771 xfree (rs->finished_annex);
9772 rs->finished_object = NULL;
9773 rs->finished_annex = NULL;
9776 /* Request only enough to fit in a single packet. The actual data
9777 may not, since we don't know how much of it will need to be escaped;
9778 the target is free to respond with slightly less data. We subtract
9779 five to account for the response type and the protocol frame. */
9780 n = min (get_remote_packet_size () - 5, len);
9781 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9782 object_name, annex ? annex : "",
9783 phex_nz (offset, sizeof offset),
9784 phex_nz (n, sizeof n));
9785 i = putpkt (rs->buf);
9787 return TARGET_XFER_E_IO;
9790 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9791 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9792 return TARGET_XFER_E_IO;
9794 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9795 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9797 /* 'm' means there is (or at least might be) more data after this
9798 batch. That does not make sense unless there's at least one byte
9799 of data in this reply. */
9800 if (rs->buf[0] == 'm' && packet_len == 1)
9801 error (_("Remote qXfer reply contained no data."));
9803 /* Got some data. */
9804 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9805 packet_len - 1, readbuf, n);
9807 /* 'l' is an EOF marker, possibly including a final block of data,
9808 or possibly empty. If we have the final block of a non-empty
9809 object, record this fact to bypass a subsequent partial read. */
9810 if (rs->buf[0] == 'l' && offset + i > 0)
9812 rs->finished_object = xstrdup (object_name);
9813 rs->finished_annex = xstrdup (annex ? annex : "");
9814 rs->finished_offset = offset + i;
9818 return TARGET_XFER_EOF;
9822 return TARGET_XFER_OK;
9826 static enum target_xfer_status
9827 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9828 const char *annex, gdb_byte *readbuf,
9829 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9830 ULONGEST *xfered_len)
9832 struct remote_state *rs;
9836 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
9838 set_remote_traceframe ();
9839 set_general_thread (inferior_ptid);
9841 rs = get_remote_state ();
9843 /* Handle memory using the standard memory routines. */
9844 if (object == TARGET_OBJECT_MEMORY)
9846 /* If the remote target is connected but not running, we should
9847 pass this request down to a lower stratum (e.g. the executable
9849 if (!target_has_execution)
9850 return TARGET_XFER_EOF;
9852 if (writebuf != NULL)
9853 return remote_write_bytes (offset, writebuf, len, unit_size,
9856 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9860 /* Handle SPU memory using qxfer packets. */
9861 if (object == TARGET_OBJECT_SPU)
9864 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9865 xfered_len, &remote_protocol_packets
9866 [PACKET_qXfer_spu_read]);
9868 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9869 xfered_len, &remote_protocol_packets
9870 [PACKET_qXfer_spu_write]);
9873 /* Handle extra signal info using qxfer packets. */
9874 if (object == TARGET_OBJECT_SIGNAL_INFO)
9877 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9878 xfered_len, &remote_protocol_packets
9879 [PACKET_qXfer_siginfo_read]);
9881 return remote_write_qxfer (ops, "siginfo", annex,
9882 writebuf, offset, len, xfered_len,
9883 &remote_protocol_packets
9884 [PACKET_qXfer_siginfo_write]);
9887 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9890 return remote_read_qxfer (ops, "statictrace", annex,
9891 readbuf, offset, len, xfered_len,
9892 &remote_protocol_packets
9893 [PACKET_qXfer_statictrace_read]);
9895 return TARGET_XFER_E_IO;
9898 /* Only handle flash writes. */
9899 if (writebuf != NULL)
9905 case TARGET_OBJECT_FLASH:
9906 return remote_flash_write (ops, offset, len, xfered_len,
9910 return TARGET_XFER_E_IO;
9914 /* Map pre-existing objects onto letters. DO NOT do this for new
9915 objects!!! Instead specify new query packets. */
9918 case TARGET_OBJECT_AVR:
9922 case TARGET_OBJECT_AUXV:
9923 gdb_assert (annex == NULL);
9924 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9926 &remote_protocol_packets[PACKET_qXfer_auxv]);
9928 case TARGET_OBJECT_AVAILABLE_FEATURES:
9929 return remote_read_qxfer
9930 (ops, "features", annex, readbuf, offset, len, xfered_len,
9931 &remote_protocol_packets[PACKET_qXfer_features]);
9933 case TARGET_OBJECT_LIBRARIES:
9934 return remote_read_qxfer
9935 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9936 &remote_protocol_packets[PACKET_qXfer_libraries]);
9938 case TARGET_OBJECT_LIBRARIES_SVR4:
9939 return remote_read_qxfer
9940 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9941 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9943 case TARGET_OBJECT_MEMORY_MAP:
9944 gdb_assert (annex == NULL);
9945 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9947 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9949 case TARGET_OBJECT_OSDATA:
9950 /* Should only get here if we're connected. */
9951 gdb_assert (rs->remote_desc);
9952 return remote_read_qxfer
9953 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9954 &remote_protocol_packets[PACKET_qXfer_osdata]);
9956 case TARGET_OBJECT_THREADS:
9957 gdb_assert (annex == NULL);
9958 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9960 &remote_protocol_packets[PACKET_qXfer_threads]);
9962 case TARGET_OBJECT_TRACEFRAME_INFO:
9963 gdb_assert (annex == NULL);
9964 return remote_read_qxfer
9965 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9966 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9968 case TARGET_OBJECT_FDPIC:
9969 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9971 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9973 case TARGET_OBJECT_OPENVMS_UIB:
9974 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9976 &remote_protocol_packets[PACKET_qXfer_uib]);
9978 case TARGET_OBJECT_BTRACE:
9979 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9981 &remote_protocol_packets[PACKET_qXfer_btrace]);
9983 case TARGET_OBJECT_BTRACE_CONF:
9984 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9986 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9988 case TARGET_OBJECT_EXEC_FILE:
9989 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9991 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9994 return TARGET_XFER_E_IO;
9997 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9998 large enough let the caller deal with it. */
9999 if (len < get_remote_packet_size ())
10000 return TARGET_XFER_E_IO;
10001 len = get_remote_packet_size ();
10003 /* Except for querying the minimum buffer size, target must be open. */
10004 if (!rs->remote_desc)
10005 error (_("remote query is only available after target open"));
10007 gdb_assert (annex != NULL);
10008 gdb_assert (readbuf != NULL);
10012 *p2++ = query_type;
10014 /* We used one buffer char for the remote protocol q command and
10015 another for the query type. As the remote protocol encapsulation
10016 uses 4 chars plus one extra in case we are debugging
10017 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10020 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10022 /* Bad caller may have sent forbidden characters. */
10023 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10028 gdb_assert (annex[i] == '\0');
10030 i = putpkt (rs->buf);
10032 return TARGET_XFER_E_IO;
10034 getpkt (&rs->buf, &rs->buf_size, 0);
10035 strcpy ((char *) readbuf, rs->buf);
10037 *xfered_len = strlen ((char *) readbuf);
10038 return TARGET_XFER_OK;
10042 remote_search_memory (struct target_ops* ops,
10043 CORE_ADDR start_addr, ULONGEST search_space_len,
10044 const gdb_byte *pattern, ULONGEST pattern_len,
10045 CORE_ADDR *found_addrp)
10047 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10048 struct remote_state *rs = get_remote_state ();
10049 int max_size = get_memory_write_packet_size ();
10050 struct packet_config *packet =
10051 &remote_protocol_packets[PACKET_qSearch_memory];
10052 /* Number of packet bytes used to encode the pattern;
10053 this could be more than PATTERN_LEN due to escape characters. */
10054 int escaped_pattern_len;
10055 /* Amount of pattern that was encodable in the packet. */
10056 int used_pattern_len;
10059 ULONGEST found_addr;
10061 /* Don't go to the target if we don't have to.
10062 This is done before checking packet->support to avoid the possibility that
10063 a success for this edge case means the facility works in general. */
10064 if (pattern_len > search_space_len)
10066 if (pattern_len == 0)
10068 *found_addrp = start_addr;
10072 /* If we already know the packet isn't supported, fall back to the simple
10073 way of searching memory. */
10075 if (packet_config_support (packet) == PACKET_DISABLE)
10077 /* Target doesn't provided special support, fall back and use the
10078 standard support (copy memory and do the search here). */
10079 return simple_search_memory (ops, start_addr, search_space_len,
10080 pattern, pattern_len, found_addrp);
10083 /* Make sure the remote is pointing at the right process. */
10084 set_general_process ();
10086 /* Insert header. */
10087 i = snprintf (rs->buf, max_size,
10088 "qSearch:memory:%s;%s;",
10089 phex_nz (start_addr, addr_size),
10090 phex_nz (search_space_len, sizeof (search_space_len)));
10091 max_size -= (i + 1);
10093 /* Escape as much data as fits into rs->buf. */
10094 escaped_pattern_len =
10095 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10096 &used_pattern_len, max_size);
10098 /* Bail if the pattern is too large. */
10099 if (used_pattern_len != pattern_len)
10100 error (_("Pattern is too large to transmit to remote target."));
10102 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10103 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10104 || packet_ok (rs->buf, packet) != PACKET_OK)
10106 /* The request may not have worked because the command is not
10107 supported. If so, fall back to the simple way. */
10108 if (packet->support == PACKET_DISABLE)
10110 return simple_search_memory (ops, start_addr, search_space_len,
10111 pattern, pattern_len, found_addrp);
10116 if (rs->buf[0] == '0')
10118 else if (rs->buf[0] == '1')
10121 if (rs->buf[1] != ',')
10122 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10123 unpack_varlen_hex (rs->buf + 2, &found_addr);
10124 *found_addrp = found_addr;
10127 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10133 remote_rcmd (struct target_ops *self, const char *command,
10134 struct ui_file *outbuf)
10136 struct remote_state *rs = get_remote_state ();
10139 if (!rs->remote_desc)
10140 error (_("remote rcmd is only available after target open"));
10142 /* Send a NULL command across as an empty command. */
10143 if (command == NULL)
10146 /* The query prefix. */
10147 strcpy (rs->buf, "qRcmd,");
10148 p = strchr (rs->buf, '\0');
10150 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10151 > get_remote_packet_size ())
10152 error (_("\"monitor\" command ``%s'' is too long."), command);
10154 /* Encode the actual command. */
10155 bin2hex ((const gdb_byte *) command, p, strlen (command));
10157 if (putpkt (rs->buf) < 0)
10158 error (_("Communication problem with target."));
10160 /* get/display the response */
10165 /* XXX - see also remote_get_noisy_reply(). */
10166 QUIT; /* Allow user to bail out with ^C. */
10168 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10170 /* Timeout. Continue to (try to) read responses.
10171 This is better than stopping with an error, assuming the stub
10172 is still executing the (long) monitor command.
10173 If needed, the user can interrupt gdb using C-c, obtaining
10174 an effect similar to stop on timeout. */
10178 if (buf[0] == '\0')
10179 error (_("Target does not support this command."));
10180 if (buf[0] == 'O' && buf[1] != 'K')
10182 remote_console_output (buf + 1); /* 'O' message from stub. */
10185 if (strcmp (buf, "OK") == 0)
10187 if (strlen (buf) == 3 && buf[0] == 'E'
10188 && isdigit (buf[1]) && isdigit (buf[2]))
10190 error (_("Protocol error with Rcmd"));
10192 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10194 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10196 fputc_unfiltered (c, outbuf);
10202 static VEC(mem_region_s) *
10203 remote_memory_map (struct target_ops *ops)
10205 VEC(mem_region_s) *result = NULL;
10206 char *text = target_read_stralloc (¤t_target,
10207 TARGET_OBJECT_MEMORY_MAP, NULL);
10211 struct cleanup *back_to = make_cleanup (xfree, text);
10213 result = parse_memory_map (text);
10214 do_cleanups (back_to);
10221 packet_command (char *args, int from_tty)
10223 struct remote_state *rs = get_remote_state ();
10225 if (!rs->remote_desc)
10226 error (_("command can only be used with remote target"));
10229 error (_("remote-packet command requires packet text as argument"));
10231 puts_filtered ("sending: ");
10232 print_packet (args);
10233 puts_filtered ("\n");
10236 getpkt (&rs->buf, &rs->buf_size, 0);
10237 puts_filtered ("received: ");
10238 print_packet (rs->buf);
10239 puts_filtered ("\n");
10243 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10245 static void display_thread_info (struct gdb_ext_thread_info *info);
10247 static void threadset_test_cmd (char *cmd, int tty);
10249 static void threadalive_test (char *cmd, int tty);
10251 static void threadlist_test_cmd (char *cmd, int tty);
10253 int get_and_display_threadinfo (threadref *ref);
10255 static void threadinfo_test_cmd (char *cmd, int tty);
10257 static int thread_display_step (threadref *ref, void *context);
10259 static void threadlist_update_test_cmd (char *cmd, int tty);
10261 static void init_remote_threadtests (void);
10263 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10266 threadset_test_cmd (char *cmd, int tty)
10268 int sample_thread = SAMPLE_THREAD;
10270 printf_filtered (_("Remote threadset test\n"));
10271 set_general_thread (sample_thread);
10276 threadalive_test (char *cmd, int tty)
10278 int sample_thread = SAMPLE_THREAD;
10279 int pid = ptid_get_pid (inferior_ptid);
10280 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10282 if (remote_thread_alive (ptid))
10283 printf_filtered ("PASS: Thread alive test\n");
10285 printf_filtered ("FAIL: Thread alive test\n");
10288 void output_threadid (char *title, threadref *ref);
10291 output_threadid (char *title, threadref *ref)
10295 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10297 printf_filtered ("%s %s\n", title, (&hexid[0]));
10301 threadlist_test_cmd (char *cmd, int tty)
10304 threadref nextthread;
10305 int done, result_count;
10306 threadref threadlist[3];
10308 printf_filtered ("Remote Threadlist test\n");
10309 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10310 &result_count, &threadlist[0]))
10311 printf_filtered ("FAIL: threadlist test\n");
10314 threadref *scan = threadlist;
10315 threadref *limit = scan + result_count;
10317 while (scan < limit)
10318 output_threadid (" thread ", scan++);
10323 display_thread_info (struct gdb_ext_thread_info *info)
10325 output_threadid ("Threadid: ", &info->threadid);
10326 printf_filtered ("Name: %s\n ", info->shortname);
10327 printf_filtered ("State: %s\n", info->display);
10328 printf_filtered ("other: %s\n\n", info->more_display);
10332 get_and_display_threadinfo (threadref *ref)
10336 struct gdb_ext_thread_info threadinfo;
10338 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10339 | TAG_MOREDISPLAY | TAG_DISPLAY;
10340 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10341 display_thread_info (&threadinfo);
10346 threadinfo_test_cmd (char *cmd, int tty)
10348 int athread = SAMPLE_THREAD;
10352 int_to_threadref (&thread, athread);
10353 printf_filtered ("Remote Threadinfo test\n");
10354 if (!get_and_display_threadinfo (&thread))
10355 printf_filtered ("FAIL cannot get thread info\n");
10359 thread_display_step (threadref *ref, void *context)
10361 /* output_threadid(" threadstep ",ref); *//* simple test */
10362 return get_and_display_threadinfo (ref);
10366 threadlist_update_test_cmd (char *cmd, int tty)
10368 printf_filtered ("Remote Threadlist update test\n");
10369 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10373 init_remote_threadtests (void)
10375 add_com ("tlist", class_obscure, threadlist_test_cmd,
10376 _("Fetch and print the remote list of "
10377 "thread identifiers, one pkt only"));
10378 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10379 _("Fetch and display info about one thread"));
10380 add_com ("tset", class_obscure, threadset_test_cmd,
10381 _("Test setting to a different thread"));
10382 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10383 _("Iterate through updating all remote thread info"));
10384 add_com ("talive", class_obscure, threadalive_test,
10385 _(" Remote thread alive test "));
10390 /* Convert a thread ID to a string. Returns the string in a static
10394 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10396 static char buf[64];
10397 struct remote_state *rs = get_remote_state ();
10399 if (ptid_equal (ptid, null_ptid))
10400 return normal_pid_to_str (ptid);
10401 else if (ptid_is_pid (ptid))
10403 /* Printing an inferior target id. */
10405 /* When multi-process extensions are off, there's no way in the
10406 remote protocol to know the remote process id, if there's any
10407 at all. There's one exception --- when we're connected with
10408 target extended-remote, and we manually attached to a process
10409 with "attach PID". We don't record anywhere a flag that
10410 allows us to distinguish that case from the case of
10411 connecting with extended-remote and the stub already being
10412 attached to a process, and reporting yes to qAttached, hence
10413 no smart special casing here. */
10414 if (!remote_multi_process_p (rs))
10416 xsnprintf (buf, sizeof buf, "Remote target");
10420 return normal_pid_to_str (ptid);
10424 if (ptid_equal (magic_null_ptid, ptid))
10425 xsnprintf (buf, sizeof buf, "Thread <main>");
10426 else if (rs->extended && remote_multi_process_p (rs))
10427 if (ptid_get_lwp (ptid) == 0)
10428 return normal_pid_to_str (ptid);
10430 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10431 ptid_get_pid (ptid), ptid_get_lwp (ptid));
10433 xsnprintf (buf, sizeof buf, "Thread %ld",
10434 ptid_get_lwp (ptid));
10439 /* Get the address of the thread local variable in OBJFILE which is
10440 stored at OFFSET within the thread local storage for thread PTID. */
10443 remote_get_thread_local_address (struct target_ops *ops,
10444 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
10446 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
10448 struct remote_state *rs = get_remote_state ();
10450 char *endp = rs->buf + get_remote_packet_size ();
10451 enum packet_result result;
10453 strcpy (p, "qGetTLSAddr:");
10455 p = write_ptid (p, endp, ptid);
10457 p += hexnumstr (p, offset);
10459 p += hexnumstr (p, lm);
10463 getpkt (&rs->buf, &rs->buf_size, 0);
10464 result = packet_ok (rs->buf,
10465 &remote_protocol_packets[PACKET_qGetTLSAddr]);
10466 if (result == PACKET_OK)
10470 unpack_varlen_hex (rs->buf, &result);
10473 else if (result == PACKET_UNKNOWN)
10474 throw_error (TLS_GENERIC_ERROR,
10475 _("Remote target doesn't support qGetTLSAddr packet"));
10477 throw_error (TLS_GENERIC_ERROR,
10478 _("Remote target failed to process qGetTLSAddr request"));
10481 throw_error (TLS_GENERIC_ERROR,
10482 _("TLS not supported or disabled on this target"));
10487 /* Provide thread local base, i.e. Thread Information Block address.
10488 Returns 1 if ptid is found and thread_local_base is non zero. */
10491 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
10493 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
10495 struct remote_state *rs = get_remote_state ();
10497 char *endp = rs->buf + get_remote_packet_size ();
10498 enum packet_result result;
10500 strcpy (p, "qGetTIBAddr:");
10502 p = write_ptid (p, endp, ptid);
10506 getpkt (&rs->buf, &rs->buf_size, 0);
10507 result = packet_ok (rs->buf,
10508 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10509 if (result == PACKET_OK)
10513 unpack_varlen_hex (rs->buf, &result);
10515 *addr = (CORE_ADDR) result;
10518 else if (result == PACKET_UNKNOWN)
10519 error (_("Remote target doesn't support qGetTIBAddr packet"));
10521 error (_("Remote target failed to process qGetTIBAddr request"));
10524 error (_("qGetTIBAddr not supported or disabled on this target"));
10529 /* Support for inferring a target description based on the current
10530 architecture and the size of a 'g' packet. While the 'g' packet
10531 can have any size (since optional registers can be left off the
10532 end), some sizes are easily recognizable given knowledge of the
10533 approximate architecture. */
10535 struct remote_g_packet_guess
10538 const struct target_desc *tdesc;
10540 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10541 DEF_VEC_O(remote_g_packet_guess_s);
10543 struct remote_g_packet_data
10545 VEC(remote_g_packet_guess_s) *guesses;
10548 static struct gdbarch_data *remote_g_packet_data_handle;
10551 remote_g_packet_data_init (struct obstack *obstack)
10553 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10557 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10558 const struct target_desc *tdesc)
10560 struct remote_g_packet_data *data
10561 = ((struct remote_g_packet_data *)
10562 gdbarch_data (gdbarch, remote_g_packet_data_handle));
10563 struct remote_g_packet_guess new_guess, *guess;
10566 gdb_assert (tdesc != NULL);
10569 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10571 if (guess->bytes == bytes)
10572 internal_error (__FILE__, __LINE__,
10573 _("Duplicate g packet description added for size %d"),
10576 new_guess.bytes = bytes;
10577 new_guess.tdesc = tdesc;
10578 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10581 /* Return 1 if remote_read_description would do anything on this target
10582 and architecture, 0 otherwise. */
10585 remote_read_description_p (struct target_ops *target)
10587 struct remote_g_packet_data *data
10588 = ((struct remote_g_packet_data *)
10589 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10591 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10597 static const struct target_desc *
10598 remote_read_description (struct target_ops *target)
10600 struct remote_g_packet_data *data
10601 = ((struct remote_g_packet_data *)
10602 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
10604 /* Do not try this during initial connection, when we do not know
10605 whether there is a running but stopped thread. */
10606 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
10607 return target->beneath->to_read_description (target->beneath);
10609 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10611 struct remote_g_packet_guess *guess;
10613 int bytes = send_g_packet ();
10616 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10618 if (guess->bytes == bytes)
10619 return guess->tdesc;
10621 /* We discard the g packet. A minor optimization would be to
10622 hold on to it, and fill the register cache once we have selected
10623 an architecture, but it's too tricky to do safely. */
10626 return target->beneath->to_read_description (target->beneath);
10629 /* Remote file transfer support. This is host-initiated I/O, not
10630 target-initiated; for target-initiated, see remote-fileio.c. */
10632 /* If *LEFT is at least the length of STRING, copy STRING to
10633 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10634 decrease *LEFT. Otherwise raise an error. */
10637 remote_buffer_add_string (char **buffer, int *left, char *string)
10639 int len = strlen (string);
10642 error (_("Packet too long for target."));
10644 memcpy (*buffer, string, len);
10648 /* NUL-terminate the buffer as a convenience, if there is
10654 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10655 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10656 decrease *LEFT. Otherwise raise an error. */
10659 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10662 if (2 * len > *left)
10663 error (_("Packet too long for target."));
10665 bin2hex (bytes, *buffer, len);
10666 *buffer += 2 * len;
10669 /* NUL-terminate the buffer as a convenience, if there is
10675 /* If *LEFT is large enough, convert VALUE to hex and add it to
10676 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10677 decrease *LEFT. Otherwise raise an error. */
10680 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10682 int len = hexnumlen (value);
10685 error (_("Packet too long for target."));
10687 hexnumstr (*buffer, value);
10691 /* NUL-terminate the buffer as a convenience, if there is
10697 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10698 value, *REMOTE_ERRNO to the remote error number or zero if none
10699 was included, and *ATTACHMENT to point to the start of the annex
10700 if any. The length of the packet isn't needed here; there may
10701 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10703 Return 0 if the packet could be parsed, -1 if it could not. If
10704 -1 is returned, the other variables may not be initialized. */
10707 remote_hostio_parse_result (char *buffer, int *retcode,
10708 int *remote_errno, char **attachment)
10713 *attachment = NULL;
10715 if (buffer[0] != 'F')
10719 *retcode = strtol (&buffer[1], &p, 16);
10720 if (errno != 0 || p == &buffer[1])
10723 /* Check for ",errno". */
10727 *remote_errno = strtol (p + 1, &p2, 16);
10728 if (errno != 0 || p + 1 == p2)
10733 /* Check for ";attachment". If there is no attachment, the
10734 packet should end here. */
10737 *attachment = p + 1;
10740 else if (*p == '\0')
10746 /* Send a prepared I/O packet to the target and read its response.
10747 The prepared packet is in the global RS->BUF before this function
10748 is called, and the answer is there when we return.
10750 COMMAND_BYTES is the length of the request to send, which may include
10751 binary data. WHICH_PACKET is the packet configuration to check
10752 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10753 is set to the error number and -1 is returned. Otherwise the value
10754 returned by the function is returned.
10756 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10757 attachment is expected; an error will be reported if there's a
10758 mismatch. If one is found, *ATTACHMENT will be set to point into
10759 the packet buffer and *ATTACHMENT_LEN will be set to the
10760 attachment's length. */
10763 remote_hostio_send_command (int command_bytes, int which_packet,
10764 int *remote_errno, char **attachment,
10765 int *attachment_len)
10767 struct remote_state *rs = get_remote_state ();
10768 int ret, bytes_read;
10769 char *attachment_tmp;
10771 if (!rs->remote_desc
10772 || packet_support (which_packet) == PACKET_DISABLE)
10774 *remote_errno = FILEIO_ENOSYS;
10778 putpkt_binary (rs->buf, command_bytes);
10779 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10781 /* If it timed out, something is wrong. Don't try to parse the
10783 if (bytes_read < 0)
10785 *remote_errno = FILEIO_EINVAL;
10789 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10792 *remote_errno = FILEIO_EINVAL;
10794 case PACKET_UNKNOWN:
10795 *remote_errno = FILEIO_ENOSYS;
10801 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10804 *remote_errno = FILEIO_EINVAL;
10808 /* Make sure we saw an attachment if and only if we expected one. */
10809 if ((attachment_tmp == NULL && attachment != NULL)
10810 || (attachment_tmp != NULL && attachment == NULL))
10812 *remote_errno = FILEIO_EINVAL;
10816 /* If an attachment was found, it must point into the packet buffer;
10817 work out how many bytes there were. */
10818 if (attachment_tmp != NULL)
10820 *attachment = attachment_tmp;
10821 *attachment_len = bytes_read - (*attachment - rs->buf);
10827 /* Invalidate the readahead cache. */
10830 readahead_cache_invalidate (void)
10832 struct remote_state *rs = get_remote_state ();
10834 rs->readahead_cache.fd = -1;
10837 /* Invalidate the readahead cache if it is holding data for FD. */
10840 readahead_cache_invalidate_fd (int fd)
10842 struct remote_state *rs = get_remote_state ();
10844 if (rs->readahead_cache.fd == fd)
10845 rs->readahead_cache.fd = -1;
10848 /* Set the filesystem remote_hostio functions that take FILENAME
10849 arguments will use. Return 0 on success, or -1 if an error
10850 occurs (and set *REMOTE_ERRNO). */
10853 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10855 struct remote_state *rs = get_remote_state ();
10856 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10858 int left = get_remote_packet_size () - 1;
10862 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10865 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10868 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10870 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10871 remote_buffer_add_string (&p, &left, arg);
10873 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10874 remote_errno, NULL, NULL);
10876 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10880 rs->fs_pid = required_pid;
10885 /* Implementation of to_fileio_open. */
10888 remote_hostio_open (struct target_ops *self,
10889 struct inferior *inf, const char *filename,
10890 int flags, int mode, int warn_if_slow,
10893 struct remote_state *rs = get_remote_state ();
10895 int left = get_remote_packet_size () - 1;
10899 static int warning_issued = 0;
10901 printf_unfiltered (_("Reading %s from remote target...\n"),
10904 if (!warning_issued)
10906 warning (_("File transfers from remote targets can be slow."
10907 " Use \"set sysroot\" to access files locally"
10909 warning_issued = 1;
10913 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10916 remote_buffer_add_string (&p, &left, "vFile:open:");
10918 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10919 strlen (filename));
10920 remote_buffer_add_string (&p, &left, ",");
10922 remote_buffer_add_int (&p, &left, flags);
10923 remote_buffer_add_string (&p, &left, ",");
10925 remote_buffer_add_int (&p, &left, mode);
10927 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10928 remote_errno, NULL, NULL);
10931 /* Implementation of to_fileio_pwrite. */
10934 remote_hostio_pwrite (struct target_ops *self,
10935 int fd, const gdb_byte *write_buf, int len,
10936 ULONGEST offset, int *remote_errno)
10938 struct remote_state *rs = get_remote_state ();
10940 int left = get_remote_packet_size ();
10943 readahead_cache_invalidate_fd (fd);
10945 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10947 remote_buffer_add_int (&p, &left, fd);
10948 remote_buffer_add_string (&p, &left, ",");
10950 remote_buffer_add_int (&p, &left, offset);
10951 remote_buffer_add_string (&p, &left, ",");
10953 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
10954 get_remote_packet_size () - (p - rs->buf));
10956 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10957 remote_errno, NULL, NULL);
10960 /* Helper for the implementation of to_fileio_pread. Read the file
10961 from the remote side with vFile:pread. */
10964 remote_hostio_pread_vFile (struct target_ops *self,
10965 int fd, gdb_byte *read_buf, int len,
10966 ULONGEST offset, int *remote_errno)
10968 struct remote_state *rs = get_remote_state ();
10971 int left = get_remote_packet_size ();
10972 int ret, attachment_len;
10975 remote_buffer_add_string (&p, &left, "vFile:pread:");
10977 remote_buffer_add_int (&p, &left, fd);
10978 remote_buffer_add_string (&p, &left, ",");
10980 remote_buffer_add_int (&p, &left, len);
10981 remote_buffer_add_string (&p, &left, ",");
10983 remote_buffer_add_int (&p, &left, offset);
10985 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10986 remote_errno, &attachment,
10992 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10994 if (read_len != ret)
10995 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11000 /* Serve pread from the readahead cache. Returns number of bytes
11001 read, or 0 if the request can't be served from the cache. */
11004 remote_hostio_pread_from_cache (struct remote_state *rs,
11005 int fd, gdb_byte *read_buf, size_t len,
11008 struct readahead_cache *cache = &rs->readahead_cache;
11010 if (cache->fd == fd
11011 && cache->offset <= offset
11012 && offset < cache->offset + cache->bufsize)
11014 ULONGEST max = cache->offset + cache->bufsize;
11016 if (offset + len > max)
11017 len = max - offset;
11019 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11026 /* Implementation of to_fileio_pread. */
11029 remote_hostio_pread (struct target_ops *self,
11030 int fd, gdb_byte *read_buf, int len,
11031 ULONGEST offset, int *remote_errno)
11034 struct remote_state *rs = get_remote_state ();
11035 struct readahead_cache *cache = &rs->readahead_cache;
11037 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11040 cache->hit_count++;
11043 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11044 pulongest (cache->hit_count));
11048 cache->miss_count++;
11050 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11051 pulongest (cache->miss_count));
11054 cache->offset = offset;
11055 cache->bufsize = get_remote_packet_size ();
11056 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11058 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11059 cache->offset, remote_errno);
11062 readahead_cache_invalidate_fd (fd);
11066 cache->bufsize = ret;
11067 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11070 /* Implementation of to_fileio_close. */
11073 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11075 struct remote_state *rs = get_remote_state ();
11077 int left = get_remote_packet_size () - 1;
11079 readahead_cache_invalidate_fd (fd);
11081 remote_buffer_add_string (&p, &left, "vFile:close:");
11083 remote_buffer_add_int (&p, &left, fd);
11085 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11086 remote_errno, NULL, NULL);
11089 /* Implementation of to_fileio_unlink. */
11092 remote_hostio_unlink (struct target_ops *self,
11093 struct inferior *inf, const char *filename,
11096 struct remote_state *rs = get_remote_state ();
11098 int left = get_remote_packet_size () - 1;
11100 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11103 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11105 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11106 strlen (filename));
11108 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11109 remote_errno, NULL, NULL);
11112 /* Implementation of to_fileio_readlink. */
11115 remote_hostio_readlink (struct target_ops *self,
11116 struct inferior *inf, const char *filename,
11119 struct remote_state *rs = get_remote_state ();
11122 int left = get_remote_packet_size ();
11123 int len, attachment_len;
11127 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11130 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11132 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11133 strlen (filename));
11135 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11136 remote_errno, &attachment,
11142 ret = (char *) xmalloc (len + 1);
11144 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11145 (gdb_byte *) ret, len);
11146 if (read_len != len)
11147 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11153 /* Implementation of to_fileio_fstat. */
11156 remote_hostio_fstat (struct target_ops *self,
11157 int fd, struct stat *st,
11160 struct remote_state *rs = get_remote_state ();
11162 int left = get_remote_packet_size ();
11163 int attachment_len, ret;
11165 struct fio_stat fst;
11168 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11170 remote_buffer_add_int (&p, &left, fd);
11172 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11173 remote_errno, &attachment,
11177 if (*remote_errno != FILEIO_ENOSYS)
11180 /* Strictly we should return -1, ENOSYS here, but when
11181 "set sysroot remote:" was implemented in August 2008
11182 BFD's need for a stat function was sidestepped with
11183 this hack. This was not remedied until March 2015
11184 so we retain the previous behavior to avoid breaking
11187 Note that the memset is a March 2015 addition; older
11188 GDBs set st_size *and nothing else* so the structure
11189 would have garbage in all other fields. This might
11190 break something but retaining the previous behavior
11191 here would be just too wrong. */
11193 memset (st, 0, sizeof (struct stat));
11194 st->st_size = INT_MAX;
11198 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11199 (gdb_byte *) &fst, sizeof (fst));
11201 if (read_len != ret)
11202 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11204 if (read_len != sizeof (fst))
11205 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11206 read_len, (int) sizeof (fst));
11208 remote_fileio_to_host_stat (&fst, st);
11213 /* Implementation of to_filesystem_is_local. */
11216 remote_filesystem_is_local (struct target_ops *self)
11218 /* Valgrind GDB presents itself as a remote target but works
11219 on the local filesystem: it does not implement remote get
11220 and users are not expected to set a sysroot. To handle
11221 this case we treat the remote filesystem as local if the
11222 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11223 does not support vFile:open. */
11224 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11226 enum packet_support ps = packet_support (PACKET_vFile_open);
11228 if (ps == PACKET_SUPPORT_UNKNOWN)
11230 int fd, remote_errno;
11232 /* Try opening a file to probe support. The supplied
11233 filename is irrelevant, we only care about whether
11234 the stub recognizes the packet or not. */
11235 fd = remote_hostio_open (self, NULL, "just probing",
11236 FILEIO_O_RDONLY, 0700, 0,
11240 remote_hostio_close (self, fd, &remote_errno);
11242 ps = packet_support (PACKET_vFile_open);
11245 if (ps == PACKET_DISABLE)
11247 static int warning_issued = 0;
11249 if (!warning_issued)
11251 warning (_("remote target does not support file"
11252 " transfer, attempting to access files"
11253 " from local filesystem."));
11254 warning_issued = 1;
11265 remote_fileio_errno_to_host (int errnum)
11271 case FILEIO_ENOENT:
11279 case FILEIO_EACCES:
11281 case FILEIO_EFAULT:
11285 case FILEIO_EEXIST:
11287 case FILEIO_ENODEV:
11289 case FILEIO_ENOTDIR:
11291 case FILEIO_EISDIR:
11293 case FILEIO_EINVAL:
11295 case FILEIO_ENFILE:
11297 case FILEIO_EMFILE:
11301 case FILEIO_ENOSPC:
11303 case FILEIO_ESPIPE:
11307 case FILEIO_ENOSYS:
11309 case FILEIO_ENAMETOOLONG:
11310 return ENAMETOOLONG;
11316 remote_hostio_error (int errnum)
11318 int host_error = remote_fileio_errno_to_host (errnum);
11320 if (host_error == -1)
11321 error (_("Unknown remote I/O error %d"), errnum);
11323 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11327 remote_hostio_close_cleanup (void *opaque)
11329 int fd = *(int *) opaque;
11332 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11336 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11338 struct cleanup *back_to, *close_cleanup;
11339 int retcode, fd, remote_errno, bytes, io_size;
11342 int bytes_in_buffer;
11345 struct remote_state *rs = get_remote_state ();
11347 if (!rs->remote_desc)
11348 error (_("command can only be used with remote target"));
11350 file = gdb_fopen_cloexec (local_file, "rb");
11352 perror_with_name (local_file);
11353 back_to = make_cleanup_fclose (file);
11355 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11356 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11358 0700, 0, &remote_errno);
11360 remote_hostio_error (remote_errno);
11362 /* Send up to this many bytes at once. They won't all fit in the
11363 remote packet limit, so we'll transfer slightly fewer. */
11364 io_size = get_remote_packet_size ();
11365 buffer = (gdb_byte *) xmalloc (io_size);
11366 make_cleanup (xfree, buffer);
11368 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11370 bytes_in_buffer = 0;
11373 while (bytes_in_buffer || !saw_eof)
11377 bytes = fread (buffer + bytes_in_buffer, 1,
11378 io_size - bytes_in_buffer,
11383 error (_("Error reading %s."), local_file);
11386 /* EOF. Unless there is something still in the
11387 buffer from the last iteration, we are done. */
11389 if (bytes_in_buffer == 0)
11397 bytes += bytes_in_buffer;
11398 bytes_in_buffer = 0;
11400 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11402 offset, &remote_errno);
11405 remote_hostio_error (remote_errno);
11406 else if (retcode == 0)
11407 error (_("Remote write of %d bytes returned 0!"), bytes);
11408 else if (retcode < bytes)
11410 /* Short write. Save the rest of the read data for the next
11412 bytes_in_buffer = bytes - retcode;
11413 memmove (buffer, buffer + retcode, bytes_in_buffer);
11419 discard_cleanups (close_cleanup);
11420 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11421 remote_hostio_error (remote_errno);
11424 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11425 do_cleanups (back_to);
11429 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11431 struct cleanup *back_to, *close_cleanup;
11432 int fd, remote_errno, bytes, io_size;
11436 struct remote_state *rs = get_remote_state ();
11438 if (!rs->remote_desc)
11439 error (_("command can only be used with remote target"));
11441 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11442 remote_file, FILEIO_O_RDONLY, 0, 0,
11445 remote_hostio_error (remote_errno);
11447 file = gdb_fopen_cloexec (local_file, "wb");
11449 perror_with_name (local_file);
11450 back_to = make_cleanup_fclose (file);
11452 /* Send up to this many bytes at once. They won't all fit in the
11453 remote packet limit, so we'll transfer slightly fewer. */
11454 io_size = get_remote_packet_size ();
11455 buffer = (gdb_byte *) xmalloc (io_size);
11456 make_cleanup (xfree, buffer);
11458 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11463 bytes = remote_hostio_pread (find_target_at (process_stratum),
11464 fd, buffer, io_size, offset, &remote_errno);
11466 /* Success, but no bytes, means end-of-file. */
11469 remote_hostio_error (remote_errno);
11473 bytes = fwrite (buffer, 1, bytes, file);
11475 perror_with_name (local_file);
11478 discard_cleanups (close_cleanup);
11479 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11480 remote_hostio_error (remote_errno);
11483 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11484 do_cleanups (back_to);
11488 remote_file_delete (const char *remote_file, int from_tty)
11490 int retcode, remote_errno;
11491 struct remote_state *rs = get_remote_state ();
11493 if (!rs->remote_desc)
11494 error (_("command can only be used with remote target"));
11496 retcode = remote_hostio_unlink (find_target_at (process_stratum),
11497 NULL, remote_file, &remote_errno);
11499 remote_hostio_error (remote_errno);
11502 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11506 remote_put_command (char *args, int from_tty)
11508 struct cleanup *back_to;
11512 error_no_arg (_("file to put"));
11514 argv = gdb_buildargv (args);
11515 back_to = make_cleanup_freeargv (argv);
11516 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11517 error (_("Invalid parameters to remote put"));
11519 remote_file_put (argv[0], argv[1], from_tty);
11521 do_cleanups (back_to);
11525 remote_get_command (char *args, int from_tty)
11527 struct cleanup *back_to;
11531 error_no_arg (_("file to get"));
11533 argv = gdb_buildargv (args);
11534 back_to = make_cleanup_freeargv (argv);
11535 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11536 error (_("Invalid parameters to remote get"));
11538 remote_file_get (argv[0], argv[1], from_tty);
11540 do_cleanups (back_to);
11544 remote_delete_command (char *args, int from_tty)
11546 struct cleanup *back_to;
11550 error_no_arg (_("file to delete"));
11552 argv = gdb_buildargv (args);
11553 back_to = make_cleanup_freeargv (argv);
11554 if (argv[0] == NULL || argv[1] != NULL)
11555 error (_("Invalid parameters to remote delete"));
11557 remote_file_delete (argv[0], from_tty);
11559 do_cleanups (back_to);
11563 remote_command (char *args, int from_tty)
11565 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
11569 remote_can_execute_reverse (struct target_ops *self)
11571 if (packet_support (PACKET_bs) == PACKET_ENABLE
11572 || packet_support (PACKET_bc) == PACKET_ENABLE)
11579 remote_supports_non_stop (struct target_ops *self)
11585 remote_supports_disable_randomization (struct target_ops *self)
11587 /* Only supported in extended mode. */
11592 remote_supports_multi_process (struct target_ops *self)
11594 struct remote_state *rs = get_remote_state ();
11596 /* Only extended-remote handles being attached to multiple
11597 processes, even though plain remote can use the multi-process
11598 thread id extensions, so that GDB knows the target process's
11600 return rs->extended && remote_multi_process_p (rs);
11604 remote_supports_cond_tracepoints (void)
11606 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
11610 remote_supports_cond_breakpoints (struct target_ops *self)
11612 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
11616 remote_supports_fast_tracepoints (void)
11618 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
11622 remote_supports_static_tracepoints (void)
11624 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
11628 remote_supports_install_in_trace (void)
11630 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
11634 remote_supports_enable_disable_tracepoint (struct target_ops *self)
11636 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11641 remote_supports_string_tracing (struct target_ops *self)
11643 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
11647 remote_can_run_breakpoint_commands (struct target_ops *self)
11649 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
11653 remote_trace_init (struct target_ops *self)
11656 remote_get_noisy_reply (&target_buf, &target_buf_size);
11657 if (strcmp (target_buf, "OK") != 0)
11658 error (_("Target does not support this command."));
11661 static void free_actions_list (char **actions_list);
11662 static void free_actions_list_cleanup_wrapper (void *);
11664 free_actions_list_cleanup_wrapper (void *al)
11666 free_actions_list ((char **) al);
11670 free_actions_list (char **actions_list)
11674 if (actions_list == 0)
11677 for (ndx = 0; actions_list[ndx]; ndx++)
11678 xfree (actions_list[ndx]);
11680 xfree (actions_list);
11683 /* Recursive routine to walk through command list including loops, and
11684 download packets for each command. */
11687 remote_download_command_source (int num, ULONGEST addr,
11688 struct command_line *cmds)
11690 struct remote_state *rs = get_remote_state ();
11691 struct command_line *cmd;
11693 for (cmd = cmds; cmd; cmd = cmd->next)
11695 QUIT; /* Allow user to bail out with ^C. */
11696 strcpy (rs->buf, "QTDPsrc:");
11697 encode_source_string (num, addr, "cmd", cmd->line,
11698 rs->buf + strlen (rs->buf),
11699 rs->buf_size - strlen (rs->buf));
11701 remote_get_noisy_reply (&target_buf, &target_buf_size);
11702 if (strcmp (target_buf, "OK"))
11703 warning (_("Target does not support source download."));
11705 if (cmd->control_type == while_control
11706 || cmd->control_type == while_stepping_control)
11708 remote_download_command_source (num, addr, *cmd->body_list);
11710 QUIT; /* Allow user to bail out with ^C. */
11711 strcpy (rs->buf, "QTDPsrc:");
11712 encode_source_string (num, addr, "cmd", "end",
11713 rs->buf + strlen (rs->buf),
11714 rs->buf_size - strlen (rs->buf));
11716 remote_get_noisy_reply (&target_buf, &target_buf_size);
11717 if (strcmp (target_buf, "OK"))
11718 warning (_("Target does not support source download."));
11724 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
11726 #define BUF_SIZE 2048
11730 char buf[BUF_SIZE];
11731 char **tdp_actions;
11732 char **stepping_actions;
11734 struct cleanup *old_chain = NULL;
11735 struct agent_expr *aexpr;
11736 struct cleanup *aexpr_chain = NULL;
11738 struct breakpoint *b = loc->owner;
11739 struct tracepoint *t = (struct tracepoint *) b;
11741 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
11742 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11744 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11747 tpaddr = loc->address;
11748 sprintf_vma (addrbuf, tpaddr);
11749 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11750 addrbuf, /* address */
11751 (b->enable_state == bp_enabled ? 'E' : 'D'),
11752 t->step_count, t->pass_count);
11753 /* Fast tracepoints are mostly handled by the target, but we can
11754 tell the target how big of an instruction block should be moved
11756 if (b->type == bp_fast_tracepoint)
11758 /* Only test for support at download time; we may not know
11759 target capabilities at definition time. */
11760 if (remote_supports_fast_tracepoints ())
11762 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11764 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
11765 gdb_insn_length (loc->gdbarch, tpaddr));
11767 /* If it passed validation at definition but fails now,
11768 something is very wrong. */
11769 internal_error (__FILE__, __LINE__,
11770 _("Fast tracepoint not "
11771 "valid during download"));
11774 /* Fast tracepoints are functionally identical to regular
11775 tracepoints, so don't take lack of support as a reason to
11776 give up on the trace run. */
11777 warning (_("Target does not support fast tracepoints, "
11778 "downloading %d as regular tracepoint"), b->number);
11780 else if (b->type == bp_static_tracepoint)
11782 /* Only test for support at download time; we may not know
11783 target capabilities at definition time. */
11784 if (remote_supports_static_tracepoints ())
11786 struct static_tracepoint_marker marker;
11788 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11789 strcat (buf, ":S");
11791 error (_("Static tracepoint not valid during download"));
11794 /* Fast tracepoints are functionally identical to regular
11795 tracepoints, so don't take lack of support as a reason
11796 to give up on the trace run. */
11797 error (_("Target does not support static tracepoints"));
11799 /* If the tracepoint has a conditional, make it into an agent
11800 expression and append to the definition. */
11803 /* Only test support at download time, we may not know target
11804 capabilities at definition time. */
11805 if (remote_supports_cond_tracepoints ())
11807 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11808 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11809 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11811 pkt = buf + strlen (buf);
11812 for (ndx = 0; ndx < aexpr->len; ++ndx)
11813 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11815 do_cleanups (aexpr_chain);
11818 warning (_("Target does not support conditional tracepoints, "
11819 "ignoring tp %d cond"), b->number);
11822 if (b->commands || *default_collect)
11825 remote_get_noisy_reply (&target_buf, &target_buf_size);
11826 if (strcmp (target_buf, "OK"))
11827 error (_("Target does not support tracepoints."));
11829 /* do_single_steps (t); */
11832 for (ndx = 0; tdp_actions[ndx]; ndx++)
11834 QUIT; /* Allow user to bail out with ^C. */
11835 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11836 b->number, addrbuf, /* address */
11838 ((tdp_actions[ndx + 1] || stepping_actions)
11841 remote_get_noisy_reply (&target_buf,
11843 if (strcmp (target_buf, "OK"))
11844 error (_("Error on target while setting tracepoints."));
11847 if (stepping_actions)
11849 for (ndx = 0; stepping_actions[ndx]; ndx++)
11851 QUIT; /* Allow user to bail out with ^C. */
11852 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11853 b->number, addrbuf, /* address */
11854 ((ndx == 0) ? "S" : ""),
11855 stepping_actions[ndx],
11856 (stepping_actions[ndx + 1] ? "-" : ""));
11858 remote_get_noisy_reply (&target_buf,
11860 if (strcmp (target_buf, "OK"))
11861 error (_("Error on target while setting tracepoints."));
11865 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11867 if (b->location != NULL)
11869 strcpy (buf, "QTDPsrc:");
11870 encode_source_string (b->number, loc->address, "at",
11871 event_location_to_string (b->location),
11872 buf + strlen (buf), 2048 - strlen (buf));
11874 remote_get_noisy_reply (&target_buf, &target_buf_size);
11875 if (strcmp (target_buf, "OK"))
11876 warning (_("Target does not support source download."));
11878 if (b->cond_string)
11880 strcpy (buf, "QTDPsrc:");
11881 encode_source_string (b->number, loc->address,
11882 "cond", b->cond_string, buf + strlen (buf),
11883 2048 - strlen (buf));
11885 remote_get_noisy_reply (&target_buf, &target_buf_size);
11886 if (strcmp (target_buf, "OK"))
11887 warning (_("Target does not support source download."));
11889 remote_download_command_source (b->number, loc->address,
11890 breakpoint_commands (b));
11893 do_cleanups (old_chain);
11897 remote_can_download_tracepoint (struct target_ops *self)
11899 struct remote_state *rs = get_remote_state ();
11900 struct trace_status *ts;
11903 /* Don't try to install tracepoints until we've relocated our
11904 symbols, and fetched and merged the target's tracepoint list with
11906 if (rs->starting_up)
11909 ts = current_trace_status ();
11910 status = remote_get_trace_status (self, ts);
11912 if (status == -1 || !ts->running_known || !ts->running)
11915 /* If we are in a tracing experiment, but remote stub doesn't support
11916 installing tracepoint in trace, we have to return. */
11917 if (!remote_supports_install_in_trace ())
11925 remote_download_trace_state_variable (struct target_ops *self,
11926 struct trace_state_variable *tsv)
11928 struct remote_state *rs = get_remote_state ();
11931 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11932 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11934 p = rs->buf + strlen (rs->buf);
11935 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11936 error (_("Trace state variable name too long for tsv definition packet"));
11937 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11940 remote_get_noisy_reply (&target_buf, &target_buf_size);
11941 if (*target_buf == '\0')
11942 error (_("Target does not support this command."));
11943 if (strcmp (target_buf, "OK") != 0)
11944 error (_("Error on target while downloading trace state variable."));
11948 remote_enable_tracepoint (struct target_ops *self,
11949 struct bp_location *location)
11951 struct remote_state *rs = get_remote_state ();
11954 sprintf_vma (addr_buf, location->address);
11955 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11956 location->owner->number, addr_buf);
11958 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11959 if (*rs->buf == '\0')
11960 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11961 if (strcmp (rs->buf, "OK") != 0)
11962 error (_("Error on target while enabling tracepoint."));
11966 remote_disable_tracepoint (struct target_ops *self,
11967 struct bp_location *location)
11969 struct remote_state *rs = get_remote_state ();
11972 sprintf_vma (addr_buf, location->address);
11973 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11974 location->owner->number, addr_buf);
11976 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11977 if (*rs->buf == '\0')
11978 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11979 if (strcmp (rs->buf, "OK") != 0)
11980 error (_("Error on target while disabling tracepoint."));
11984 remote_trace_set_readonly_regions (struct target_ops *self)
11988 bfd_size_type size;
11994 return; /* No information to give. */
11996 strcpy (target_buf, "QTro");
11997 offset = strlen (target_buf);
11998 for (s = exec_bfd->sections; s; s = s->next)
12000 char tmp1[40], tmp2[40];
12003 if ((s->flags & SEC_LOAD) == 0 ||
12004 /* (s->flags & SEC_CODE) == 0 || */
12005 (s->flags & SEC_READONLY) == 0)
12009 vma = bfd_get_section_vma (abfd, s);
12010 size = bfd_get_section_size (s);
12011 sprintf_vma (tmp1, vma);
12012 sprintf_vma (tmp2, vma + size);
12013 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12014 if (offset + sec_length + 1 > target_buf_size)
12016 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12018 Too many sections for read-only sections definition packet."));
12021 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12023 offset += sec_length;
12027 putpkt (target_buf);
12028 getpkt (&target_buf, &target_buf_size, 0);
12033 remote_trace_start (struct target_ops *self)
12035 putpkt ("QTStart");
12036 remote_get_noisy_reply (&target_buf, &target_buf_size);
12037 if (*target_buf == '\0')
12038 error (_("Target does not support this command."));
12039 if (strcmp (target_buf, "OK") != 0)
12040 error (_("Bogus reply from target: %s"), target_buf);
12044 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12046 /* Initialize it just to avoid a GCC false warning. */
12048 /* FIXME we need to get register block size some other way. */
12049 extern int trace_regblock_size;
12050 enum packet_result result;
12052 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12055 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12057 putpkt ("qTStatus");
12061 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12063 CATCH (ex, RETURN_MASK_ERROR)
12065 if (ex.error != TARGET_CLOSE_ERROR)
12067 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12070 throw_exception (ex);
12074 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12076 /* If the remote target doesn't do tracing, flag it. */
12077 if (result == PACKET_UNKNOWN)
12080 /* We're working with a live target. */
12081 ts->filename = NULL;
12084 error (_("Bogus trace status reply from target: %s"), target_buf);
12086 /* Function 'parse_trace_status' sets default value of each field of
12087 'ts' at first, so we don't have to do it here. */
12088 parse_trace_status (p, ts);
12090 return ts->running;
12094 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12095 struct uploaded_tp *utp)
12097 struct remote_state *rs = get_remote_state ();
12099 struct bp_location *loc;
12100 struct tracepoint *tp = (struct tracepoint *) bp;
12101 size_t size = get_remote_packet_size ();
12105 tp->base.hit_count = 0;
12106 tp->traceframe_usage = 0;
12107 for (loc = tp->base.loc; loc; loc = loc->next)
12109 /* If the tracepoint was never downloaded, don't go asking for
12111 if (tp->number_on_target == 0)
12113 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12114 phex_nz (loc->address, 0));
12116 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12117 if (reply && *reply)
12120 parse_tracepoint_status (reply + 1, bp, utp);
12126 utp->hit_count = 0;
12127 utp->traceframe_usage = 0;
12128 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12129 phex_nz (utp->addr, 0));
12131 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12132 if (reply && *reply)
12135 parse_tracepoint_status (reply + 1, bp, utp);
12141 remote_trace_stop (struct target_ops *self)
12144 remote_get_noisy_reply (&target_buf, &target_buf_size);
12145 if (*target_buf == '\0')
12146 error (_("Target does not support this command."));
12147 if (strcmp (target_buf, "OK") != 0)
12148 error (_("Bogus reply from target: %s"), target_buf);
12152 remote_trace_find (struct target_ops *self,
12153 enum trace_find_type type, int num,
12154 CORE_ADDR addr1, CORE_ADDR addr2,
12157 struct remote_state *rs = get_remote_state ();
12158 char *endbuf = rs->buf + get_remote_packet_size ();
12160 int target_frameno = -1, target_tracept = -1;
12162 /* Lookups other than by absolute frame number depend on the current
12163 trace selected, so make sure it is correct on the remote end
12165 if (type != tfind_number)
12166 set_remote_traceframe ();
12169 strcpy (p, "QTFrame:");
12170 p = strchr (p, '\0');
12174 xsnprintf (p, endbuf - p, "%x", num);
12177 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12180 xsnprintf (p, endbuf - p, "tdp:%x", num);
12183 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12184 phex_nz (addr2, 0));
12186 case tfind_outside:
12187 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12188 phex_nz (addr2, 0));
12191 error (_("Unknown trace find type %d"), type);
12195 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12196 if (*reply == '\0')
12197 error (_("Target does not support this command."));
12199 while (reply && *reply)
12204 target_frameno = (int) strtol (p, &reply, 16);
12206 error (_("Unable to parse trace frame number"));
12207 /* Don't update our remote traceframe number cache on failure
12208 to select a remote traceframe. */
12209 if (target_frameno == -1)
12214 target_tracept = (int) strtol (p, &reply, 16);
12216 error (_("Unable to parse tracepoint number"));
12218 case 'O': /* "OK"? */
12219 if (reply[1] == 'K' && reply[2] == '\0')
12222 error (_("Bogus reply from target: %s"), reply);
12225 error (_("Bogus reply from target: %s"), reply);
12228 *tpp = target_tracept;
12230 rs->remote_traceframe_number = target_frameno;
12231 return target_frameno;
12235 remote_get_trace_state_variable_value (struct target_ops *self,
12236 int tsvnum, LONGEST *val)
12238 struct remote_state *rs = get_remote_state ();
12242 set_remote_traceframe ();
12244 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12246 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12247 if (reply && *reply)
12251 unpack_varlen_hex (reply + 1, &uval);
12252 *val = (LONGEST) uval;
12260 remote_save_trace_data (struct target_ops *self, const char *filename)
12262 struct remote_state *rs = get_remote_state ();
12266 strcpy (p, "QTSave:");
12268 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12269 error (_("Remote file name too long for trace save packet"));
12270 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12273 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12274 if (*reply == '\0')
12275 error (_("Target does not support this command."));
12276 if (strcmp (reply, "OK") != 0)
12277 error (_("Bogus reply from target: %s"), reply);
12281 /* This is basically a memory transfer, but needs to be its own packet
12282 because we don't know how the target actually organizes its trace
12283 memory, plus we want to be able to ask for as much as possible, but
12284 not be unhappy if we don't get as much as we ask for. */
12287 remote_get_raw_trace_data (struct target_ops *self,
12288 gdb_byte *buf, ULONGEST offset, LONGEST len)
12290 struct remote_state *rs = get_remote_state ();
12296 strcpy (p, "qTBuffer:");
12298 p += hexnumstr (p, offset);
12300 p += hexnumstr (p, len);
12304 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12305 if (reply && *reply)
12307 /* 'l' by itself means we're at the end of the buffer and
12308 there is nothing more to get. */
12312 /* Convert the reply into binary. Limit the number of bytes to
12313 convert according to our passed-in buffer size, rather than
12314 what was returned in the packet; if the target is
12315 unexpectedly generous and gives us a bigger reply than we
12316 asked for, we don't want to crash. */
12317 rslt = hex2bin (target_buf, buf, len);
12321 /* Something went wrong, flag as an error. */
12326 remote_set_disconnected_tracing (struct target_ops *self, int val)
12328 struct remote_state *rs = get_remote_state ();
12330 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12334 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12336 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12337 if (*reply == '\0')
12338 error (_("Target does not support this command."));
12339 if (strcmp (reply, "OK") != 0)
12340 error (_("Bogus reply from target: %s"), reply);
12343 warning (_("Target does not support disconnected tracing."));
12347 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12349 struct thread_info *info = find_thread_ptid (ptid);
12351 if (info && info->priv)
12352 return info->priv->core;
12357 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12359 struct remote_state *rs = get_remote_state ();
12362 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12364 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12365 if (*reply == '\0')
12366 error (_("Target does not support this command."));
12367 if (strcmp (reply, "OK") != 0)
12368 error (_("Bogus reply from target: %s"), reply);
12371 static struct traceframe_info *
12372 remote_traceframe_info (struct target_ops *self)
12376 text = target_read_stralloc (¤t_target,
12377 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12380 struct traceframe_info *info;
12381 struct cleanup *back_to = make_cleanup (xfree, text);
12383 info = parse_traceframe_info (text);
12384 do_cleanups (back_to);
12391 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12392 instruction on which a fast tracepoint may be placed. Returns -1
12393 if the packet is not supported, and 0 if the minimum instruction
12394 length is unknown. */
12397 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12399 struct remote_state *rs = get_remote_state ();
12402 /* If we're not debugging a process yet, the IPA can't be
12404 if (!target_has_execution)
12407 /* Make sure the remote is pointing at the right process. */
12408 set_general_process ();
12410 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12412 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12413 if (*reply == '\0')
12417 ULONGEST min_insn_len;
12419 unpack_varlen_hex (reply, &min_insn_len);
12421 return (int) min_insn_len;
12426 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12428 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12430 struct remote_state *rs = get_remote_state ();
12431 char *buf = rs->buf;
12432 char *endbuf = rs->buf + get_remote_packet_size ();
12433 enum packet_result result;
12435 gdb_assert (val >= 0 || val == -1);
12436 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12437 /* Send -1 as literal "-1" to avoid host size dependency. */
12441 buf += hexnumstr (buf, (ULONGEST) -val);
12444 buf += hexnumstr (buf, (ULONGEST) val);
12447 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12448 result = packet_ok (rs->buf,
12449 &remote_protocol_packets[PACKET_QTBuffer_size]);
12451 if (result != PACKET_OK)
12452 warning (_("Bogus reply from target: %s"), rs->buf);
12457 remote_set_trace_notes (struct target_ops *self,
12458 const char *user, const char *notes,
12459 const char *stop_notes)
12461 struct remote_state *rs = get_remote_state ();
12463 char *buf = rs->buf;
12464 char *endbuf = rs->buf + get_remote_packet_size ();
12467 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12470 buf += xsnprintf (buf, endbuf - buf, "user:");
12471 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12477 buf += xsnprintf (buf, endbuf - buf, "notes:");
12478 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
12484 buf += xsnprintf (buf, endbuf - buf, "tstop:");
12485 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
12489 /* Ensure the buffer is terminated. */
12493 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12494 if (*reply == '\0')
12497 if (strcmp (reply, "OK") != 0)
12498 error (_("Bogus reply from target: %s"), reply);
12504 remote_use_agent (struct target_ops *self, int use)
12506 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
12508 struct remote_state *rs = get_remote_state ();
12510 /* If the stub supports QAgent. */
12511 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
12513 getpkt (&rs->buf, &rs->buf_size, 0);
12515 if (strcmp (rs->buf, "OK") == 0)
12526 remote_can_use_agent (struct target_ops *self)
12528 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
12531 struct btrace_target_info
12533 /* The ptid of the traced thread. */
12536 /* The obtained branch trace configuration. */
12537 struct btrace_config conf;
12540 /* Reset our idea of our target's btrace configuration. */
12543 remote_btrace_reset (void)
12545 struct remote_state *rs = get_remote_state ();
12547 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12550 /* Check whether the target supports branch tracing. */
12553 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
12555 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
12557 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
12562 case BTRACE_FORMAT_NONE:
12565 case BTRACE_FORMAT_BTS:
12566 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
12568 case BTRACE_FORMAT_PT:
12569 /* The trace is decoded on the host. Even if our target supports it,
12570 we still need to have libipt to decode the trace. */
12571 #if defined (HAVE_LIBIPT)
12572 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12573 #else /* !defined (HAVE_LIBIPT) */
12575 #endif /* !defined (HAVE_LIBIPT) */
12578 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
12581 /* Synchronize the configuration with the target. */
12584 btrace_sync_conf (const struct btrace_config *conf)
12586 struct packet_config *packet;
12587 struct remote_state *rs;
12588 char *buf, *pos, *endbuf;
12590 rs = get_remote_state ();
12592 endbuf = buf + get_remote_packet_size ();
12594 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12595 if (packet_config_support (packet) == PACKET_ENABLE
12596 && conf->bts.size != rs->btrace_config.bts.size)
12599 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12603 getpkt (&buf, &rs->buf_size, 0);
12605 if (packet_ok (buf, packet) == PACKET_ERROR)
12607 if (buf[0] == 'E' && buf[1] == '.')
12608 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12610 error (_("Failed to configure the BTS buffer size."));
12613 rs->btrace_config.bts.size = conf->bts.size;
12616 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12617 if (packet_config_support (packet) == PACKET_ENABLE
12618 && conf->pt.size != rs->btrace_config.pt.size)
12621 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12625 getpkt (&buf, &rs->buf_size, 0);
12627 if (packet_ok (buf, packet) == PACKET_ERROR)
12629 if (buf[0] == 'E' && buf[1] == '.')
12630 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12632 error (_("Failed to configure the trace buffer size."));
12635 rs->btrace_config.pt.size = conf->pt.size;
12639 /* Read the current thread's btrace configuration from the target and
12640 store it into CONF. */
12643 btrace_read_config (struct btrace_config *conf)
12647 xml = target_read_stralloc (¤t_target,
12648 TARGET_OBJECT_BTRACE_CONF, "");
12651 struct cleanup *cleanup;
12653 cleanup = make_cleanup (xfree, xml);
12654 parse_xml_btrace_conf (conf, xml);
12655 do_cleanups (cleanup);
12659 /* Enable branch tracing. */
12661 static struct btrace_target_info *
12662 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12663 const struct btrace_config *conf)
12665 struct btrace_target_info *tinfo = NULL;
12666 struct packet_config *packet = NULL;
12667 struct remote_state *rs = get_remote_state ();
12668 char *buf = rs->buf;
12669 char *endbuf = rs->buf + get_remote_packet_size ();
12671 switch (conf->format)
12673 case BTRACE_FORMAT_BTS:
12674 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12677 case BTRACE_FORMAT_PT:
12678 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12682 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
12683 error (_("Target does not support branch tracing."));
12685 btrace_sync_conf (conf);
12687 set_general_thread (ptid);
12689 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12691 getpkt (&rs->buf, &rs->buf_size, 0);
12693 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12695 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12696 error (_("Could not enable branch tracing for %s: %s"),
12697 target_pid_to_str (ptid), rs->buf + 2);
12699 error (_("Could not enable branch tracing for %s."),
12700 target_pid_to_str (ptid));
12703 tinfo = XCNEW (struct btrace_target_info);
12704 tinfo->ptid = ptid;
12706 /* If we fail to read the configuration, we lose some information, but the
12707 tracing itself is not impacted. */
12710 btrace_read_config (&tinfo->conf);
12712 CATCH (err, RETURN_MASK_ERROR)
12714 if (err.message != NULL)
12715 warning ("%s", err.message);
12722 /* Disable branch tracing. */
12725 remote_disable_btrace (struct target_ops *self,
12726 struct btrace_target_info *tinfo)
12728 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12729 struct remote_state *rs = get_remote_state ();
12730 char *buf = rs->buf;
12731 char *endbuf = rs->buf + get_remote_packet_size ();
12733 if (packet_config_support (packet) != PACKET_ENABLE)
12734 error (_("Target does not support branch tracing."));
12736 set_general_thread (tinfo->ptid);
12738 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12740 getpkt (&rs->buf, &rs->buf_size, 0);
12742 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12744 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12745 error (_("Could not disable branch tracing for %s: %s"),
12746 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12748 error (_("Could not disable branch tracing for %s."),
12749 target_pid_to_str (tinfo->ptid));
12755 /* Teardown branch tracing. */
12758 remote_teardown_btrace (struct target_ops *self,
12759 struct btrace_target_info *tinfo)
12761 /* We must not talk to the target during teardown. */
12765 /* Read the branch trace. */
12767 static enum btrace_error
12768 remote_read_btrace (struct target_ops *self,
12769 struct btrace_data *btrace,
12770 struct btrace_target_info *tinfo,
12771 enum btrace_read_type type)
12773 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12774 struct remote_state *rs = get_remote_state ();
12775 struct cleanup *cleanup;
12779 if (packet_config_support (packet) != PACKET_ENABLE)
12780 error (_("Target does not support branch tracing."));
12782 #if !defined(HAVE_LIBEXPAT)
12783 error (_("Cannot process branch tracing result. XML parsing not supported."));
12788 case BTRACE_READ_ALL:
12791 case BTRACE_READ_NEW:
12794 case BTRACE_READ_DELTA:
12798 internal_error (__FILE__, __LINE__,
12799 _("Bad branch tracing read type: %u."),
12800 (unsigned int) type);
12803 xml = target_read_stralloc (¤t_target,
12804 TARGET_OBJECT_BTRACE, annex);
12806 return BTRACE_ERR_UNKNOWN;
12808 cleanup = make_cleanup (xfree, xml);
12809 parse_xml_btrace (btrace, xml);
12810 do_cleanups (cleanup);
12812 return BTRACE_ERR_NONE;
12815 static const struct btrace_config *
12816 remote_btrace_conf (struct target_ops *self,
12817 const struct btrace_target_info *tinfo)
12819 return &tinfo->conf;
12823 remote_augmented_libraries_svr4_read (struct target_ops *self)
12825 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12829 /* Implementation of to_load. */
12832 remote_load (struct target_ops *self, const char *name, int from_tty)
12834 generic_load (name, from_tty);
12837 /* Accepts an integer PID; returns a string representing a file that
12838 can be opened on the remote side to get the symbols for the child
12839 process. Returns NULL if the operation is not supported. */
12842 remote_pid_to_exec_file (struct target_ops *self, int pid)
12844 static char *filename = NULL;
12845 struct inferior *inf;
12846 char *annex = NULL;
12848 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12851 if (filename != NULL)
12854 inf = find_inferior_pid (pid);
12856 internal_error (__FILE__, __LINE__,
12857 _("not currently attached to process %d"), pid);
12859 if (!inf->fake_pid_p)
12861 const int annex_size = 9;
12863 annex = (char *) alloca (annex_size);
12864 xsnprintf (annex, annex_size, "%x", pid);
12867 filename = target_read_stralloc (¤t_target,
12868 TARGET_OBJECT_EXEC_FILE, annex);
12873 /* Implement the to_can_do_single_step target_ops method. */
12876 remote_can_do_single_step (struct target_ops *ops)
12878 /* We can only tell whether target supports single step or not by
12879 supported s and S vCont actions if the stub supports vContSupported
12880 feature. If the stub doesn't support vContSupported feature,
12881 we have conservatively to think target doesn't supports single
12883 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12885 struct remote_state *rs = get_remote_state ();
12887 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12888 remote_vcont_probe (rs);
12890 return rs->supports_vCont.s && rs->supports_vCont.S;
12897 init_remote_ops (void)
12899 remote_ops.to_shortname = "remote";
12900 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12901 remote_ops.to_doc =
12902 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12903 Specify the serial device it is connected to\n\
12904 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12905 remote_ops.to_open = remote_open;
12906 remote_ops.to_close = remote_close;
12907 remote_ops.to_detach = remote_detach;
12908 remote_ops.to_disconnect = remote_disconnect;
12909 remote_ops.to_resume = remote_resume;
12910 remote_ops.to_wait = remote_wait;
12911 remote_ops.to_fetch_registers = remote_fetch_registers;
12912 remote_ops.to_store_registers = remote_store_registers;
12913 remote_ops.to_prepare_to_store = remote_prepare_to_store;
12914 remote_ops.to_files_info = remote_files_info;
12915 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12916 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12917 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12918 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12919 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12920 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12921 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12922 remote_ops.to_stopped_data_address = remote_stopped_data_address;
12923 remote_ops.to_watchpoint_addr_within_range =
12924 remote_watchpoint_addr_within_range;
12925 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12926 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12927 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12928 remote_ops.to_region_ok_for_hw_watchpoint
12929 = remote_region_ok_for_hw_watchpoint;
12930 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12931 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12932 remote_ops.to_kill = remote_kill;
12933 remote_ops.to_load = remote_load;
12934 remote_ops.to_mourn_inferior = remote_mourn;
12935 remote_ops.to_pass_signals = remote_pass_signals;
12936 remote_ops.to_program_signals = remote_program_signals;
12937 remote_ops.to_thread_alive = remote_thread_alive;
12938 remote_ops.to_thread_name = remote_thread_name;
12939 remote_ops.to_update_thread_list = remote_update_thread_list;
12940 remote_ops.to_pid_to_str = remote_pid_to_str;
12941 remote_ops.to_extra_thread_info = remote_threads_extra_info;
12942 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12943 remote_ops.to_stop = remote_stop;
12944 remote_ops.to_interrupt = remote_interrupt;
12945 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
12946 remote_ops.to_xfer_partial = remote_xfer_partial;
12947 remote_ops.to_rcmd = remote_rcmd;
12948 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12949 remote_ops.to_log_command = serial_log_command;
12950 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12951 remote_ops.to_stratum = process_stratum;
12952 remote_ops.to_has_all_memory = default_child_has_all_memory;
12953 remote_ops.to_has_memory = default_child_has_memory;
12954 remote_ops.to_has_stack = default_child_has_stack;
12955 remote_ops.to_has_registers = default_child_has_registers;
12956 remote_ops.to_has_execution = default_child_has_execution;
12957 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
12958 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12959 remote_ops.to_magic = OPS_MAGIC;
12960 remote_ops.to_memory_map = remote_memory_map;
12961 remote_ops.to_flash_erase = remote_flash_erase;
12962 remote_ops.to_flash_done = remote_flash_done;
12963 remote_ops.to_read_description = remote_read_description;
12964 remote_ops.to_search_memory = remote_search_memory;
12965 remote_ops.to_can_async_p = remote_can_async_p;
12966 remote_ops.to_is_async_p = remote_is_async_p;
12967 remote_ops.to_async = remote_async;
12968 remote_ops.to_can_do_single_step = remote_can_do_single_step;
12969 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12970 remote_ops.to_terminal_ours = remote_terminal_ours;
12971 remote_ops.to_supports_non_stop = remote_supports_non_stop;
12972 remote_ops.to_supports_multi_process = remote_supports_multi_process;
12973 remote_ops.to_supports_disable_randomization
12974 = remote_supports_disable_randomization;
12975 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12976 remote_ops.to_fileio_open = remote_hostio_open;
12977 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12978 remote_ops.to_fileio_pread = remote_hostio_pread;
12979 remote_ops.to_fileio_fstat = remote_hostio_fstat;
12980 remote_ops.to_fileio_close = remote_hostio_close;
12981 remote_ops.to_fileio_unlink = remote_hostio_unlink;
12982 remote_ops.to_fileio_readlink = remote_hostio_readlink;
12983 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12984 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12985 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12986 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12987 remote_ops.to_trace_init = remote_trace_init;
12988 remote_ops.to_download_tracepoint = remote_download_tracepoint;
12989 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12990 remote_ops.to_download_trace_state_variable
12991 = remote_download_trace_state_variable;
12992 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12993 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12994 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12995 remote_ops.to_trace_start = remote_trace_start;
12996 remote_ops.to_get_trace_status = remote_get_trace_status;
12997 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12998 remote_ops.to_trace_stop = remote_trace_stop;
12999 remote_ops.to_trace_find = remote_trace_find;
13000 remote_ops.to_get_trace_state_variable_value
13001 = remote_get_trace_state_variable_value;
13002 remote_ops.to_save_trace_data = remote_save_trace_data;
13003 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13004 remote_ops.to_upload_trace_state_variables
13005 = remote_upload_trace_state_variables;
13006 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13007 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13008 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13009 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13010 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13011 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13012 remote_ops.to_core_of_thread = remote_core_of_thread;
13013 remote_ops.to_verify_memory = remote_verify_memory;
13014 remote_ops.to_get_tib_address = remote_get_tib_address;
13015 remote_ops.to_set_permissions = remote_set_permissions;
13016 remote_ops.to_static_tracepoint_marker_at
13017 = remote_static_tracepoint_marker_at;
13018 remote_ops.to_static_tracepoint_markers_by_strid
13019 = remote_static_tracepoint_markers_by_strid;
13020 remote_ops.to_traceframe_info = remote_traceframe_info;
13021 remote_ops.to_use_agent = remote_use_agent;
13022 remote_ops.to_can_use_agent = remote_can_use_agent;
13023 remote_ops.to_supports_btrace = remote_supports_btrace;
13024 remote_ops.to_enable_btrace = remote_enable_btrace;
13025 remote_ops.to_disable_btrace = remote_disable_btrace;
13026 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13027 remote_ops.to_read_btrace = remote_read_btrace;
13028 remote_ops.to_btrace_conf = remote_btrace_conf;
13029 remote_ops.to_augmented_libraries_svr4_read =
13030 remote_augmented_libraries_svr4_read;
13033 /* Set up the extended remote vector by making a copy of the standard
13034 remote vector and adding to it. */
13037 init_extended_remote_ops (void)
13039 extended_remote_ops = remote_ops;
13041 extended_remote_ops.to_shortname = "extended-remote";
13042 extended_remote_ops.to_longname =
13043 "Extended remote serial target in gdb-specific protocol";
13044 extended_remote_ops.to_doc =
13045 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13046 Specify the serial device it is connected to (e.g. /dev/ttya).";
13047 extended_remote_ops.to_open = extended_remote_open;
13048 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13049 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
13050 extended_remote_ops.to_detach = extended_remote_detach;
13051 extended_remote_ops.to_attach = extended_remote_attach;
13052 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13053 extended_remote_ops.to_kill = extended_remote_kill;
13054 extended_remote_ops.to_supports_disable_randomization
13055 = extended_remote_supports_disable_randomization;
13056 extended_remote_ops.to_follow_fork = remote_follow_fork;
13057 extended_remote_ops.to_follow_exec = remote_follow_exec;
13058 extended_remote_ops.to_insert_fork_catchpoint
13059 = remote_insert_fork_catchpoint;
13060 extended_remote_ops.to_remove_fork_catchpoint
13061 = remote_remove_fork_catchpoint;
13062 extended_remote_ops.to_insert_vfork_catchpoint
13063 = remote_insert_vfork_catchpoint;
13064 extended_remote_ops.to_remove_vfork_catchpoint
13065 = remote_remove_vfork_catchpoint;
13066 extended_remote_ops.to_insert_exec_catchpoint
13067 = remote_insert_exec_catchpoint;
13068 extended_remote_ops.to_remove_exec_catchpoint
13069 = remote_remove_exec_catchpoint;
13073 remote_can_async_p (struct target_ops *ops)
13075 struct remote_state *rs = get_remote_state ();
13077 if (!target_async_permitted)
13078 /* We only enable async when the user specifically asks for it. */
13081 /* We're async whenever the serial device is. */
13082 return serial_can_async_p (rs->remote_desc);
13086 remote_is_async_p (struct target_ops *ops)
13088 struct remote_state *rs = get_remote_state ();
13090 if (!target_async_permitted)
13091 /* We only enable async when the user specifically asks for it. */
13094 /* We're async whenever the serial device is. */
13095 return serial_is_async_p (rs->remote_desc);
13098 /* Pass the SERIAL event on and up to the client. One day this code
13099 will be able to delay notifying the client of an event until the
13100 point where an entire packet has been received. */
13102 static serial_event_ftype remote_async_serial_handler;
13105 remote_async_serial_handler (struct serial *scb, void *context)
13107 struct remote_state *rs = (struct remote_state *) context;
13109 /* Don't propogate error information up to the client. Instead let
13110 the client find out about the error by querying the target. */
13111 inferior_event_handler (INF_REG_EVENT, NULL);
13115 remote_async_inferior_event_handler (gdb_client_data data)
13117 inferior_event_handler (INF_REG_EVENT, NULL);
13121 remote_async (struct target_ops *ops, int enable)
13123 struct remote_state *rs = get_remote_state ();
13127 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13129 /* If there are pending events in the stop reply queue tell the
13130 event loop to process them. */
13131 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13132 mark_async_event_handler (remote_async_inferior_event_token);
13133 /* For simplicity, below we clear the pending events token
13134 without remembering whether it is marked, so here we always
13135 mark it. If there's actually no pending notification to
13136 process, this ends up being a no-op (other than a spurious
13137 event-loop wakeup). */
13138 if (target_is_non_stop_p ())
13139 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13143 serial_async (rs->remote_desc, NULL, NULL);
13144 /* If the core is disabling async, it doesn't want to be
13145 disturbed with target events. Clear all async event sources
13147 clear_async_event_handler (remote_async_inferior_event_token);
13148 if (target_is_non_stop_p ())
13149 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13154 set_remote_cmd (char *args, int from_tty)
13156 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13160 show_remote_cmd (char *args, int from_tty)
13162 /* We can't just use cmd_show_list here, because we want to skip
13163 the redundant "show remote Z-packet" and the legacy aliases. */
13164 struct cleanup *showlist_chain;
13165 struct cmd_list_element *list = remote_show_cmdlist;
13166 struct ui_out *uiout = current_uiout;
13168 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13169 for (; list != NULL; list = list->next)
13170 if (strcmp (list->name, "Z-packet") == 0)
13172 else if (list->type == not_set_cmd)
13173 /* Alias commands are exactly like the original, except they
13174 don't have the normal type. */
13178 struct cleanup *option_chain
13179 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
13181 ui_out_field_string (uiout, "name", list->name);
13182 ui_out_text (uiout, ": ");
13183 if (list->type == show_cmd)
13184 do_show_command ((char *) NULL, from_tty, list);
13186 cmd_func (list, NULL, from_tty);
13187 /* Close the tuple. */
13188 do_cleanups (option_chain);
13191 /* Close the tuple. */
13192 do_cleanups (showlist_chain);
13196 /* Function to be called whenever a new objfile (shlib) is detected. */
13198 remote_new_objfile (struct objfile *objfile)
13200 struct remote_state *rs = get_remote_state ();
13202 if (rs->remote_desc != 0) /* Have a remote connection. */
13203 remote_check_symbols ();
13206 /* Pull all the tracepoints defined on the target and create local
13207 data structures representing them. We don't want to create real
13208 tracepoints yet, we don't want to mess up the user's existing
13212 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13214 struct remote_state *rs = get_remote_state ();
13217 /* Ask for a first packet of tracepoint definition. */
13219 getpkt (&rs->buf, &rs->buf_size, 0);
13221 while (*p && *p != 'l')
13223 parse_tracepoint_definition (p, utpp);
13224 /* Ask for another packet of tracepoint definition. */
13226 getpkt (&rs->buf, &rs->buf_size, 0);
13233 remote_upload_trace_state_variables (struct target_ops *self,
13234 struct uploaded_tsv **utsvp)
13236 struct remote_state *rs = get_remote_state ();
13239 /* Ask for a first packet of variable definition. */
13241 getpkt (&rs->buf, &rs->buf_size, 0);
13243 while (*p && *p != 'l')
13245 parse_tsv_definition (p, utsvp);
13246 /* Ask for another packet of variable definition. */
13248 getpkt (&rs->buf, &rs->buf_size, 0);
13254 /* The "set/show range-stepping" show hook. */
13257 show_range_stepping (struct ui_file *file, int from_tty,
13258 struct cmd_list_element *c,
13261 fprintf_filtered (file,
13262 _("Debugger's willingness to use range stepping "
13263 "is %s.\n"), value);
13266 /* The "set/show range-stepping" set hook. */
13269 set_range_stepping (char *ignore_args, int from_tty,
13270 struct cmd_list_element *c)
13272 struct remote_state *rs = get_remote_state ();
13274 /* Whene enabling, check whether range stepping is actually
13275 supported by the target, and warn if not. */
13276 if (use_range_stepping)
13278 if (rs->remote_desc != NULL)
13280 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13281 remote_vcont_probe (rs);
13283 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13284 && rs->supports_vCont.r)
13288 warning (_("Range stepping is not supported by the current target"));
13293 _initialize_remote (void)
13295 struct remote_state *rs;
13296 struct cmd_list_element *cmd;
13297 const char *cmd_name;
13299 /* architecture specific data */
13300 remote_gdbarch_data_handle =
13301 gdbarch_data_register_post_init (init_remote_state);
13302 remote_g_packet_data_handle =
13303 gdbarch_data_register_pre_init (remote_g_packet_data_init);
13306 = register_program_space_data_with_cleanup (NULL,
13307 remote_pspace_data_cleanup);
13309 /* Initialize the per-target state. At the moment there is only one
13310 of these, not one per target. Only one target is active at a
13312 remote_state = new_remote_state ();
13314 init_remote_ops ();
13315 add_target (&remote_ops);
13317 init_extended_remote_ops ();
13318 add_target (&extended_remote_ops);
13320 /* Hook into new objfile notification. */
13321 observer_attach_new_objfile (remote_new_objfile);
13322 /* We're no longer interested in notification events of an inferior
13324 observer_attach_inferior_exit (discard_pending_stop_replies);
13326 /* Set up signal handlers. */
13327 async_sigint_remote_token =
13328 create_async_signal_handler (async_remote_interrupt, NULL);
13329 async_sigint_remote_twice_token =
13330 create_async_signal_handler (async_remote_interrupt_twice, NULL);
13333 init_remote_threadtests ();
13336 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13337 /* set/show remote ... */
13339 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13340 Remote protocol specific variables\n\
13341 Configure various remote-protocol specific variables such as\n\
13342 the packets being used"),
13343 &remote_set_cmdlist, "set remote ",
13344 0 /* allow-unknown */, &setlist);
13345 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13346 Remote protocol specific variables\n\
13347 Configure various remote-protocol specific variables such as\n\
13348 the packets being used"),
13349 &remote_show_cmdlist, "show remote ",
13350 0 /* allow-unknown */, &showlist);
13352 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13353 Compare section data on target to the exec file.\n\
13354 Argument is a single section name (default: all loaded sections).\n\
13355 To compare only read-only loaded sections, specify the -r option."),
13358 add_cmd ("packet", class_maintenance, packet_command, _("\
13359 Send an arbitrary packet to a remote target.\n\
13360 maintenance packet TEXT\n\
13361 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13362 this command sends the string TEXT to the inferior, and displays the\n\
13363 response packet. GDB supplies the initial `$' character, and the\n\
13364 terminating `#' character and checksum."),
13367 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13368 Set whether to send break if interrupted."), _("\
13369 Show whether to send break if interrupted."), _("\
13370 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13371 set_remotebreak, show_remotebreak,
13372 &setlist, &showlist);
13373 cmd_name = "remotebreak";
13374 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13375 deprecate_cmd (cmd, "set remote interrupt-sequence");
13376 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13377 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13378 deprecate_cmd (cmd, "show remote interrupt-sequence");
13380 add_setshow_enum_cmd ("interrupt-sequence", class_support,
13381 interrupt_sequence_modes, &interrupt_sequence_mode,
13383 Set interrupt sequence to remote target."), _("\
13384 Show interrupt sequence to remote target."), _("\
13385 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13386 NULL, show_interrupt_sequence,
13387 &remote_set_cmdlist,
13388 &remote_show_cmdlist);
13390 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13391 &interrupt_on_connect, _("\
13392 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13393 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13394 If set, interrupt sequence is sent to remote target."),
13396 &remote_set_cmdlist, &remote_show_cmdlist);
13398 /* Install commands for configuring memory read/write packets. */
13400 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13401 Set the maximum number of bytes per memory write packet (deprecated)."),
13403 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13404 Show the maximum number of bytes per memory write packet (deprecated)."),
13406 add_cmd ("memory-write-packet-size", no_class,
13407 set_memory_write_packet_size, _("\
13408 Set the maximum number of bytes per memory-write packet.\n\
13409 Specify the number of bytes in a packet or 0 (zero) for the\n\
13410 default packet size. The actual limit is further reduced\n\
13411 dependent on the target. Specify ``fixed'' to disable the\n\
13412 further restriction and ``limit'' to enable that restriction."),
13413 &remote_set_cmdlist);
13414 add_cmd ("memory-read-packet-size", no_class,
13415 set_memory_read_packet_size, _("\
13416 Set the maximum number of bytes per memory-read packet.\n\
13417 Specify the number of bytes in a packet or 0 (zero) for the\n\
13418 default packet size. The actual limit is further reduced\n\
13419 dependent on the target. Specify ``fixed'' to disable the\n\
13420 further restriction and ``limit'' to enable that restriction."),
13421 &remote_set_cmdlist);
13422 add_cmd ("memory-write-packet-size", no_class,
13423 show_memory_write_packet_size,
13424 _("Show the maximum number of bytes per memory-write packet."),
13425 &remote_show_cmdlist);
13426 add_cmd ("memory-read-packet-size", no_class,
13427 show_memory_read_packet_size,
13428 _("Show the maximum number of bytes per memory-read packet."),
13429 &remote_show_cmdlist);
13431 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
13432 &remote_hw_watchpoint_limit, _("\
13433 Set the maximum number of target hardware watchpoints."), _("\
13434 Show the maximum number of target hardware watchpoints."), _("\
13435 Specify a negative limit for unlimited."),
13436 NULL, NULL, /* FIXME: i18n: The maximum
13437 number of target hardware
13438 watchpoints is %s. */
13439 &remote_set_cmdlist, &remote_show_cmdlist);
13440 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13441 &remote_hw_watchpoint_length_limit, _("\
13442 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13443 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13444 Specify a negative limit for unlimited."),
13445 NULL, NULL, /* FIXME: i18n: The maximum
13446 length (in bytes) of a target
13447 hardware watchpoint is %s. */
13448 &remote_set_cmdlist, &remote_show_cmdlist);
13449 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
13450 &remote_hw_breakpoint_limit, _("\
13451 Set the maximum number of target hardware breakpoints."), _("\
13452 Show the maximum number of target hardware breakpoints."), _("\
13453 Specify a negative limit for unlimited."),
13454 NULL, NULL, /* FIXME: i18n: The maximum
13455 number of target hardware
13456 breakpoints is %s. */
13457 &remote_set_cmdlist, &remote_show_cmdlist);
13459 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13460 &remote_address_size, _("\
13461 Set the maximum size of the address (in bits) in a memory packet."), _("\
13462 Show the maximum size of the address (in bits) in a memory packet."), NULL,
13464 NULL, /* FIXME: i18n: */
13465 &setlist, &showlist);
13467 init_all_packet_configs ();
13469 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
13470 "X", "binary-download", 1);
13472 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
13473 "vCont", "verbose-resume", 0);
13475 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13476 "QPassSignals", "pass-signals", 0);
13478 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13479 "QProgramSignals", "program-signals", 0);
13481 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
13482 "qSymbol", "symbol-lookup", 0);
13484 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
13485 "P", "set-register", 1);
13487 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
13488 "p", "fetch-register", 1);
13490 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
13491 "Z0", "software-breakpoint", 0);
13493 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
13494 "Z1", "hardware-breakpoint", 0);
13496 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
13497 "Z2", "write-watchpoint", 0);
13499 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
13500 "Z3", "read-watchpoint", 0);
13502 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
13503 "Z4", "access-watchpoint", 0);
13505 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13506 "qXfer:auxv:read", "read-aux-vector", 0);
13508 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13509 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13511 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13512 "qXfer:features:read", "target-features", 0);
13514 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13515 "qXfer:libraries:read", "library-info", 0);
13517 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13518 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13520 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13521 "qXfer:memory-map:read", "memory-map", 0);
13523 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13524 "qXfer:spu:read", "read-spu-object", 0);
13526 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13527 "qXfer:spu:write", "write-spu-object", 0);
13529 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13530 "qXfer:osdata:read", "osdata", 0);
13532 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13533 "qXfer:threads:read", "threads", 0);
13535 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13536 "qXfer:siginfo:read", "read-siginfo-object", 0);
13538 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13539 "qXfer:siginfo:write", "write-siginfo-object", 0);
13541 add_packet_config_cmd
13542 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
13543 "qXfer:traceframe-info:read", "traceframe-info", 0);
13545 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13546 "qXfer:uib:read", "unwind-info-block", 0);
13548 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
13549 "qGetTLSAddr", "get-thread-local-storage-address",
13552 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13553 "qGetTIBAddr", "get-thread-information-block-address",
13556 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13557 "bc", "reverse-continue", 0);
13559 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13560 "bs", "reverse-step", 0);
13562 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13563 "qSupported", "supported-packets", 0);
13565 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13566 "qSearch:memory", "search-memory", 0);
13568 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13569 "qTStatus", "trace-status", 0);
13571 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13572 "vFile:setfs", "hostio-setfs", 0);
13574 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13575 "vFile:open", "hostio-open", 0);
13577 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13578 "vFile:pread", "hostio-pread", 0);
13580 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13581 "vFile:pwrite", "hostio-pwrite", 0);
13583 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13584 "vFile:close", "hostio-close", 0);
13586 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13587 "vFile:unlink", "hostio-unlink", 0);
13589 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13590 "vFile:readlink", "hostio-readlink", 0);
13592 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13593 "vFile:fstat", "hostio-fstat", 0);
13595 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13596 "vAttach", "attach", 0);
13598 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13601 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13602 "QStartNoAckMode", "noack", 0);
13604 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13605 "vKill", "kill", 0);
13607 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13608 "qAttached", "query-attached", 0);
13610 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
13611 "ConditionalTracepoints",
13612 "conditional-tracepoints", 0);
13614 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13615 "ConditionalBreakpoints",
13616 "conditional-breakpoints", 0);
13618 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13619 "BreakpointCommands",
13620 "breakpoint-commands", 0);
13622 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13623 "FastTracepoints", "fast-tracepoints", 0);
13625 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13626 "TracepointSource", "TracepointSource", 0);
13628 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13629 "QAllow", "allow", 0);
13631 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13632 "StaticTracepoints", "static-tracepoints", 0);
13634 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13635 "InstallInTrace", "install-in-trace", 0);
13637 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13638 "qXfer:statictrace:read", "read-sdata-object", 0);
13640 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13641 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13643 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13644 "QDisableRandomization", "disable-randomization", 0);
13646 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13647 "QAgent", "agent", 0);
13649 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13650 "QTBuffer:size", "trace-buffer-size", 0);
13652 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13653 "Qbtrace:off", "disable-btrace", 0);
13655 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
13656 "Qbtrace:bts", "enable-btrace-bts", 0);
13658 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13659 "Qbtrace:pt", "enable-btrace-pt", 0);
13661 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13662 "qXfer:btrace", "read-btrace", 0);
13664 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13665 "qXfer:btrace-conf", "read-btrace-conf", 0);
13667 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13668 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13670 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13671 "multiprocess-feature", "multiprocess-feature", 0);
13673 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13674 "swbreak-feature", "swbreak-feature", 0);
13676 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13677 "hwbreak-feature", "hwbreak-feature", 0);
13679 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13680 "fork-event-feature", "fork-event-feature", 0);
13682 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13683 "vfork-event-feature", "vfork-event-feature", 0);
13685 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13686 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13688 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13689 "vContSupported", "verbose-resume-supported", 0);
13691 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13692 "exec-event-feature", "exec-event-feature", 0);
13694 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13695 "vCtrlC", "ctrl-c", 0);
13697 /* Assert that we've registered "set remote foo-packet" commands
13698 for all packet configs. */
13702 for (i = 0; i < PACKET_MAX; i++)
13704 /* Ideally all configs would have a command associated. Some
13705 still don't though. */
13710 case PACKET_QNonStop:
13711 case PACKET_EnableDisableTracepoints_feature:
13712 case PACKET_tracenz_feature:
13713 case PACKET_DisconnectedTracing_feature:
13714 case PACKET_augmented_libraries_svr4_read_feature:
13716 /* Additions to this list need to be well justified:
13717 pre-existing packets are OK; new packets are not. */
13725 /* This catches both forgetting to add a config command, and
13726 forgetting to remove a packet from the exception list. */
13727 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13731 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13732 Z sub-packet has its own set and show commands, but users may
13733 have sets to this variable in their .gdbinit files (or in their
13735 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
13736 &remote_Z_packet_detect, _("\
13737 Set use of remote protocol `Z' packets"), _("\
13738 Show use of remote protocol `Z' packets "), _("\
13739 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
13741 set_remote_protocol_Z_packet_cmd,
13742 show_remote_protocol_Z_packet_cmd,
13743 /* FIXME: i18n: Use of remote protocol
13744 `Z' packets is %s. */
13745 &remote_set_cmdlist, &remote_show_cmdlist);
13747 add_prefix_cmd ("remote", class_files, remote_command, _("\
13748 Manipulate files on the remote system\n\
13749 Transfer files to and from the remote target system."),
13750 &remote_cmdlist, "remote ",
13751 0 /* allow-unknown */, &cmdlist);
13753 add_cmd ("put", class_files, remote_put_command,
13754 _("Copy a local file to the remote system."),
13757 add_cmd ("get", class_files, remote_get_command,
13758 _("Copy a remote file to the local system."),
13761 add_cmd ("delete", class_files, remote_delete_command,
13762 _("Delete a remote file."),
13765 add_setshow_string_noescape_cmd ("exec-file", class_files,
13766 &remote_exec_file_var, _("\
13767 Set the remote pathname for \"run\""), _("\
13768 Show the remote pathname for \"run\""), NULL,
13769 set_remote_exec_file,
13770 show_remote_exec_file,
13771 &remote_set_cmdlist,
13772 &remote_show_cmdlist);
13774 add_setshow_boolean_cmd ("range-stepping", class_run,
13775 &use_range_stepping, _("\
13776 Enable or disable range stepping."), _("\
13777 Show whether target-assisted range stepping is enabled."), _("\
13778 If on, and the target supports it, when stepping a source line, GDB\n\
13779 tells the target to step the corresponding range of addresses itself instead\n\
13780 of issuing multiple single-steps. This speeds up source level\n\
13781 stepping. If off, GDB always issues single-steps, even if range\n\
13782 stepping is supported by the target. The default is on."),
13783 set_range_stepping,
13784 show_range_stepping,
13788 /* Eventually initialize fileio. See fileio.c */
13789 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
13791 /* Take advantage of the fact that the TID field is not used, to tag
13792 special ptids with it set to != 0. */
13793 magic_null_ptid = ptid_build (42000, -1, 1);
13794 not_sent_ptid = ptid_build (42000, -2, 1);
13795 any_thread_ptid = ptid_build (42000, 0, 1);
13797 target_buf_size = 2048;
13798 target_buf = (char *) xmalloc (target_buf_size);