1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2017 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"
73 #include "record-btrace.h"
75 #include "common/scoped_restore.h"
77 #include "common/byte-vector.h"
79 /* Temp hacks for tracepoint encoding migration. */
80 static char *target_buf;
81 static long target_buf_size;
83 /* Per-program-space data key. */
84 static const struct program_space_data *remote_pspace_data;
86 /* The variable registered as the control variable used by the
87 remote exec-file commands. While the remote exec-file setting is
88 per-program-space, the set/show machinery uses this as the
89 location of the remote exec-file value. */
90 static char *remote_exec_file_var;
92 /* The size to align memory write packets, when practical. The protocol
93 does not guarantee any alignment, and gdb will generate short
94 writes and unaligned writes, but even as a best-effort attempt this
95 can improve bulk transfers. For instance, if a write is misaligned
96 relative to the target's data bus, the stub may need to make an extra
97 round trip fetching data from the target. This doesn't make a
98 huge difference, but it's easy to do, so we try to be helpful.
100 The alignment chosen is arbitrary; usually data bus width is
101 important here, not the possibly larger cache line size. */
102 enum { REMOTE_ALIGN_WRITES = 16 };
104 /* Prototypes for local functions. */
105 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
106 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
107 int forever, int *is_notif);
109 static void remote_files_info (struct target_ops *ignore);
111 static void remote_prepare_to_store (struct target_ops *self,
112 struct regcache *regcache);
114 static void remote_open_1 (const char *, int, struct target_ops *,
117 static void remote_close (struct target_ops *self);
121 static int remote_vkill (int pid, struct remote_state *rs);
123 static void remote_kill_k (void);
125 static void remote_mourn (struct target_ops *ops);
127 static void extended_remote_restart (void);
129 static void remote_send (char **buf, long *sizeof_buf_p);
131 static int readchar (int timeout);
133 static void remote_serial_write (const char *str, int len);
135 static void remote_kill (struct target_ops *ops);
137 static int remote_can_async_p (struct target_ops *);
139 static int remote_is_async_p (struct target_ops *);
141 static void remote_async (struct target_ops *ops, int enable);
143 static void remote_thread_events (struct target_ops *ops, int enable);
145 static void interrupt_query (void);
147 static void set_general_thread (ptid_t ptid);
148 static void set_continue_thread (ptid_t ptid);
150 static void get_offsets (void);
152 static void skip_frame (void);
154 static long read_frame (char **buf_p, long *sizeof_buf);
156 static int hexnumlen (ULONGEST num);
158 static void init_remote_ops (void);
160 static void init_extended_remote_ops (void);
162 static void remote_stop (struct target_ops *self, ptid_t);
164 static int stubhex (int ch);
166 static int hexnumstr (char *, ULONGEST);
168 static int hexnumnstr (char *, ULONGEST, int);
170 static CORE_ADDR remote_address_masked (CORE_ADDR);
172 static void print_packet (const char *);
174 static int stub_unpack_int (char *buff, int fieldlength);
176 static ptid_t remote_current_thread (ptid_t oldptid);
178 static int putpkt_binary (const char *buf, int cnt);
180 static void check_binary_download (CORE_ADDR addr);
182 struct packet_config;
184 static void show_packet_config_cmd (struct packet_config *config);
186 static void show_remote_protocol_packet_cmd (struct ui_file *file,
188 struct cmd_list_element *c,
191 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
192 static ptid_t read_ptid (char *buf, char **obuf);
194 static void remote_set_permissions (struct target_ops *self);
196 static int remote_get_trace_status (struct target_ops *self,
197 struct trace_status *ts);
199 static int remote_upload_tracepoints (struct target_ops *self,
200 struct uploaded_tp **utpp);
202 static int remote_upload_trace_state_variables (struct target_ops *self,
203 struct uploaded_tsv **utsvp);
205 static void remote_query_supported (void);
207 static void remote_check_symbols (void);
210 static void stop_reply_xfree (struct stop_reply *);
211 static void remote_parse_stop_reply (char *, struct stop_reply *);
212 static void push_stop_reply (struct stop_reply *);
213 static void discard_pending_stop_replies_in_queue (struct remote_state *);
214 static int peek_stop_reply (ptid_t ptid);
216 struct threads_listing_context;
217 static void remove_new_fork_children (struct threads_listing_context *);
219 static void remote_async_inferior_event_handler (gdb_client_data);
221 static void remote_terminal_ours (struct target_ops *self);
223 static int remote_read_description_p (struct target_ops *target);
225 static void remote_console_output (char *msg);
227 static int remote_supports_cond_breakpoints (struct target_ops *self);
229 static int remote_can_run_breakpoint_commands (struct target_ops *self);
231 static void remote_btrace_reset (void);
233 static void remote_btrace_maybe_reopen (void);
235 static int stop_reply_queue_length (void);
237 static void readahead_cache_invalidate (void);
239 static void remote_unpush_and_throw (void);
243 static struct cmd_list_element *remote_cmdlist;
245 /* For "set remote" and "show remote". */
247 static struct cmd_list_element *remote_set_cmdlist;
248 static struct cmd_list_element *remote_show_cmdlist;
250 /* Stub vCont actions support.
252 Each field is a boolean flag indicating whether the stub reports
253 support for the corresponding action. */
255 struct vCont_action_support
270 /* Controls whether GDB is willing to use range stepping. */
272 static int use_range_stepping = 1;
274 #define OPAQUETHREADBYTES 8
276 /* a 64 bit opaque identifier */
277 typedef unsigned char threadref[OPAQUETHREADBYTES];
279 /* About this many threadisds fit in a packet. */
281 #define MAXTHREADLISTRESULTS 32
283 /* The max number of chars in debug output. The rest of chars are
286 #define REMOTE_DEBUG_MAX_CHAR 512
288 /* Data for the vFile:pread readahead cache. */
290 struct readahead_cache
292 /* The file descriptor for the file that is being cached. -1 if the
296 /* The offset into the file that the cache buffer corresponds
300 /* The buffer holding the cache contents. */
302 /* The buffer's size. We try to read as much as fits into a packet
306 /* Cache hit and miss counters. */
311 /* Description of the remote protocol state for the currently
312 connected target. This is per-target state, and independent of the
313 selected architecture. */
317 /* A buffer to use for incoming packets, and its current size. The
318 buffer is grown dynamically for larger incoming packets.
319 Outgoing packets may also be constructed in this buffer.
320 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
321 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
326 /* True if we're going through initial connection setup (finding out
327 about the remote side's threads, relocating symbols, etc.). */
330 /* If we negotiated packet size explicitly (and thus can bypass
331 heuristics for the largest packet size that will not overflow
332 a buffer in the stub), this will be set to that packet size.
333 Otherwise zero, meaning to use the guessed size. */
334 long explicit_packet_size;
336 /* remote_wait is normally called when the target is running and
337 waits for a stop reply packet. But sometimes we need to call it
338 when the target is already stopped. We can send a "?" packet
339 and have remote_wait read the response. Or, if we already have
340 the response, we can stash it in BUF and tell remote_wait to
341 skip calling getpkt. This flag is set when BUF contains a
342 stop reply packet and the target is not waiting. */
343 int cached_wait_status;
345 /* True, if in no ack mode. That is, neither GDB nor the stub will
346 expect acks from each other. The connection is assumed to be
350 /* True if we're connected in extended remote mode. */
353 /* True if we resumed the target and we're waiting for the target to
354 stop. In the mean time, we can't start another command/query.
355 The remote server wouldn't be ready to process it, so we'd
356 timeout waiting for a reply that would never come and eventually
357 we'd close the connection. This can happen in asynchronous mode
358 because we allow GDB commands while the target is running. */
359 int waiting_for_stop_reply;
361 /* The status of the stub support for the various vCont actions. */
362 struct vCont_action_support supports_vCont;
364 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
365 responded to that. */
368 /* True if we saw a Ctrl-C while reading or writing from/to the
369 remote descriptor. At that point it is not safe to send a remote
370 interrupt packet, so we instead remember we saw the Ctrl-C and
371 process it once we're done with sending/receiving the current
372 packet, which should be shortly. If however that takes too long,
373 and the user presses Ctrl-C again, we offer to disconnect. */
374 int got_ctrlc_during_io;
376 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
377 remote_open knows that we don't have a file open when the program
379 struct serial *remote_desc;
381 /* These are the threads which we last sent to the remote system. The
382 TID member will be -1 for all or -2 for not sent yet. */
383 ptid_t general_thread;
384 ptid_t continue_thread;
386 /* This is the traceframe which we last selected on the remote system.
387 It will be -1 if no traceframe is selected. */
388 int remote_traceframe_number;
390 char *last_pass_packet;
392 /* The last QProgramSignals packet sent to the target. We bypass
393 sending a new program signals list down to the target if the new
394 packet is exactly the same as the last we sent. IOW, we only let
395 the target know about program signals list changes. */
396 char *last_program_signals_packet;
398 enum gdb_signal last_sent_signal;
402 /* The execution direction of the last resume we got. */
403 enum exec_direction_kind last_resume_exec_dir;
405 char *finished_object;
406 char *finished_annex;
407 ULONGEST finished_offset;
409 /* Should we try the 'ThreadInfo' query packet?
411 This variable (NOT available to the user: auto-detect only!)
412 determines whether GDB will use the new, simpler "ThreadInfo"
413 query or the older, more complex syntax for thread queries.
414 This is an auto-detect variable (set to true at each connect,
415 and set to false when the target fails to recognize it). */
416 int use_threadinfo_query;
417 int use_threadextra_query;
419 threadref echo_nextthread;
420 threadref nextthread;
421 threadref resultthreadlist[MAXTHREADLISTRESULTS];
423 /* The state of remote notification. */
424 struct remote_notif_state *notif_state;
426 /* The branch trace configuration. */
427 struct btrace_config btrace_config;
429 /* The argument to the last "vFile:setfs:" packet we sent, used
430 to avoid sending repeated unnecessary "vFile:setfs:" packets.
431 Initialized to -1 to indicate that no "vFile:setfs:" packet
432 has yet been sent. */
435 /* A readahead cache for vFile:pread. Often, reading a binary
436 involves a sequence of small reads. E.g., when parsing an ELF
437 file. A readahead cache helps mostly the case of remote
438 debugging on a connection with higher latency, due to the
439 request/reply nature of the RSP. We only cache data for a single
440 file descriptor at a time. */
441 struct readahead_cache readahead_cache;
444 /* Private data that we'll store in (struct thread_info)->private. */
445 struct private_thread_info
451 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
452 sequence of bytes. */
453 gdb::byte_vector *thread_handle;
455 /* Whether the target stopped for a breakpoint/watchpoint. */
456 enum target_stop_reason stop_reason;
458 /* This is set to the data address of the access causing the target
459 to stop for a watchpoint. */
460 CORE_ADDR watch_data_address;
462 /* Fields used by the vCont action coalescing implemented in
463 remote_resume / remote_commit_resume. remote_resume stores each
464 thread's last resume request in these fields, so that a later
465 remote_commit_resume knows which is the proper action for this
466 thread to include in the vCont packet. */
468 /* True if the last target_resume call for this thread was a step
469 request, false if a continue request. */
470 int last_resume_step;
472 /* The signal specified in the last target_resume call for this
474 enum gdb_signal last_resume_sig;
476 /* Whether this thread was already vCont-resumed on the remote
482 free_private_thread_info (struct private_thread_info *info)
486 delete info->thread_handle;
490 /* This data could be associated with a target, but we do not always
491 have access to the current target when we need it, so for now it is
492 static. This will be fine for as long as only one target is in use
494 static struct remote_state *remote_state;
496 static struct remote_state *
497 get_remote_state_raw (void)
502 /* Allocate a new struct remote_state with xmalloc, initialize it, and
505 static struct remote_state *
506 new_remote_state (void)
508 struct remote_state *result = XCNEW (struct remote_state);
510 /* The default buffer size is unimportant; it will be expanded
511 whenever a larger buffer is needed. */
512 result->buf_size = 400;
513 result->buf = (char *) xmalloc (result->buf_size);
514 result->remote_traceframe_number = -1;
515 result->last_sent_signal = GDB_SIGNAL_0;
516 result->last_resume_exec_dir = EXEC_FORWARD;
522 /* Description of the remote protocol for a given architecture. */
526 long offset; /* Offset into G packet. */
527 long regnum; /* GDB's internal register number. */
528 LONGEST pnum; /* Remote protocol register number. */
529 int in_g_packet; /* Always part of G packet. */
530 /* long size in bytes; == register_size (target_gdbarch (), regnum);
532 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
536 struct remote_arch_state
538 /* Description of the remote protocol registers. */
539 long sizeof_g_packet;
541 /* Description of the remote protocol registers indexed by REGNUM
542 (making an array gdbarch_num_regs in size). */
543 struct packet_reg *regs;
545 /* This is the size (in chars) of the first response to the ``g''
546 packet. It is used as a heuristic when determining the maximum
547 size of memory-read and memory-write packets. A target will
548 typically only reserve a buffer large enough to hold the ``g''
549 packet. The size does not include packet overhead (headers and
551 long actual_register_packet_size;
553 /* This is the maximum size (in chars) of a non read/write packet.
554 It is also used as a cap on the size of read/write packets. */
555 long remote_packet_size;
558 /* Utility: generate error from an incoming stub packet. */
560 trace_error (char *buf)
563 return; /* not an error msg */
566 case '1': /* malformed packet error */
567 if (*++buf == '0') /* general case: */
568 error (_("remote.c: error in outgoing packet."));
570 error (_("remote.c: error in outgoing packet at field #%ld."),
571 strtol (buf, NULL, 16));
573 error (_("Target returns error code '%s'."), buf);
577 /* Utility: wait for reply from stub, while accepting "O" packets. */
579 remote_get_noisy_reply (char **buf_p,
582 do /* Loop on reply from remote stub. */
586 QUIT; /* Allow user to bail out with ^C. */
587 getpkt (buf_p, sizeof_buf, 0);
591 else if (startswith (buf, "qRelocInsn:"))
594 CORE_ADDR from, to, org_to;
596 int adjusted_size = 0;
599 p = buf + strlen ("qRelocInsn:");
600 pp = unpack_varlen_hex (p, &ul);
602 error (_("invalid qRelocInsn packet: %s"), buf);
606 unpack_varlen_hex (p, &ul);
613 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
616 CATCH (ex, RETURN_MASK_ALL)
618 if (ex.error == MEMORY_ERROR)
620 /* Propagate memory errors silently back to the
621 target. The stub may have limited the range of
622 addresses we can write to, for example. */
626 /* Something unexpectedly bad happened. Be verbose
627 so we can tell what, and propagate the error back
628 to the stub, so it doesn't get stuck waiting for
630 exception_fprintf (gdb_stderr, ex,
631 _("warning: relocating instruction: "));
639 adjusted_size = to - org_to;
641 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
645 else if (buf[0] == 'O' && buf[1] != 'K')
646 remote_console_output (buf + 1); /* 'O' message from stub */
648 return buf; /* Here's the actual reply. */
653 /* Handle for retreving the remote protocol data from gdbarch. */
654 static struct gdbarch_data *remote_gdbarch_data_handle;
656 static struct remote_arch_state *
657 get_remote_arch_state (void)
659 gdb_assert (target_gdbarch () != NULL);
660 return ((struct remote_arch_state *)
661 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
664 /* Fetch the global remote target state. */
666 static struct remote_state *
667 get_remote_state (void)
669 /* Make sure that the remote architecture state has been
670 initialized, because doing so might reallocate rs->buf. Any
671 function which calls getpkt also needs to be mindful of changes
672 to rs->buf, but this call limits the number of places which run
674 get_remote_arch_state ();
676 return get_remote_state_raw ();
679 /* Cleanup routine for the remote module's pspace data. */
682 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
684 char *remote_exec_file = (char *) arg;
686 xfree (remote_exec_file);
689 /* Fetch the remote exec-file from the current program space. */
692 get_remote_exec_file (void)
694 char *remote_exec_file;
697 = (char *) program_space_data (current_program_space,
699 if (remote_exec_file == NULL)
702 return remote_exec_file;
705 /* Set the remote exec file for PSPACE. */
708 set_pspace_remote_exec_file (struct program_space *pspace,
709 char *remote_exec_file)
711 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
714 set_program_space_data (pspace, remote_pspace_data,
715 xstrdup (remote_exec_file));
718 /* The "set/show remote exec-file" set command hook. */
721 set_remote_exec_file (char *ignored, int from_tty,
722 struct cmd_list_element *c)
724 gdb_assert (remote_exec_file_var != NULL);
725 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
728 /* The "set/show remote exec-file" show command hook. */
731 show_remote_exec_file (struct ui_file *file, int from_tty,
732 struct cmd_list_element *cmd, const char *value)
734 fprintf_filtered (file, "%s\n", remote_exec_file_var);
738 compare_pnums (const void *lhs_, const void *rhs_)
740 const struct packet_reg * const *lhs
741 = (const struct packet_reg * const *) lhs_;
742 const struct packet_reg * const *rhs
743 = (const struct packet_reg * const *) rhs_;
745 if ((*lhs)->pnum < (*rhs)->pnum)
747 else if ((*lhs)->pnum == (*rhs)->pnum)
754 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
756 int regnum, num_remote_regs, offset;
757 struct packet_reg **remote_regs;
759 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
761 struct packet_reg *r = ®s[regnum];
763 if (register_size (gdbarch, regnum) == 0)
764 /* Do not try to fetch zero-sized (placeholder) registers. */
767 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
772 /* Define the g/G packet format as the contents of each register
773 with a remote protocol number, in order of ascending protocol
776 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
777 for (num_remote_regs = 0, regnum = 0;
778 regnum < gdbarch_num_regs (gdbarch);
780 if (regs[regnum].pnum != -1)
781 remote_regs[num_remote_regs++] = ®s[regnum];
783 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
786 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
788 remote_regs[regnum]->in_g_packet = 1;
789 remote_regs[regnum]->offset = offset;
790 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
796 /* Given the architecture described by GDBARCH, return the remote
797 protocol register's number and the register's offset in the g/G
798 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
799 If the target does not have a mapping for REGNUM, return false,
800 otherwise, return true. */
803 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
804 int *pnum, int *poffset)
806 struct packet_reg *regs;
807 struct cleanup *old_chain;
809 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
811 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
812 old_chain = make_cleanup (xfree, regs);
814 map_regcache_remote_table (gdbarch, regs);
816 *pnum = regs[regnum].pnum;
817 *poffset = regs[regnum].offset;
819 do_cleanups (old_chain);
825 init_remote_state (struct gdbarch *gdbarch)
827 struct remote_state *rs = get_remote_state_raw ();
828 struct remote_arch_state *rsa;
830 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
832 /* Use the architecture to build a regnum<->pnum table, which will be
833 1:1 unless a feature set specifies otherwise. */
834 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
835 gdbarch_num_regs (gdbarch),
838 /* Record the maximum possible size of the g packet - it may turn out
840 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
842 /* Default maximum number of characters in a packet body. Many
843 remote stubs have a hardwired buffer size of 400 bytes
844 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
845 as the maximum packet-size to ensure that the packet and an extra
846 NUL character can always fit in the buffer. This stops GDB
847 trashing stubs that try to squeeze an extra NUL into what is
848 already a full buffer (As of 1999-12-04 that was most stubs). */
849 rsa->remote_packet_size = 400 - 1;
851 /* This one is filled in when a ``g'' packet is received. */
852 rsa->actual_register_packet_size = 0;
854 /* Should rsa->sizeof_g_packet needs more space than the
855 default, adjust the size accordingly. Remember that each byte is
856 encoded as two characters. 32 is the overhead for the packet
857 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
858 (``$NN:G...#NN'') is a better guess, the below has been padded a
860 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
861 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
863 /* Make sure that the packet buffer is plenty big enough for
864 this architecture. */
865 if (rs->buf_size < rsa->remote_packet_size)
867 rs->buf_size = 2 * rsa->remote_packet_size;
868 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
874 /* Return the current allowed size of a remote packet. This is
875 inferred from the current architecture, and should be used to
876 limit the length of outgoing packets. */
878 get_remote_packet_size (void)
880 struct remote_state *rs = get_remote_state ();
881 struct remote_arch_state *rsa = get_remote_arch_state ();
883 if (rs->explicit_packet_size)
884 return rs->explicit_packet_size;
886 return rsa->remote_packet_size;
889 static struct packet_reg *
890 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
892 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
896 struct packet_reg *r = &rsa->regs[regnum];
898 gdb_assert (r->regnum == regnum);
903 static struct packet_reg *
904 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
908 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
910 struct packet_reg *r = &rsa->regs[i];
918 static struct target_ops remote_ops;
920 static struct target_ops extended_remote_ops;
922 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
923 ``forever'' still use the normal timeout mechanism. This is
924 currently used by the ASYNC code to guarentee that target reads
925 during the initial connect always time-out. Once getpkt has been
926 modified to return a timeout indication and, in turn
927 remote_wait()/wait_for_inferior() have gained a timeout parameter
929 static int wait_forever_enabled_p = 1;
931 /* Allow the user to specify what sequence to send to the remote
932 when he requests a program interruption: Although ^C is usually
933 what remote systems expect (this is the default, here), it is
934 sometimes preferable to send a break. On other systems such
935 as the Linux kernel, a break followed by g, which is Magic SysRq g
936 is required in order to interrupt the execution. */
937 const char interrupt_sequence_control_c[] = "Ctrl-C";
938 const char interrupt_sequence_break[] = "BREAK";
939 const char interrupt_sequence_break_g[] = "BREAK-g";
940 static const char *const interrupt_sequence_modes[] =
942 interrupt_sequence_control_c,
943 interrupt_sequence_break,
944 interrupt_sequence_break_g,
947 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
950 show_interrupt_sequence (struct ui_file *file, int from_tty,
951 struct cmd_list_element *c,
954 if (interrupt_sequence_mode == interrupt_sequence_control_c)
955 fprintf_filtered (file,
956 _("Send the ASCII ETX character (Ctrl-c) "
957 "to the remote target to interrupt the "
958 "execution of the program.\n"));
959 else if (interrupt_sequence_mode == interrupt_sequence_break)
960 fprintf_filtered (file,
961 _("send a break signal to the remote target "
962 "to interrupt the execution of the program.\n"));
963 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
964 fprintf_filtered (file,
965 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
966 "the remote target to interrupt the execution "
967 "of Linux kernel.\n"));
969 internal_error (__FILE__, __LINE__,
970 _("Invalid value for interrupt_sequence_mode: %s."),
971 interrupt_sequence_mode);
974 /* This boolean variable specifies whether interrupt_sequence is sent
975 to the remote target when gdb connects to it.
976 This is mostly needed when you debug the Linux kernel: The Linux kernel
977 expects BREAK g which is Magic SysRq g for connecting gdb. */
978 static int interrupt_on_connect = 0;
980 /* This variable is used to implement the "set/show remotebreak" commands.
981 Since these commands are now deprecated in favor of "set/show remote
982 interrupt-sequence", it no longer has any effect on the code. */
983 static int remote_break;
986 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
989 interrupt_sequence_mode = interrupt_sequence_break;
991 interrupt_sequence_mode = interrupt_sequence_control_c;
995 show_remotebreak (struct ui_file *file, int from_tty,
996 struct cmd_list_element *c,
1001 /* This variable sets the number of bits in an address that are to be
1002 sent in a memory ("M" or "m") packet. Normally, after stripping
1003 leading zeros, the entire address would be sent. This variable
1004 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1005 initial implementation of remote.c restricted the address sent in
1006 memory packets to ``host::sizeof long'' bytes - (typically 32
1007 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1008 address was never sent. Since fixing this bug may cause a break in
1009 some remote targets this variable is principly provided to
1010 facilitate backward compatibility. */
1012 static unsigned int remote_address_size;
1014 /* Temporary to track who currently owns the terminal. See
1015 remote_terminal_* for more details. */
1017 static int remote_async_terminal_ours_p;
1020 /* User configurable variables for the number of characters in a
1021 memory read/write packet. MIN (rsa->remote_packet_size,
1022 rsa->sizeof_g_packet) is the default. Some targets need smaller
1023 values (fifo overruns, et.al.) and some users need larger values
1024 (speed up transfers). The variables ``preferred_*'' (the user
1025 request), ``current_*'' (what was actually set) and ``forced_*''
1026 (Positive - a soft limit, negative - a hard limit). */
1028 struct memory_packet_config
1035 /* The default max memory-write-packet-size. The 16k is historical.
1036 (It came from older GDB's using alloca for buffers and the
1037 knowledge (folklore?) that some hosts don't cope very well with
1038 large alloca calls.) */
1039 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1041 /* The minimum remote packet size for memory transfers. Ensures we
1042 can write at least one byte. */
1043 #define MIN_MEMORY_PACKET_SIZE 20
1045 /* Compute the current size of a read/write packet. Since this makes
1046 use of ``actual_register_packet_size'' the computation is dynamic. */
1049 get_memory_packet_size (struct memory_packet_config *config)
1051 struct remote_state *rs = get_remote_state ();
1052 struct remote_arch_state *rsa = get_remote_arch_state ();
1055 if (config->fixed_p)
1057 if (config->size <= 0)
1058 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1060 what_they_get = config->size;
1064 what_they_get = get_remote_packet_size ();
1065 /* Limit the packet to the size specified by the user. */
1066 if (config->size > 0
1067 && what_they_get > config->size)
1068 what_they_get = config->size;
1070 /* Limit it to the size of the targets ``g'' response unless we have
1071 permission from the stub to use a larger packet size. */
1072 if (rs->explicit_packet_size == 0
1073 && rsa->actual_register_packet_size > 0
1074 && what_they_get > rsa->actual_register_packet_size)
1075 what_they_get = rsa->actual_register_packet_size;
1077 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1078 what_they_get = MIN_MEMORY_PACKET_SIZE;
1080 /* Make sure there is room in the global buffer for this packet
1081 (including its trailing NUL byte). */
1082 if (rs->buf_size < what_they_get + 1)
1084 rs->buf_size = 2 * what_they_get;
1085 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1088 return what_they_get;
1091 /* Update the size of a read/write packet. If they user wants
1092 something really big then do a sanity check. */
1095 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1097 int fixed_p = config->fixed_p;
1098 long size = config->size;
1101 error (_("Argument required (integer, `fixed' or `limited')."));
1102 else if (strcmp (args, "hard") == 0
1103 || strcmp (args, "fixed") == 0)
1105 else if (strcmp (args, "soft") == 0
1106 || strcmp (args, "limit") == 0)
1112 size = strtoul (args, &end, 0);
1114 error (_("Invalid %s (bad syntax)."), config->name);
1116 /* Instead of explicitly capping the size of a packet to or
1117 disallowing it, the user is allowed to set the size to
1118 something arbitrarily large. */
1121 /* So that the query shows the correct value. */
1123 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1126 if (fixed_p && !config->fixed_p)
1128 if (! query (_("The target may not be able to correctly handle a %s\n"
1129 "of %ld bytes. Change the packet size? "),
1130 config->name, size))
1131 error (_("Packet size not changed."));
1133 /* Update the config. */
1134 config->fixed_p = fixed_p;
1135 config->size = size;
1139 show_memory_packet_size (struct memory_packet_config *config)
1141 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1142 if (config->fixed_p)
1143 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1144 get_memory_packet_size (config));
1146 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1147 get_memory_packet_size (config));
1150 static struct memory_packet_config memory_write_packet_config =
1152 "memory-write-packet-size",
1156 set_memory_write_packet_size (const char *args, int from_tty)
1158 set_memory_packet_size (args, &memory_write_packet_config);
1162 show_memory_write_packet_size (const char *args, int from_tty)
1164 show_memory_packet_size (&memory_write_packet_config);
1168 get_memory_write_packet_size (void)
1170 return get_memory_packet_size (&memory_write_packet_config);
1173 static struct memory_packet_config memory_read_packet_config =
1175 "memory-read-packet-size",
1179 set_memory_read_packet_size (const char *args, int from_tty)
1181 set_memory_packet_size (args, &memory_read_packet_config);
1185 show_memory_read_packet_size (const char *args, int from_tty)
1187 show_memory_packet_size (&memory_read_packet_config);
1191 get_memory_read_packet_size (void)
1193 long size = get_memory_packet_size (&memory_read_packet_config);
1195 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1196 extra buffer size argument before the memory read size can be
1197 increased beyond this. */
1198 if (size > get_remote_packet_size ())
1199 size = get_remote_packet_size ();
1204 /* Generic configuration support for packets the stub optionally
1205 supports. Allows the user to specify the use of the packet as well
1206 as allowing GDB to auto-detect support in the remote stub. */
1210 PACKET_SUPPORT_UNKNOWN = 0,
1215 struct packet_config
1220 /* If auto, GDB auto-detects support for this packet or feature,
1221 either through qSupported, or by trying the packet and looking
1222 at the response. If true, GDB assumes the target supports this
1223 packet. If false, the packet is disabled. Configs that don't
1224 have an associated command always have this set to auto. */
1225 enum auto_boolean detect;
1227 /* Does the target support this packet? */
1228 enum packet_support support;
1231 /* Analyze a packet's return value and update the packet config
1241 static enum packet_support packet_config_support (struct packet_config *config);
1242 static enum packet_support packet_support (int packet);
1245 show_packet_config_cmd (struct packet_config *config)
1247 const char *support = "internal-error";
1249 switch (packet_config_support (config))
1252 support = "enabled";
1254 case PACKET_DISABLE:
1255 support = "disabled";
1257 case PACKET_SUPPORT_UNKNOWN:
1258 support = "unknown";
1261 switch (config->detect)
1263 case AUTO_BOOLEAN_AUTO:
1264 printf_filtered (_("Support for the `%s' packet "
1265 "is auto-detected, currently %s.\n"),
1266 config->name, support);
1268 case AUTO_BOOLEAN_TRUE:
1269 case AUTO_BOOLEAN_FALSE:
1270 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1271 config->name, support);
1277 add_packet_config_cmd (struct packet_config *config, const char *name,
1278 const char *title, int legacy)
1284 config->name = name;
1285 config->title = title;
1286 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1288 show_doc = xstrprintf ("Show current use of remote "
1289 "protocol `%s' (%s) packet",
1291 /* set/show TITLE-packet {auto,on,off} */
1292 cmd_name = xstrprintf ("%s-packet", title);
1293 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1294 &config->detect, set_doc,
1295 show_doc, NULL, /* help_doc */
1297 show_remote_protocol_packet_cmd,
1298 &remote_set_cmdlist, &remote_show_cmdlist);
1299 /* The command code copies the documentation strings. */
1302 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1307 legacy_name = xstrprintf ("%s-packet", name);
1308 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1309 &remote_set_cmdlist);
1310 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1311 &remote_show_cmdlist);
1315 static enum packet_result
1316 packet_check_result (const char *buf)
1320 /* The stub recognized the packet request. Check that the
1321 operation succeeded. */
1323 && isxdigit (buf[1]) && isxdigit (buf[2])
1325 /* "Enn" - definitly an error. */
1326 return PACKET_ERROR;
1328 /* Always treat "E." as an error. This will be used for
1329 more verbose error messages, such as E.memtypes. */
1330 if (buf[0] == 'E' && buf[1] == '.')
1331 return PACKET_ERROR;
1333 /* The packet may or may not be OK. Just assume it is. */
1337 /* The stub does not support the packet. */
1338 return PACKET_UNKNOWN;
1341 static enum packet_result
1342 packet_ok (const char *buf, struct packet_config *config)
1344 enum packet_result result;
1346 if (config->detect != AUTO_BOOLEAN_TRUE
1347 && config->support == PACKET_DISABLE)
1348 internal_error (__FILE__, __LINE__,
1349 _("packet_ok: attempt to use a disabled packet"));
1351 result = packet_check_result (buf);
1356 /* The stub recognized the packet request. */
1357 if (config->support == PACKET_SUPPORT_UNKNOWN)
1360 fprintf_unfiltered (gdb_stdlog,
1361 "Packet %s (%s) is supported\n",
1362 config->name, config->title);
1363 config->support = PACKET_ENABLE;
1366 case PACKET_UNKNOWN:
1367 /* The stub does not support the packet. */
1368 if (config->detect == AUTO_BOOLEAN_AUTO
1369 && config->support == PACKET_ENABLE)
1371 /* If the stub previously indicated that the packet was
1372 supported then there is a protocol error. */
1373 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1374 config->name, config->title);
1376 else if (config->detect == AUTO_BOOLEAN_TRUE)
1378 /* The user set it wrong. */
1379 error (_("Enabled packet %s (%s) not recognized by stub"),
1380 config->name, config->title);
1384 fprintf_unfiltered (gdb_stdlog,
1385 "Packet %s (%s) is NOT supported\n",
1386 config->name, config->title);
1387 config->support = PACKET_DISABLE;
1408 PACKET_vFile_pwrite,
1410 PACKET_vFile_unlink,
1411 PACKET_vFile_readlink,
1414 PACKET_qXfer_features,
1415 PACKET_qXfer_exec_file,
1416 PACKET_qXfer_libraries,
1417 PACKET_qXfer_libraries_svr4,
1418 PACKET_qXfer_memory_map,
1419 PACKET_qXfer_spu_read,
1420 PACKET_qXfer_spu_write,
1421 PACKET_qXfer_osdata,
1422 PACKET_qXfer_threads,
1423 PACKET_qXfer_statictrace_read,
1424 PACKET_qXfer_traceframe_info,
1430 PACKET_QPassSignals,
1431 PACKET_QCatchSyscalls,
1432 PACKET_QProgramSignals,
1433 PACKET_QStartupWithShell,
1434 PACKET_QEnvironmentHexEncoded,
1435 PACKET_QEnvironmentReset,
1436 PACKET_QEnvironmentUnset,
1438 PACKET_qSearch_memory,
1441 PACKET_QStartNoAckMode,
1443 PACKET_qXfer_siginfo_read,
1444 PACKET_qXfer_siginfo_write,
1447 /* Support for conditional tracepoints. */
1448 PACKET_ConditionalTracepoints,
1450 /* Support for target-side breakpoint conditions. */
1451 PACKET_ConditionalBreakpoints,
1453 /* Support for target-side breakpoint commands. */
1454 PACKET_BreakpointCommands,
1456 /* Support for fast tracepoints. */
1457 PACKET_FastTracepoints,
1459 /* Support for static tracepoints. */
1460 PACKET_StaticTracepoints,
1462 /* Support for installing tracepoints while a trace experiment is
1464 PACKET_InstallInTrace,
1468 PACKET_TracepointSource,
1471 PACKET_QDisableRandomization,
1473 PACKET_QTBuffer_size,
1477 PACKET_qXfer_btrace,
1479 /* Support for the QNonStop packet. */
1482 /* Support for the QThreadEvents packet. */
1483 PACKET_QThreadEvents,
1485 /* Support for multi-process extensions. */
1486 PACKET_multiprocess_feature,
1488 /* Support for enabling and disabling tracepoints while a trace
1489 experiment is running. */
1490 PACKET_EnableDisableTracepoints_feature,
1492 /* Support for collecting strings using the tracenz bytecode. */
1493 PACKET_tracenz_feature,
1495 /* Support for continuing to run a trace experiment while GDB is
1497 PACKET_DisconnectedTracing_feature,
1499 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1500 PACKET_augmented_libraries_svr4_read_feature,
1502 /* Support for the qXfer:btrace-conf:read packet. */
1503 PACKET_qXfer_btrace_conf,
1505 /* Support for the Qbtrace-conf:bts:size packet. */
1506 PACKET_Qbtrace_conf_bts_size,
1508 /* Support for swbreak+ feature. */
1509 PACKET_swbreak_feature,
1511 /* Support for hwbreak+ feature. */
1512 PACKET_hwbreak_feature,
1514 /* Support for fork events. */
1515 PACKET_fork_event_feature,
1517 /* Support for vfork events. */
1518 PACKET_vfork_event_feature,
1520 /* Support for the Qbtrace-conf:pt:size packet. */
1521 PACKET_Qbtrace_conf_pt_size,
1523 /* Support for exec events. */
1524 PACKET_exec_event_feature,
1526 /* Support for query supported vCont actions. */
1527 PACKET_vContSupported,
1529 /* Support remote CTRL-C. */
1532 /* Support TARGET_WAITKIND_NO_RESUMED. */
1538 static struct packet_config remote_protocol_packets[PACKET_MAX];
1540 /* Returns the packet's corresponding "set remote foo-packet" command
1541 state. See struct packet_config for more details. */
1543 static enum auto_boolean
1544 packet_set_cmd_state (int packet)
1546 return remote_protocol_packets[packet].detect;
1549 /* Returns whether a given packet or feature is supported. This takes
1550 into account the state of the corresponding "set remote foo-packet"
1551 command, which may be used to bypass auto-detection. */
1553 static enum packet_support
1554 packet_config_support (struct packet_config *config)
1556 switch (config->detect)
1558 case AUTO_BOOLEAN_TRUE:
1559 return PACKET_ENABLE;
1560 case AUTO_BOOLEAN_FALSE:
1561 return PACKET_DISABLE;
1562 case AUTO_BOOLEAN_AUTO:
1563 return config->support;
1565 gdb_assert_not_reached (_("bad switch"));
1569 /* Same as packet_config_support, but takes the packet's enum value as
1572 static enum packet_support
1573 packet_support (int packet)
1575 struct packet_config *config = &remote_protocol_packets[packet];
1577 return packet_config_support (config);
1581 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1582 struct cmd_list_element *c,
1585 struct packet_config *packet;
1587 for (packet = remote_protocol_packets;
1588 packet < &remote_protocol_packets[PACKET_MAX];
1591 if (&packet->detect == c->var)
1593 show_packet_config_cmd (packet);
1597 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1601 /* Should we try one of the 'Z' requests? */
1605 Z_PACKET_SOFTWARE_BP,
1606 Z_PACKET_HARDWARE_BP,
1613 /* For compatibility with older distributions. Provide a ``set remote
1614 Z-packet ...'' command that updates all the Z packet types. */
1616 static enum auto_boolean remote_Z_packet_detect;
1619 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1620 struct cmd_list_element *c)
1624 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1625 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1629 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1630 struct cmd_list_element *c,
1635 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1637 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1641 /* Returns true if the multi-process extensions are in effect. */
1644 remote_multi_process_p (struct remote_state *rs)
1646 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1649 /* Returns true if fork events are supported. */
1652 remote_fork_event_p (struct remote_state *rs)
1654 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1657 /* Returns true if vfork events are supported. */
1660 remote_vfork_event_p (struct remote_state *rs)
1662 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1665 /* Returns true if exec events are supported. */
1668 remote_exec_event_p (struct remote_state *rs)
1670 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1673 /* Insert fork catchpoint target routine. If fork events are enabled
1674 then return success, nothing more to do. */
1677 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1679 struct remote_state *rs = get_remote_state ();
1681 return !remote_fork_event_p (rs);
1684 /* Remove fork catchpoint target routine. Nothing to do, just
1688 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1693 /* Insert vfork catchpoint target routine. If vfork events are enabled
1694 then return success, nothing more to do. */
1697 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1699 struct remote_state *rs = get_remote_state ();
1701 return !remote_vfork_event_p (rs);
1704 /* Remove vfork catchpoint target routine. Nothing to do, just
1708 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1713 /* Insert exec catchpoint target routine. If exec events are
1714 enabled, just return success. */
1717 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1719 struct remote_state *rs = get_remote_state ();
1721 return !remote_exec_event_p (rs);
1724 /* Remove exec catchpoint target routine. Nothing to do, just
1728 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1734 /* Asynchronous signal handle registered as event loop source for
1735 when we have pending events ready to be passed to the core. */
1737 static struct async_event_handler *remote_async_inferior_event_token;
1741 static ptid_t magic_null_ptid;
1742 static ptid_t not_sent_ptid;
1743 static ptid_t any_thread_ptid;
1745 /* Find out if the stub attached to PID (and hence GDB should offer to
1746 detach instead of killing it when bailing out). */
1749 remote_query_attached (int pid)
1751 struct remote_state *rs = get_remote_state ();
1752 size_t size = get_remote_packet_size ();
1754 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1757 if (remote_multi_process_p (rs))
1758 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1760 xsnprintf (rs->buf, size, "qAttached");
1763 getpkt (&rs->buf, &rs->buf_size, 0);
1765 switch (packet_ok (rs->buf,
1766 &remote_protocol_packets[PACKET_qAttached]))
1769 if (strcmp (rs->buf, "1") == 0)
1773 warning (_("Remote failure reply: %s"), rs->buf);
1775 case PACKET_UNKNOWN:
1782 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1783 has been invented by GDB, instead of reported by the target. Since
1784 we can be connected to a remote system before before knowing about
1785 any inferior, mark the target with execution when we find the first
1786 inferior. If ATTACHED is 1, then we had just attached to this
1787 inferior. If it is 0, then we just created this inferior. If it
1788 is -1, then try querying the remote stub to find out if it had
1789 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1790 attempt to open this inferior's executable as the main executable
1791 if no main executable is open already. */
1793 static struct inferior *
1794 remote_add_inferior (int fake_pid_p, int pid, int attached,
1797 struct inferior *inf;
1799 /* Check whether this process we're learning about is to be
1800 considered attached, or if is to be considered to have been
1801 spawned by the stub. */
1803 attached = remote_query_attached (pid);
1805 if (gdbarch_has_global_solist (target_gdbarch ()))
1807 /* If the target shares code across all inferiors, then every
1808 attach adds a new inferior. */
1809 inf = add_inferior (pid);
1811 /* ... and every inferior is bound to the same program space.
1812 However, each inferior may still have its own address
1814 inf->aspace = maybe_new_address_space ();
1815 inf->pspace = current_program_space;
1819 /* In the traditional debugging scenario, there's a 1-1 match
1820 between program/address spaces. We simply bind the inferior
1821 to the program space's address space. */
1822 inf = current_inferior ();
1823 inferior_appeared (inf, pid);
1826 inf->attach_flag = attached;
1827 inf->fake_pid_p = fake_pid_p;
1829 /* If no main executable is currently open then attempt to
1830 open the file that was executed to create this inferior. */
1831 if (try_open_exec && get_exec_file (0) == NULL)
1832 exec_file_locate_attach (pid, 0, 1);
1837 static struct private_thread_info *
1838 get_private_info_thread (struct thread_info *info);
1840 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1841 according to RUNNING. */
1844 remote_add_thread (ptid_t ptid, int running, int executing)
1846 struct remote_state *rs = get_remote_state ();
1847 struct thread_info *thread;
1849 /* GDB historically didn't pull threads in the initial connection
1850 setup. If the remote target doesn't even have a concept of
1851 threads (e.g., a bare-metal target), even if internally we
1852 consider that a single-threaded target, mentioning a new thread
1853 might be confusing to the user. Be silent then, preserving the
1854 age old behavior. */
1855 if (rs->starting_up)
1856 thread = add_thread_silent (ptid);
1858 thread = add_thread (ptid);
1860 get_private_info_thread (thread)->vcont_resumed = executing;
1861 set_executing (ptid, executing);
1862 set_running (ptid, running);
1865 /* Come here when we learn about a thread id from the remote target.
1866 It may be the first time we hear about such thread, so take the
1867 opportunity to add it to GDB's thread list. In case this is the
1868 first time we're noticing its corresponding inferior, add it to
1869 GDB's inferior list as well. EXECUTING indicates whether the
1870 thread is (internally) executing or stopped. */
1873 remote_notice_new_inferior (ptid_t currthread, int executing)
1875 /* In non-stop mode, we assume new found threads are (externally)
1876 running until proven otherwise with a stop reply. In all-stop,
1877 we can only get here if all threads are stopped. */
1878 int running = target_is_non_stop_p () ? 1 : 0;
1880 /* If this is a new thread, add it to GDB's thread list.
1881 If we leave it up to WFI to do this, bad things will happen. */
1883 if (in_thread_list (currthread) && is_exited (currthread))
1885 /* We're seeing an event on a thread id we knew had exited.
1886 This has to be a new thread reusing the old id. Add it. */
1887 remote_add_thread (currthread, running, executing);
1891 if (!in_thread_list (currthread))
1893 struct inferior *inf = NULL;
1894 int pid = ptid_get_pid (currthread);
1896 if (ptid_is_pid (inferior_ptid)
1897 && pid == ptid_get_pid (inferior_ptid))
1899 /* inferior_ptid has no thread member yet. This can happen
1900 with the vAttach -> remote_wait,"TAAthread:" path if the
1901 stub doesn't support qC. This is the first stop reported
1902 after an attach, so this is the main thread. Update the
1903 ptid in the thread list. */
1904 if (in_thread_list (pid_to_ptid (pid)))
1905 thread_change_ptid (inferior_ptid, currthread);
1908 remote_add_thread (currthread, running, executing);
1909 inferior_ptid = currthread;
1914 if (ptid_equal (magic_null_ptid, inferior_ptid))
1916 /* inferior_ptid is not set yet. This can happen with the
1917 vRun -> remote_wait,"TAAthread:" path if the stub
1918 doesn't support qC. This is the first stop reported
1919 after an attach, so this is the main thread. Update the
1920 ptid in the thread list. */
1921 thread_change_ptid (inferior_ptid, currthread);
1925 /* When connecting to a target remote, or to a target
1926 extended-remote which already was debugging an inferior, we
1927 may not know about it yet. Add it before adding its child
1928 thread, so notifications are emitted in a sensible order. */
1929 if (!in_inferior_list (ptid_get_pid (currthread)))
1931 struct remote_state *rs = get_remote_state ();
1932 int fake_pid_p = !remote_multi_process_p (rs);
1934 inf = remote_add_inferior (fake_pid_p,
1935 ptid_get_pid (currthread), -1, 1);
1938 /* This is really a new thread. Add it. */
1939 remote_add_thread (currthread, running, executing);
1941 /* If we found a new inferior, let the common code do whatever
1942 it needs to with it (e.g., read shared libraries, insert
1943 breakpoints), unless we're just setting up an all-stop
1947 struct remote_state *rs = get_remote_state ();
1949 if (!rs->starting_up)
1950 notice_new_inferior (currthread, executing, 0);
1955 /* Return THREAD's private thread data, creating it if necessary. */
1957 static struct private_thread_info *
1958 get_private_info_thread (struct thread_info *thread)
1960 gdb_assert (thread != NULL);
1962 if (thread->priv == NULL)
1964 struct private_thread_info *priv = XNEW (struct private_thread_info);
1966 thread->private_dtor = free_private_thread_info;
1967 thread->priv = priv;
1973 priv->last_resume_step = 0;
1974 priv->last_resume_sig = GDB_SIGNAL_0;
1975 priv->vcont_resumed = 0;
1976 priv->thread_handle = nullptr;
1979 return thread->priv;
1982 /* Return PTID's private thread data, creating it if necessary. */
1984 static struct private_thread_info *
1985 get_private_info_ptid (ptid_t ptid)
1987 struct thread_info *info = find_thread_ptid (ptid);
1989 return get_private_info_thread (info);
1992 /* Call this function as a result of
1993 1) A halt indication (T packet) containing a thread id
1994 2) A direct query of currthread
1995 3) Successful execution of set thread */
1998 record_currthread (struct remote_state *rs, ptid_t currthread)
2000 rs->general_thread = currthread;
2003 /* If 'QPassSignals' is supported, tell the remote stub what signals
2004 it can simply pass through to the inferior without reporting. */
2007 remote_pass_signals (struct target_ops *self,
2008 int numsigs, unsigned char *pass_signals)
2010 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2012 char *pass_packet, *p;
2014 struct remote_state *rs = get_remote_state ();
2016 gdb_assert (numsigs < 256);
2017 for (i = 0; i < numsigs; i++)
2019 if (pass_signals[i])
2022 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2023 strcpy (pass_packet, "QPassSignals:");
2024 p = pass_packet + strlen (pass_packet);
2025 for (i = 0; i < numsigs; i++)
2027 if (pass_signals[i])
2030 *p++ = tohex (i >> 4);
2031 *p++ = tohex (i & 15);
2040 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2042 putpkt (pass_packet);
2043 getpkt (&rs->buf, &rs->buf_size, 0);
2044 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2045 if (rs->last_pass_packet)
2046 xfree (rs->last_pass_packet);
2047 rs->last_pass_packet = pass_packet;
2050 xfree (pass_packet);
2054 /* If 'QCatchSyscalls' is supported, tell the remote stub
2055 to report syscalls to GDB. */
2058 remote_set_syscall_catchpoint (struct target_ops *self,
2059 int pid, int needed, int any_count,
2060 int table_size, int *table)
2063 enum packet_result result;
2066 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2068 /* Not supported. */
2072 if (needed && !any_count)
2076 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2077 for (i = 0; i < table_size; i++)
2086 fprintf_unfiltered (gdb_stdlog,
2087 "remote_set_syscall_catchpoint "
2088 "pid %d needed %d any_count %d n_sysno %d\n",
2089 pid, needed, any_count, n_sysno);
2094 /* Prepare a packet with the sysno list, assuming max 8+1
2095 characters for a sysno. If the resulting packet size is too
2096 big, fallback on the non-selective packet. */
2097 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2099 catch_packet = (char *) xmalloc (maxpktsz);
2100 strcpy (catch_packet, "QCatchSyscalls:1");
2109 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2110 for (i = 0; i < table_size; i++)
2113 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2116 if (strlen (catch_packet) > get_remote_packet_size ())
2118 /* catch_packet too big. Fallback to less efficient
2119 non selective mode, with GDB doing the filtering. */
2120 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2124 catch_packet = xstrdup ("QCatchSyscalls:0");
2127 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2128 struct remote_state *rs = get_remote_state ();
2130 putpkt (catch_packet);
2131 getpkt (&rs->buf, &rs->buf_size, 0);
2132 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2133 do_cleanups (old_chain);
2134 if (result == PACKET_OK)
2141 /* If 'QProgramSignals' is supported, tell the remote stub what
2142 signals it should pass through to the inferior when detaching. */
2145 remote_program_signals (struct target_ops *self,
2146 int numsigs, unsigned char *signals)
2148 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2152 struct remote_state *rs = get_remote_state ();
2154 gdb_assert (numsigs < 256);
2155 for (i = 0; i < numsigs; i++)
2160 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2161 strcpy (packet, "QProgramSignals:");
2162 p = packet + strlen (packet);
2163 for (i = 0; i < numsigs; i++)
2165 if (signal_pass_state (i))
2168 *p++ = tohex (i >> 4);
2169 *p++ = tohex (i & 15);
2178 if (!rs->last_program_signals_packet
2179 || strcmp (rs->last_program_signals_packet, packet) != 0)
2182 getpkt (&rs->buf, &rs->buf_size, 0);
2183 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2184 xfree (rs->last_program_signals_packet);
2185 rs->last_program_signals_packet = packet;
2192 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2193 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2194 thread. If GEN is set, set the general thread, if not, then set
2195 the step/continue thread. */
2197 set_thread (ptid_t ptid, int gen)
2199 struct remote_state *rs = get_remote_state ();
2200 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2201 char *buf = rs->buf;
2202 char *endbuf = rs->buf + get_remote_packet_size ();
2204 if (ptid_equal (state, ptid))
2208 *buf++ = gen ? 'g' : 'c';
2209 if (ptid_equal (ptid, magic_null_ptid))
2210 xsnprintf (buf, endbuf - buf, "0");
2211 else if (ptid_equal (ptid, any_thread_ptid))
2212 xsnprintf (buf, endbuf - buf, "0");
2213 else if (ptid_equal (ptid, minus_one_ptid))
2214 xsnprintf (buf, endbuf - buf, "-1");
2216 write_ptid (buf, endbuf, ptid);
2218 getpkt (&rs->buf, &rs->buf_size, 0);
2220 rs->general_thread = ptid;
2222 rs->continue_thread = ptid;
2226 set_general_thread (ptid_t ptid)
2228 set_thread (ptid, 1);
2232 set_continue_thread (ptid_t ptid)
2234 set_thread (ptid, 0);
2237 /* Change the remote current process. Which thread within the process
2238 ends up selected isn't important, as long as it is the same process
2239 as what INFERIOR_PTID points to.
2241 This comes from that fact that there is no explicit notion of
2242 "selected process" in the protocol. The selected process for
2243 general operations is the process the selected general thread
2247 set_general_process (void)
2249 struct remote_state *rs = get_remote_state ();
2251 /* If the remote can't handle multiple processes, don't bother. */
2252 if (!remote_multi_process_p (rs))
2255 /* We only need to change the remote current thread if it's pointing
2256 at some other process. */
2257 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2258 set_general_thread (inferior_ptid);
2262 /* Return nonzero if this is the main thread that we made up ourselves
2263 to model non-threaded targets as single-threaded. */
2266 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2268 if (ptid_equal (ptid, magic_null_ptid))
2269 /* The main thread is always alive. */
2272 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2273 /* The main thread is always alive. This can happen after a
2274 vAttach, if the remote side doesn't support
2281 /* Return nonzero if the thread PTID is still alive on the remote
2285 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2287 struct remote_state *rs = get_remote_state ();
2290 /* Check if this is a thread that we made up ourselves to model
2291 non-threaded targets as single-threaded. */
2292 if (remote_thread_always_alive (ops, ptid))
2296 endp = rs->buf + get_remote_packet_size ();
2299 write_ptid (p, endp, ptid);
2302 getpkt (&rs->buf, &rs->buf_size, 0);
2303 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2306 /* Return a pointer to a thread name if we know it and NULL otherwise.
2307 The thread_info object owns the memory for the name. */
2310 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2312 if (info->priv != NULL)
2313 return info->priv->name;
2318 /* About these extended threadlist and threadinfo packets. They are
2319 variable length packets but, the fields within them are often fixed
2320 length. They are redundent enough to send over UDP as is the
2321 remote protocol in general. There is a matching unit test module
2324 /* WARNING: This threadref data structure comes from the remote O.S.,
2325 libstub protocol encoding, and remote.c. It is not particularly
2328 /* Right now, the internal structure is int. We want it to be bigger.
2329 Plan to fix this. */
2331 typedef int gdb_threadref; /* Internal GDB thread reference. */
2333 /* gdb_ext_thread_info is an internal GDB data structure which is
2334 equivalent to the reply of the remote threadinfo packet. */
2336 struct gdb_ext_thread_info
2338 threadref threadid; /* External form of thread reference. */
2339 int active; /* Has state interesting to GDB?
2341 char display[256]; /* Brief state display, name,
2342 blocked/suspended. */
2343 char shortname[32]; /* To be used to name threads. */
2344 char more_display[256]; /* Long info, statistics, queue depth,
2348 /* The volume of remote transfers can be limited by submitting
2349 a mask containing bits specifying the desired information.
2350 Use a union of these values as the 'selection' parameter to
2351 get_thread_info. FIXME: Make these TAG names more thread specific. */
2353 #define TAG_THREADID 1
2354 #define TAG_EXISTS 2
2355 #define TAG_DISPLAY 4
2356 #define TAG_THREADNAME 8
2357 #define TAG_MOREDISPLAY 16
2359 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2361 static char *unpack_nibble (char *buf, int *val);
2363 static char *unpack_byte (char *buf, int *value);
2365 static char *pack_int (char *buf, int value);
2367 static char *unpack_int (char *buf, int *value);
2369 static char *unpack_string (char *src, char *dest, int length);
2371 static char *pack_threadid (char *pkt, threadref *id);
2373 static char *unpack_threadid (char *inbuf, threadref *id);
2375 void int_to_threadref (threadref *id, int value);
2377 static int threadref_to_int (threadref *ref);
2379 static void copy_threadref (threadref *dest, threadref *src);
2381 static int threadmatch (threadref *dest, threadref *src);
2383 static char *pack_threadinfo_request (char *pkt, int mode,
2386 static int remote_unpack_thread_info_response (char *pkt,
2387 threadref *expectedref,
2388 struct gdb_ext_thread_info
2392 static int remote_get_threadinfo (threadref *threadid,
2393 int fieldset, /*TAG mask */
2394 struct gdb_ext_thread_info *info);
2396 static char *pack_threadlist_request (char *pkt, int startflag,
2398 threadref *nextthread);
2400 static int parse_threadlist_response (char *pkt,
2402 threadref *original_echo,
2403 threadref *resultlist,
2406 static int remote_get_threadlist (int startflag,
2407 threadref *nextthread,
2411 threadref *threadlist);
2413 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2415 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2416 void *context, int looplimit);
2418 static int remote_newthread_step (threadref *ref, void *context);
2421 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2422 buffer we're allowed to write to. Returns
2423 BUF+CHARACTERS_WRITTEN. */
2426 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2429 struct remote_state *rs = get_remote_state ();
2431 if (remote_multi_process_p (rs))
2433 pid = ptid_get_pid (ptid);
2435 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2437 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2439 tid = ptid_get_lwp (ptid);
2441 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2443 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2448 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2449 passed the last parsed char. Returns null_ptid on error. */
2452 read_ptid (char *buf, char **obuf)
2456 ULONGEST pid = 0, tid = 0;
2460 /* Multi-process ptid. */
2461 pp = unpack_varlen_hex (p + 1, &pid);
2463 error (_("invalid remote ptid: %s"), p);
2466 pp = unpack_varlen_hex (p + 1, &tid);
2469 return ptid_build (pid, tid, 0);
2472 /* No multi-process. Just a tid. */
2473 pp = unpack_varlen_hex (p, &tid);
2475 /* Return null_ptid when no thread id is found. */
2483 /* Since the stub is not sending a process id, then default to
2484 what's in inferior_ptid, unless it's null at this point. If so,
2485 then since there's no way to know the pid of the reported
2486 threads, use the magic number. */
2487 if (ptid_equal (inferior_ptid, null_ptid))
2488 pid = ptid_get_pid (magic_null_ptid);
2490 pid = ptid_get_pid (inferior_ptid);
2494 return ptid_build (pid, tid, 0);
2500 if (ch >= 'a' && ch <= 'f')
2501 return ch - 'a' + 10;
2502 if (ch >= '0' && ch <= '9')
2504 if (ch >= 'A' && ch <= 'F')
2505 return ch - 'A' + 10;
2510 stub_unpack_int (char *buff, int fieldlength)
2517 nibble = stubhex (*buff++);
2521 retval = retval << 4;
2527 unpack_nibble (char *buf, int *val)
2529 *val = fromhex (*buf++);
2534 unpack_byte (char *buf, int *value)
2536 *value = stub_unpack_int (buf, 2);
2541 pack_int (char *buf, int value)
2543 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2544 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2545 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2546 buf = pack_hex_byte (buf, (value & 0xff));
2551 unpack_int (char *buf, int *value)
2553 *value = stub_unpack_int (buf, 8);
2557 #if 0 /* Currently unused, uncomment when needed. */
2558 static char *pack_string (char *pkt, char *string);
2561 pack_string (char *pkt, char *string)
2566 len = strlen (string);
2568 len = 200; /* Bigger than most GDB packets, junk??? */
2569 pkt = pack_hex_byte (pkt, len);
2573 if ((ch == '\0') || (ch == '#'))
2574 ch = '*'; /* Protect encapsulation. */
2579 #endif /* 0 (unused) */
2582 unpack_string (char *src, char *dest, int length)
2591 pack_threadid (char *pkt, threadref *id)
2594 unsigned char *altid;
2596 altid = (unsigned char *) id;
2597 limit = pkt + BUF_THREAD_ID_SIZE;
2599 pkt = pack_hex_byte (pkt, *altid++);
2605 unpack_threadid (char *inbuf, threadref *id)
2608 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2611 altref = (char *) id;
2613 while (inbuf < limit)
2615 x = stubhex (*inbuf++);
2616 y = stubhex (*inbuf++);
2617 *altref++ = (x << 4) | y;
2622 /* Externally, threadrefs are 64 bits but internally, they are still
2623 ints. This is due to a mismatch of specifications. We would like
2624 to use 64bit thread references internally. This is an adapter
2628 int_to_threadref (threadref *id, int value)
2630 unsigned char *scan;
2632 scan = (unsigned char *) id;
2638 *scan++ = (value >> 24) & 0xff;
2639 *scan++ = (value >> 16) & 0xff;
2640 *scan++ = (value >> 8) & 0xff;
2641 *scan++ = (value & 0xff);
2645 threadref_to_int (threadref *ref)
2648 unsigned char *scan;
2654 value = (value << 8) | ((*scan++) & 0xff);
2659 copy_threadref (threadref *dest, threadref *src)
2662 unsigned char *csrc, *cdest;
2664 csrc = (unsigned char *) src;
2665 cdest = (unsigned char *) dest;
2672 threadmatch (threadref *dest, threadref *src)
2674 /* Things are broken right now, so just assume we got a match. */
2676 unsigned char *srcp, *destp;
2678 srcp = (char *) src;
2679 destp = (char *) dest;
2683 result &= (*srcp++ == *destp++) ? 1 : 0;
2690 threadid:1, # always request threadid
2697 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2700 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2702 *pkt++ = 'q'; /* Info Query */
2703 *pkt++ = 'P'; /* process or thread info */
2704 pkt = pack_int (pkt, mode); /* mode */
2705 pkt = pack_threadid (pkt, id); /* threadid */
2706 *pkt = '\0'; /* terminate */
2710 /* These values tag the fields in a thread info response packet. */
2711 /* Tagging the fields allows us to request specific fields and to
2712 add more fields as time goes by. */
2714 #define TAG_THREADID 1 /* Echo the thread identifier. */
2715 #define TAG_EXISTS 2 /* Is this process defined enough to
2716 fetch registers and its stack? */
2717 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2718 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2719 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2723 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2724 struct gdb_ext_thread_info *info)
2726 struct remote_state *rs = get_remote_state ();
2730 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2733 /* info->threadid = 0; FIXME: implement zero_threadref. */
2735 info->display[0] = '\0';
2736 info->shortname[0] = '\0';
2737 info->more_display[0] = '\0';
2739 /* Assume the characters indicating the packet type have been
2741 pkt = unpack_int (pkt, &mask); /* arg mask */
2742 pkt = unpack_threadid (pkt, &ref);
2745 warning (_("Incomplete response to threadinfo request."));
2746 if (!threadmatch (&ref, expectedref))
2747 { /* This is an answer to a different request. */
2748 warning (_("ERROR RMT Thread info mismatch."));
2751 copy_threadref (&info->threadid, &ref);
2753 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2755 /* Packets are terminated with nulls. */
2756 while ((pkt < limit) && mask && *pkt)
2758 pkt = unpack_int (pkt, &tag); /* tag */
2759 pkt = unpack_byte (pkt, &length); /* length */
2760 if (!(tag & mask)) /* Tags out of synch with mask. */
2762 warning (_("ERROR RMT: threadinfo tag mismatch."));
2766 if (tag == TAG_THREADID)
2770 warning (_("ERROR RMT: length of threadid is not 16."));
2774 pkt = unpack_threadid (pkt, &ref);
2775 mask = mask & ~TAG_THREADID;
2778 if (tag == TAG_EXISTS)
2780 info->active = stub_unpack_int (pkt, length);
2782 mask = mask & ~(TAG_EXISTS);
2785 warning (_("ERROR RMT: 'exists' length too long."));
2791 if (tag == TAG_THREADNAME)
2793 pkt = unpack_string (pkt, &info->shortname[0], length);
2794 mask = mask & ~TAG_THREADNAME;
2797 if (tag == TAG_DISPLAY)
2799 pkt = unpack_string (pkt, &info->display[0], length);
2800 mask = mask & ~TAG_DISPLAY;
2803 if (tag == TAG_MOREDISPLAY)
2805 pkt = unpack_string (pkt, &info->more_display[0], length);
2806 mask = mask & ~TAG_MOREDISPLAY;
2809 warning (_("ERROR RMT: unknown thread info tag."));
2810 break; /* Not a tag we know about. */
2816 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2817 struct gdb_ext_thread_info *info)
2819 struct remote_state *rs = get_remote_state ();
2822 pack_threadinfo_request (rs->buf, fieldset, threadid);
2824 getpkt (&rs->buf, &rs->buf_size, 0);
2826 if (rs->buf[0] == '\0')
2829 result = remote_unpack_thread_info_response (rs->buf + 2,
2834 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2837 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2838 threadref *nextthread)
2840 *pkt++ = 'q'; /* info query packet */
2841 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2842 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2843 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2844 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2849 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2852 parse_threadlist_response (char *pkt, int result_limit,
2853 threadref *original_echo, threadref *resultlist,
2856 struct remote_state *rs = get_remote_state ();
2858 int count, resultcount, done;
2861 /* Assume the 'q' and 'M chars have been stripped. */
2862 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2863 /* done parse past here */
2864 pkt = unpack_byte (pkt, &count); /* count field */
2865 pkt = unpack_nibble (pkt, &done);
2866 /* The first threadid is the argument threadid. */
2867 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2868 while ((count-- > 0) && (pkt < limit))
2870 pkt = unpack_threadid (pkt, resultlist++);
2871 if (resultcount++ >= result_limit)
2879 /* Fetch the next batch of threads from the remote. Returns -1 if the
2880 qL packet is not supported, 0 on error and 1 on success. */
2883 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2884 int *done, int *result_count, threadref *threadlist)
2886 struct remote_state *rs = get_remote_state ();
2889 /* Trancate result limit to be smaller than the packet size. */
2890 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2891 >= get_remote_packet_size ())
2892 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2894 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2896 getpkt (&rs->buf, &rs->buf_size, 0);
2897 if (*rs->buf == '\0')
2899 /* Packet not supported. */
2904 parse_threadlist_response (rs->buf + 2, result_limit,
2905 &rs->echo_nextthread, threadlist, done);
2907 if (!threadmatch (&rs->echo_nextthread, nextthread))
2909 /* FIXME: This is a good reason to drop the packet. */
2910 /* Possably, there is a duplicate response. */
2912 retransmit immediatly - race conditions
2913 retransmit after timeout - yes
2915 wait for packet, then exit
2917 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2918 return 0; /* I choose simply exiting. */
2920 if (*result_count <= 0)
2924 warning (_("RMT ERROR : failed to get remote thread list."));
2927 return result; /* break; */
2929 if (*result_count > result_limit)
2932 warning (_("RMT ERROR: threadlist response longer than requested."));
2938 /* Fetch the list of remote threads, with the qL packet, and call
2939 STEPFUNCTION for each thread found. Stops iterating and returns 1
2940 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2941 STEPFUNCTION returns false. If the packet is not supported,
2945 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2948 struct remote_state *rs = get_remote_state ();
2949 int done, i, result_count;
2957 if (loopcount++ > looplimit)
2960 warning (_("Remote fetch threadlist -infinite loop-."));
2963 result = remote_get_threadlist (startflag, &rs->nextthread,
2964 MAXTHREADLISTRESULTS,
2965 &done, &result_count,
2966 rs->resultthreadlist);
2969 /* Clear for later iterations. */
2971 /* Setup to resume next batch of thread references, set nextthread. */
2972 if (result_count >= 1)
2973 copy_threadref (&rs->nextthread,
2974 &rs->resultthreadlist[result_count - 1]);
2976 while (result_count--)
2978 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2988 /* A thread found on the remote target. */
2990 typedef struct thread_item
2992 /* The thread's PTID. */
2995 /* The thread's extra info. May be NULL. */
2998 /* The thread's name. May be NULL. */
3001 /* The core the thread was running on. -1 if not known. */
3004 /* The thread handle associated with the thread. */
3005 gdb::byte_vector *thread_handle;
3008 DEF_VEC_O(thread_item_t);
3010 /* Context passed around to the various methods listing remote
3011 threads. As new threads are found, they're added to the ITEMS
3014 struct threads_listing_context
3016 /* The threads found on the remote target. */
3017 VEC (thread_item_t) *items;
3020 /* Discard the contents of the constructed thread listing context. */
3023 clear_threads_listing_context (void *p)
3025 struct threads_listing_context *context
3026 = (struct threads_listing_context *) p;
3028 struct thread_item *item;
3030 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3032 xfree (item->extra);
3034 delete item->thread_handle;
3037 VEC_free (thread_item_t, context->items);
3040 /* Remove the thread specified as the related_pid field of WS
3041 from the CONTEXT list. */
3044 threads_listing_context_remove (struct target_waitstatus *ws,
3045 struct threads_listing_context *context)
3047 struct thread_item *item;
3049 ptid_t child_ptid = ws->value.related_pid;
3051 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3053 if (ptid_equal (item->ptid, child_ptid))
3055 VEC_ordered_remove (thread_item_t, context->items, i);
3062 remote_newthread_step (threadref *ref, void *data)
3064 struct threads_listing_context *context
3065 = (struct threads_listing_context *) data;
3066 struct thread_item item;
3067 int pid = ptid_get_pid (inferior_ptid);
3069 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3073 item.thread_handle = nullptr;
3075 VEC_safe_push (thread_item_t, context->items, &item);
3077 return 1; /* continue iterator */
3080 #define CRAZY_MAX_THREADS 1000
3083 remote_current_thread (ptid_t oldpid)
3085 struct remote_state *rs = get_remote_state ();
3088 getpkt (&rs->buf, &rs->buf_size, 0);
3089 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3094 result = read_ptid (&rs->buf[2], &obuf);
3095 if (*obuf != '\0' && remote_debug)
3096 fprintf_unfiltered (gdb_stdlog,
3097 "warning: garbage in qC reply\n");
3105 /* List remote threads using the deprecated qL packet. */
3108 remote_get_threads_with_ql (struct target_ops *ops,
3109 struct threads_listing_context *context)
3111 if (remote_threadlist_iterator (remote_newthread_step, context,
3112 CRAZY_MAX_THREADS) >= 0)
3118 #if defined(HAVE_LIBEXPAT)
3121 start_thread (struct gdb_xml_parser *parser,
3122 const struct gdb_xml_element *element,
3123 void *user_data, VEC(gdb_xml_value_s) *attributes)
3125 struct threads_listing_context *data
3126 = (struct threads_listing_context *) user_data;
3128 struct thread_item item;
3130 struct gdb_xml_value *attr;
3132 id = (char *) xml_find_attribute (attributes, "id")->value;
3133 item.ptid = read_ptid (id, NULL);
3135 attr = xml_find_attribute (attributes, "core");
3137 item.core = *(ULONGEST *) attr->value;
3141 attr = xml_find_attribute (attributes, "name");
3142 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
3144 attr = xml_find_attribute (attributes, "handle");
3147 item.thread_handle = new gdb::byte_vector
3148 (strlen ((const char *) attr->value) / 2);
3149 hex2bin ((const char *) attr->value, item.thread_handle->data (),
3150 item.thread_handle->size ());
3153 item.thread_handle = nullptr;
3157 VEC_safe_push (thread_item_t, data->items, &item);
3161 end_thread (struct gdb_xml_parser *parser,
3162 const struct gdb_xml_element *element,
3163 void *user_data, const char *body_text)
3165 struct threads_listing_context *data
3166 = (struct threads_listing_context *) user_data;
3168 if (body_text && *body_text)
3169 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
3172 const struct gdb_xml_attribute thread_attributes[] = {
3173 { "id", GDB_XML_AF_NONE, NULL, NULL },
3174 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3175 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3176 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3177 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3180 const struct gdb_xml_element thread_children[] = {
3181 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3184 const struct gdb_xml_element threads_children[] = {
3185 { "thread", thread_attributes, thread_children,
3186 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3187 start_thread, end_thread },
3188 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3191 const struct gdb_xml_element threads_elements[] = {
3192 { "threads", NULL, threads_children,
3193 GDB_XML_EF_NONE, NULL, NULL },
3194 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3199 /* List remote threads using qXfer:threads:read. */
3202 remote_get_threads_with_qxfer (struct target_ops *ops,
3203 struct threads_listing_context *context)
3205 #if defined(HAVE_LIBEXPAT)
3206 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3208 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3209 struct cleanup *back_to = make_cleanup (xfree, xml);
3211 if (xml != NULL && *xml != '\0')
3213 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3214 threads_elements, xml, context);
3217 do_cleanups (back_to);
3225 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3228 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3229 struct threads_listing_context *context)
3231 struct remote_state *rs = get_remote_state ();
3233 if (rs->use_threadinfo_query)
3237 putpkt ("qfThreadInfo");
3238 getpkt (&rs->buf, &rs->buf_size, 0);
3240 if (bufp[0] != '\0') /* q packet recognized */
3242 while (*bufp++ == 'm') /* reply contains one or more TID */
3246 struct thread_item item;
3248 item.ptid = read_ptid (bufp, &bufp);
3252 item.thread_handle = nullptr;
3254 VEC_safe_push (thread_item_t, context->items, &item);
3256 while (*bufp++ == ','); /* comma-separated list */
3257 putpkt ("qsThreadInfo");
3258 getpkt (&rs->buf, &rs->buf_size, 0);
3265 /* Packet not recognized. */
3266 rs->use_threadinfo_query = 0;
3273 /* Implement the to_update_thread_list function for the remote
3277 remote_update_thread_list (struct target_ops *ops)
3279 struct threads_listing_context context;
3280 struct cleanup *old_chain;
3283 context.items = NULL;
3284 old_chain = make_cleanup (clear_threads_listing_context, &context);
3286 /* We have a few different mechanisms to fetch the thread list. Try
3287 them all, starting with the most preferred one first, falling
3288 back to older methods. */
3289 if (remote_get_threads_with_qxfer (ops, &context)
3290 || remote_get_threads_with_qthreadinfo (ops, &context)
3291 || remote_get_threads_with_ql (ops, &context))
3294 struct thread_item *item;
3295 struct thread_info *tp, *tmp;
3299 if (VEC_empty (thread_item_t, context.items)
3300 && remote_thread_always_alive (ops, inferior_ptid))
3302 /* Some targets don't really support threads, but still
3303 reply an (empty) thread list in response to the thread
3304 listing packets, instead of replying "packet not
3305 supported". Exit early so we don't delete the main
3307 do_cleanups (old_chain);
3311 /* CONTEXT now holds the current thread list on the remote
3312 target end. Delete GDB-side threads no longer found on the
3314 ALL_THREADS_SAFE (tp, tmp)
3317 VEC_iterate (thread_item_t, context.items, i, item);
3320 if (ptid_equal (item->ptid, tp->ptid))
3324 if (i == VEC_length (thread_item_t, context.items))
3327 delete_thread (tp->ptid);
3331 /* Remove any unreported fork child threads from CONTEXT so
3332 that we don't interfere with follow fork, which is where
3333 creation of such threads is handled. */
3334 remove_new_fork_children (&context);
3336 /* And now add threads we don't know about yet to our list. */
3338 VEC_iterate (thread_item_t, context.items, i, item);
3341 if (!ptid_equal (item->ptid, null_ptid))
3343 struct private_thread_info *info;
3344 /* In non-stop mode, we assume new found threads are
3345 executing until proven otherwise with a stop reply.
3346 In all-stop, we can only get here if all threads are
3348 int executing = target_is_non_stop_p () ? 1 : 0;
3350 remote_notice_new_inferior (item->ptid, executing);
3352 info = get_private_info_ptid (item->ptid);
3353 info->core = item->core;
3354 info->extra = item->extra;
3356 info->name = item->name;
3358 info->thread_handle = item->thread_handle;
3359 item->thread_handle = nullptr;
3366 /* If no thread listing method is supported, then query whether
3367 each known thread is alive, one by one, with the T packet.
3368 If the target doesn't support threads at all, then this is a
3369 no-op. See remote_thread_alive. */
3373 do_cleanups (old_chain);
3377 * Collect a descriptive string about the given thread.
3378 * The target may say anything it wants to about the thread
3379 * (typically info about its blocked / runnable state, name, etc.).
3380 * This string will appear in the info threads display.
3382 * Optional: targets are not required to implement this function.
3386 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3388 struct remote_state *rs = get_remote_state ();
3392 struct gdb_ext_thread_info threadinfo;
3393 static char display_buf[100]; /* arbitrary... */
3394 int n = 0; /* position in display_buf */
3396 if (rs->remote_desc == 0) /* paranoia */
3397 internal_error (__FILE__, __LINE__,
3398 _("remote_threads_extra_info"));
3400 if (ptid_equal (tp->ptid, magic_null_ptid)
3401 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3402 /* This is the main thread which was added by GDB. The remote
3403 server doesn't know about it. */
3406 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3408 struct thread_info *info = find_thread_ptid (tp->ptid);
3410 if (info && info->priv)
3411 return info->priv->extra;
3416 if (rs->use_threadextra_query)
3419 char *endb = rs->buf + get_remote_packet_size ();
3421 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3423 write_ptid (b, endb, tp->ptid);
3426 getpkt (&rs->buf, &rs->buf_size, 0);
3427 if (rs->buf[0] != 0)
3429 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3430 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3431 display_buf [result] = '\0';
3436 /* If the above query fails, fall back to the old method. */
3437 rs->use_threadextra_query = 0;
3438 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3439 | TAG_MOREDISPLAY | TAG_DISPLAY;
3440 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3441 if (remote_get_threadinfo (&id, set, &threadinfo))
3442 if (threadinfo.active)
3444 if (*threadinfo.shortname)
3445 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3446 " Name: %s,", threadinfo.shortname);
3447 if (*threadinfo.display)
3448 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3449 " State: %s,", threadinfo.display);
3450 if (*threadinfo.more_display)
3451 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3452 " Priority: %s", threadinfo.more_display);
3456 /* For purely cosmetic reasons, clear up trailing commas. */
3457 if (',' == display_buf[n-1])
3458 display_buf[n-1] = ' ';
3467 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3468 struct static_tracepoint_marker *marker)
3470 struct remote_state *rs = get_remote_state ();
3473 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3475 p += hexnumstr (p, addr);
3477 getpkt (&rs->buf, &rs->buf_size, 0);
3481 error (_("Remote failure reply: %s"), p);
3485 parse_static_tracepoint_marker_definition (p, &p, marker);
3492 static VEC(static_tracepoint_marker_p) *
3493 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3496 struct remote_state *rs = get_remote_state ();
3497 VEC(static_tracepoint_marker_p) *markers = NULL;
3498 struct static_tracepoint_marker *marker = NULL;
3499 struct cleanup *old_chain;
3502 /* Ask for a first packet of static tracepoint marker
3505 getpkt (&rs->buf, &rs->buf_size, 0);
3508 error (_("Remote failure reply: %s"), p);
3510 old_chain = make_cleanup (free_current_marker, &marker);
3515 marker = XCNEW (struct static_tracepoint_marker);
3519 parse_static_tracepoint_marker_definition (p, &p, marker);
3521 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3523 VEC_safe_push (static_tracepoint_marker_p,
3529 release_static_tracepoint_marker (marker);
3530 memset (marker, 0, sizeof (*marker));
3533 while (*p++ == ','); /* comma-separated list */
3534 /* Ask for another packet of static tracepoint definition. */
3536 getpkt (&rs->buf, &rs->buf_size, 0);
3540 do_cleanups (old_chain);
3545 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3548 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3550 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3554 /* Restart the remote side; this is an extended protocol operation. */
3557 extended_remote_restart (void)
3559 struct remote_state *rs = get_remote_state ();
3561 /* Send the restart command; for reasons I don't understand the
3562 remote side really expects a number after the "R". */
3563 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3566 remote_fileio_reset ();
3569 /* Clean up connection to a remote debugger. */
3572 remote_close (struct target_ops *self)
3574 struct remote_state *rs = get_remote_state ();
3576 if (rs->remote_desc == NULL)
3577 return; /* already closed */
3579 /* Make sure we leave stdin registered in the event loop. */
3580 remote_terminal_ours (self);
3582 serial_close (rs->remote_desc);
3583 rs->remote_desc = NULL;
3585 /* We don't have a connection to the remote stub anymore. Get rid
3586 of all the inferiors and their threads we were controlling.
3587 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3588 will be unable to find the thread corresponding to (pid, 0, 0). */
3589 inferior_ptid = null_ptid;
3590 discard_all_inferiors ();
3592 /* We are closing the remote target, so we should discard
3593 everything of this target. */
3594 discard_pending_stop_replies_in_queue (rs);
3596 if (remote_async_inferior_event_token)
3597 delete_async_event_handler (&remote_async_inferior_event_token);
3599 remote_notif_state_xfree (rs->notif_state);
3601 trace_reset_local_state ();
3604 /* Query the remote side for the text, data and bss offsets. */
3609 struct remote_state *rs = get_remote_state ();
3612 int lose, num_segments = 0, do_sections, do_segments;
3613 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3614 struct section_offsets *offs;
3615 struct symfile_segment_data *data;
3617 if (symfile_objfile == NULL)
3620 putpkt ("qOffsets");
3621 getpkt (&rs->buf, &rs->buf_size, 0);
3624 if (buf[0] == '\000')
3625 return; /* Return silently. Stub doesn't support
3629 warning (_("Remote failure reply: %s"), buf);
3633 /* Pick up each field in turn. This used to be done with scanf, but
3634 scanf will make trouble if CORE_ADDR size doesn't match
3635 conversion directives correctly. The following code will work
3636 with any size of CORE_ADDR. */
3637 text_addr = data_addr = bss_addr = 0;
3641 if (startswith (ptr, "Text="))
3644 /* Don't use strtol, could lose on big values. */
3645 while (*ptr && *ptr != ';')
3646 text_addr = (text_addr << 4) + fromhex (*ptr++);
3648 if (startswith (ptr, ";Data="))
3651 while (*ptr && *ptr != ';')
3652 data_addr = (data_addr << 4) + fromhex (*ptr++);
3657 if (!lose && startswith (ptr, ";Bss="))
3660 while (*ptr && *ptr != ';')
3661 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3663 if (bss_addr != data_addr)
3664 warning (_("Target reported unsupported offsets: %s"), buf);
3669 else if (startswith (ptr, "TextSeg="))
3672 /* Don't use strtol, could lose on big values. */
3673 while (*ptr && *ptr != ';')
3674 text_addr = (text_addr << 4) + fromhex (*ptr++);
3677 if (startswith (ptr, ";DataSeg="))
3680 while (*ptr && *ptr != ';')
3681 data_addr = (data_addr << 4) + fromhex (*ptr++);
3689 error (_("Malformed response to offset query, %s"), buf);
3690 else if (*ptr != '\0')
3691 warning (_("Target reported unsupported offsets: %s"), buf);
3693 offs = ((struct section_offsets *)
3694 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3695 memcpy (offs, symfile_objfile->section_offsets,
3696 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3698 data = get_symfile_segment_data (symfile_objfile->obfd);
3699 do_segments = (data != NULL);
3700 do_sections = num_segments == 0;
3702 if (num_segments > 0)
3704 segments[0] = text_addr;
3705 segments[1] = data_addr;
3707 /* If we have two segments, we can still try to relocate everything
3708 by assuming that the .text and .data offsets apply to the whole
3709 text and data segments. Convert the offsets given in the packet
3710 to base addresses for symfile_map_offsets_to_segments. */
3711 else if (data && data->num_segments == 2)
3713 segments[0] = data->segment_bases[0] + text_addr;
3714 segments[1] = data->segment_bases[1] + data_addr;
3717 /* If the object file has only one segment, assume that it is text
3718 rather than data; main programs with no writable data are rare,
3719 but programs with no code are useless. Of course the code might
3720 have ended up in the data segment... to detect that we would need
3721 the permissions here. */
3722 else if (data && data->num_segments == 1)
3724 segments[0] = data->segment_bases[0] + text_addr;
3727 /* There's no way to relocate by segment. */
3733 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3734 offs, num_segments, segments);
3736 if (ret == 0 && !do_sections)
3737 error (_("Can not handle qOffsets TextSeg "
3738 "response with this symbol file"));
3745 free_symfile_segment_data (data);
3749 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3751 /* This is a temporary kludge to force data and bss to use the
3752 same offsets because that's what nlmconv does now. The real
3753 solution requires changes to the stub and remote.c that I
3754 don't have time to do right now. */
3756 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3757 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3760 objfile_relocate (symfile_objfile, offs);
3763 /* Send interrupt_sequence to remote target. */
3765 send_interrupt_sequence (void)
3767 struct remote_state *rs = get_remote_state ();
3769 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3770 remote_serial_write ("\x03", 1);
3771 else if (interrupt_sequence_mode == interrupt_sequence_break)
3772 serial_send_break (rs->remote_desc);
3773 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3775 serial_send_break (rs->remote_desc);
3776 remote_serial_write ("g", 1);
3779 internal_error (__FILE__, __LINE__,
3780 _("Invalid value for interrupt_sequence_mode: %s."),
3781 interrupt_sequence_mode);
3785 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3786 and extract the PTID. Returns NULL_PTID if not found. */
3789 stop_reply_extract_thread (char *stop_reply)
3791 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3795 /* Txx r:val ; r:val (...) */
3798 /* Look for "register" named "thread". */
3803 p1 = strchr (p, ':');
3807 if (strncmp (p, "thread", p1 - p) == 0)
3808 return read_ptid (++p1, &p);
3810 p1 = strchr (p, ';');
3822 /* Determine the remote side's current thread. If we have a stop
3823 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3824 "thread" register we can extract the current thread from. If not,
3825 ask the remote which is the current thread with qC. The former
3826 method avoids a roundtrip. */
3829 get_current_thread (char *wait_status)
3831 ptid_t ptid = null_ptid;
3833 /* Note we don't use remote_parse_stop_reply as that makes use of
3834 the target architecture, which we haven't yet fully determined at
3836 if (wait_status != NULL)
3837 ptid = stop_reply_extract_thread (wait_status);
3838 if (ptid_equal (ptid, null_ptid))
3839 ptid = remote_current_thread (inferior_ptid);
3844 /* Query the remote target for which is the current thread/process,
3845 add it to our tables, and update INFERIOR_PTID. The caller is
3846 responsible for setting the state such that the remote end is ready
3847 to return the current thread.
3849 This function is called after handling the '?' or 'vRun' packets,
3850 whose response is a stop reply from which we can also try
3851 extracting the thread. If the target doesn't support the explicit
3852 qC query, we infer the current thread from that stop reply, passed
3853 in in WAIT_STATUS, which may be NULL. */
3856 add_current_inferior_and_thread (char *wait_status)
3858 struct remote_state *rs = get_remote_state ();
3861 inferior_ptid = null_ptid;
3863 /* Now, if we have thread information, update inferior_ptid. */
3864 ptid_t curr_ptid = get_current_thread (wait_status);
3866 if (curr_ptid != null_ptid)
3868 if (!remote_multi_process_p (rs))
3873 /* Without this, some commands which require an active target
3874 (such as kill) won't work. This variable serves (at least)
3875 double duty as both the pid of the target process (if it has
3876 such), and as a flag indicating that a target is active. */
3877 curr_ptid = magic_null_ptid;
3881 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
3883 /* Add the main thread and switch to it. Don't try reading
3884 registers yet, since we haven't fetched the target description
3886 thread_info *tp = add_thread_silent (curr_ptid);
3887 switch_to_thread_no_regs (tp);
3890 /* Print info about a thread that was found already stopped on
3894 print_one_stopped_thread (struct thread_info *thread)
3896 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3898 switch_to_thread (thread->ptid);
3899 stop_pc = get_frame_pc (get_current_frame ());
3900 set_current_sal_from_frame (get_current_frame ());
3902 thread->suspend.waitstatus_pending_p = 0;
3904 if (ws->kind == TARGET_WAITKIND_STOPPED)
3906 enum gdb_signal sig = ws->value.sig;
3908 if (signal_print_state (sig))
3909 observer_notify_signal_received (sig);
3911 observer_notify_normal_stop (NULL, 1);
3914 /* Process all initial stop replies the remote side sent in response
3915 to the ? packet. These indicate threads that were already stopped
3916 on initial connection. We mark these threads as stopped and print
3917 their current frame before giving the user the prompt. */
3920 process_initial_stop_replies (int from_tty)
3922 int pending_stop_replies = stop_reply_queue_length ();
3923 struct inferior *inf;
3924 struct thread_info *thread;
3925 struct thread_info *selected = NULL;
3926 struct thread_info *lowest_stopped = NULL;
3927 struct thread_info *first = NULL;
3929 /* Consume the initial pending events. */
3930 while (pending_stop_replies-- > 0)
3932 ptid_t waiton_ptid = minus_one_ptid;
3934 struct target_waitstatus ws;
3935 int ignore_event = 0;
3936 struct thread_info *thread;
3938 memset (&ws, 0, sizeof (ws));
3939 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3941 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3945 case TARGET_WAITKIND_IGNORE:
3946 case TARGET_WAITKIND_NO_RESUMED:
3947 case TARGET_WAITKIND_SIGNALLED:
3948 case TARGET_WAITKIND_EXITED:
3949 /* We shouldn't see these, but if we do, just ignore. */
3951 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3955 case TARGET_WAITKIND_EXECD:
3956 xfree (ws.value.execd_pathname);
3965 thread = find_thread_ptid (event_ptid);
3967 if (ws.kind == TARGET_WAITKIND_STOPPED)
3969 enum gdb_signal sig = ws.value.sig;
3971 /* Stubs traditionally report SIGTRAP as initial signal,
3972 instead of signal 0. Suppress it. */
3973 if (sig == GDB_SIGNAL_TRAP)
3975 thread->suspend.stop_signal = sig;
3979 thread->suspend.waitstatus = ws;
3981 if (ws.kind != TARGET_WAITKIND_STOPPED
3982 || ws.value.sig != GDB_SIGNAL_0)
3983 thread->suspend.waitstatus_pending_p = 1;
3985 set_executing (event_ptid, 0);
3986 set_running (event_ptid, 0);
3987 thread->priv->vcont_resumed = 0;
3990 /* "Notice" the new inferiors before anything related to
3991 registers/memory. */
3997 inf->needs_setup = 1;
4001 thread = any_live_thread_of_process (inf->pid);
4002 notice_new_inferior (thread->ptid,
4003 thread->state == THREAD_RUNNING,
4008 /* If all-stop on top of non-stop, pause all threads. Note this
4009 records the threads' stop pc, so must be done after "noticing"
4013 stop_all_threads ();
4015 /* If all threads of an inferior were already stopped, we
4016 haven't setup the inferior yet. */
4022 if (inf->needs_setup)
4024 thread = any_live_thread_of_process (inf->pid);
4025 switch_to_thread_no_regs (thread);
4031 /* Now go over all threads that are stopped, and print their current
4032 frame. If all-stop, then if there's a signalled thread, pick
4034 ALL_NON_EXITED_THREADS (thread)
4040 set_running (thread->ptid, 0);
4041 else if (thread->state != THREAD_STOPPED)
4044 if (selected == NULL
4045 && thread->suspend.waitstatus_pending_p)
4048 if (lowest_stopped == NULL
4049 || thread->inf->num < lowest_stopped->inf->num
4050 || thread->per_inf_num < lowest_stopped->per_inf_num)
4051 lowest_stopped = thread;
4054 print_one_stopped_thread (thread);
4057 /* In all-stop, we only print the status of one thread, and leave
4058 others with their status pending. */
4063 thread = lowest_stopped;
4067 print_one_stopped_thread (thread);
4070 /* For "info program". */
4071 thread = inferior_thread ();
4072 if (thread->state == THREAD_STOPPED)
4073 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4076 /* Start the remote connection and sync state. */
4079 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
4081 struct remote_state *rs = get_remote_state ();
4082 struct packet_config *noack_config;
4083 char *wait_status = NULL;
4085 /* Signal other parts that we're going through the initial setup,
4086 and so things may not be stable yet. E.g., we don't try to
4087 install tracepoints until we've relocated symbols. Also, a
4088 Ctrl-C before we're connected and synced up can't interrupt the
4089 target. Instead, it offers to drop the (potentially wedged)
4091 rs->starting_up = 1;
4095 if (interrupt_on_connect)
4096 send_interrupt_sequence ();
4098 /* Ack any packet which the remote side has already sent. */
4099 remote_serial_write ("+", 1);
4101 /* The first packet we send to the target is the optional "supported
4102 packets" request. If the target can answer this, it will tell us
4103 which later probes to skip. */
4104 remote_query_supported ();
4106 /* If the stub wants to get a QAllow, compose one and send it. */
4107 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4108 remote_set_permissions (target);
4110 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4111 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4112 as a reply to known packet. For packet "vFile:setfs:" it is an
4113 invalid reply and GDB would return error in
4114 remote_hostio_set_filesystem, making remote files access impossible.
4115 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4116 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4118 const char v_mustreplyempty[] = "vMustReplyEmpty";
4120 putpkt (v_mustreplyempty);
4121 getpkt (&rs->buf, &rs->buf_size, 0);
4122 if (strcmp (rs->buf, "OK") == 0)
4123 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4124 else if (strcmp (rs->buf, "") != 0)
4125 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4129 /* Next, we possibly activate noack mode.
4131 If the QStartNoAckMode packet configuration is set to AUTO,
4132 enable noack mode if the stub reported a wish for it with
4135 If set to TRUE, then enable noack mode even if the stub didn't
4136 report it in qSupported. If the stub doesn't reply OK, the
4137 session ends with an error.
4139 If FALSE, then don't activate noack mode, regardless of what the
4140 stub claimed should be the default with qSupported. */
4142 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4143 if (packet_config_support (noack_config) != PACKET_DISABLE)
4145 putpkt ("QStartNoAckMode");
4146 getpkt (&rs->buf, &rs->buf_size, 0);
4147 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4153 /* Tell the remote that we are using the extended protocol. */
4155 getpkt (&rs->buf, &rs->buf_size, 0);
4158 /* Let the target know which signals it is allowed to pass down to
4160 update_signals_program_target ();
4162 /* Next, if the target can specify a description, read it. We do
4163 this before anything involving memory or registers. */
4164 target_find_description ();
4166 /* Next, now that we know something about the target, update the
4167 address spaces in the program spaces. */
4168 update_address_spaces ();
4170 /* On OSs where the list of libraries is global to all
4171 processes, we fetch them early. */
4172 if (gdbarch_has_global_solist (target_gdbarch ()))
4173 solib_add (NULL, from_tty, auto_solib_add);
4175 if (target_is_non_stop_p ())
4177 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4178 error (_("Non-stop mode requested, but remote "
4179 "does not support non-stop"));
4181 putpkt ("QNonStop:1");
4182 getpkt (&rs->buf, &rs->buf_size, 0);
4184 if (strcmp (rs->buf, "OK") != 0)
4185 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4187 /* Find about threads and processes the stub is already
4188 controlling. We default to adding them in the running state.
4189 The '?' query below will then tell us about which threads are
4191 remote_update_thread_list (target);
4193 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4195 /* Don't assume that the stub can operate in all-stop mode.
4196 Request it explicitly. */
4197 putpkt ("QNonStop:0");
4198 getpkt (&rs->buf, &rs->buf_size, 0);
4200 if (strcmp (rs->buf, "OK") != 0)
4201 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4204 /* Upload TSVs regardless of whether the target is running or not. The
4205 remote stub, such as GDBserver, may have some predefined or builtin
4206 TSVs, even if the target is not running. */
4207 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4209 struct uploaded_tsv *uploaded_tsvs = NULL;
4211 remote_upload_trace_state_variables (target, &uploaded_tsvs);
4212 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4215 /* Check whether the target is running now. */
4217 getpkt (&rs->buf, &rs->buf_size, 0);
4219 if (!target_is_non_stop_p ())
4221 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4224 error (_("The target is not running (try extended-remote?)"));
4226 /* We're connected, but not running. Drop out before we
4227 call start_remote. */
4228 rs->starting_up = 0;
4233 /* Save the reply for later. */
4234 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4235 strcpy (wait_status, rs->buf);
4238 /* Fetch thread list. */
4239 target_update_thread_list ();
4241 /* Let the stub know that we want it to return the thread. */
4242 set_continue_thread (minus_one_ptid);
4244 if (thread_count () == 0)
4246 /* Target has no concept of threads at all. GDB treats
4247 non-threaded target as single-threaded; add a main
4249 add_current_inferior_and_thread (wait_status);
4253 /* We have thread information; select the thread the target
4254 says should be current. If we're reconnecting to a
4255 multi-threaded program, this will ideally be the thread
4256 that last reported an event before GDB disconnected. */
4257 inferior_ptid = get_current_thread (wait_status);
4258 if (ptid_equal (inferior_ptid, null_ptid))
4260 /* Odd... The target was able to list threads, but not
4261 tell us which thread was current (no "thread"
4262 register in T stop reply?). Just pick the first
4263 thread in the thread list then. */
4266 fprintf_unfiltered (gdb_stdlog,
4267 "warning: couldn't determine remote "
4268 "current thread; picking first in list.\n");
4270 inferior_ptid = thread_list->ptid;
4274 /* init_wait_for_inferior should be called before get_offsets in order
4275 to manage `inserted' flag in bp loc in a correct state.
4276 breakpoint_init_inferior, called from init_wait_for_inferior, set
4277 `inserted' flag to 0, while before breakpoint_re_set, called from
4278 start_remote, set `inserted' flag to 1. In the initialization of
4279 inferior, breakpoint_init_inferior should be called first, and then
4280 breakpoint_re_set can be called. If this order is broken, state of
4281 `inserted' flag is wrong, and cause some problems on breakpoint
4283 init_wait_for_inferior ();
4285 get_offsets (); /* Get text, data & bss offsets. */
4287 /* If we could not find a description using qXfer, and we know
4288 how to do it some other way, try again. This is not
4289 supported for non-stop; it could be, but it is tricky if
4290 there are no stopped threads when we connect. */
4291 if (remote_read_description_p (target)
4292 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4294 target_clear_description ();
4295 target_find_description ();
4298 /* Use the previously fetched status. */
4299 gdb_assert (wait_status != NULL);
4300 strcpy (rs->buf, wait_status);
4301 rs->cached_wait_status = 1;
4303 start_remote (from_tty); /* Initialize gdb process mechanisms. */
4307 /* Clear WFI global state. Do this before finding about new
4308 threads and inferiors, and setting the current inferior.
4309 Otherwise we would clear the proceed status of the current
4310 inferior when we want its stop_soon state to be preserved
4311 (see notice_new_inferior). */
4312 init_wait_for_inferior ();
4314 /* In non-stop, we will either get an "OK", meaning that there
4315 are no stopped threads at this time; or, a regular stop
4316 reply. In the latter case, there may be more than one thread
4317 stopped --- we pull them all out using the vStopped
4319 if (strcmp (rs->buf, "OK") != 0)
4321 struct notif_client *notif = ¬if_client_stop;
4323 /* remote_notif_get_pending_replies acks this one, and gets
4325 rs->notif_state->pending_event[notif_client_stop.id]
4326 = remote_notif_parse (notif, rs->buf);
4327 remote_notif_get_pending_events (notif);
4330 if (thread_count () == 0)
4333 error (_("The target is not running (try extended-remote?)"));
4335 /* We're connected, but not running. Drop out before we
4336 call start_remote. */
4337 rs->starting_up = 0;
4341 /* In non-stop mode, any cached wait status will be stored in
4342 the stop reply queue. */
4343 gdb_assert (wait_status == NULL);
4345 /* Report all signals during attach/startup. */
4346 remote_pass_signals (target, 0, NULL);
4348 /* If there are already stopped threads, mark them stopped and
4349 report their stops before giving the prompt to the user. */
4350 process_initial_stop_replies (from_tty);
4352 if (target_can_async_p ())
4356 /* If we connected to a live target, do some additional setup. */
4357 if (target_has_execution)
4359 if (symfile_objfile) /* No use without a symbol-file. */
4360 remote_check_symbols ();
4363 /* Possibly the target has been engaged in a trace run started
4364 previously; find out where things are at. */
4365 if (remote_get_trace_status (target, current_trace_status ()) != -1)
4367 struct uploaded_tp *uploaded_tps = NULL;
4369 if (current_trace_status ()->running)
4370 printf_filtered (_("Trace is already running on the target.\n"));
4372 remote_upload_tracepoints (target, &uploaded_tps);
4374 merge_uploaded_tracepoints (&uploaded_tps);
4377 /* Possibly the target has been engaged in a btrace record started
4378 previously; find out where things are at. */
4379 remote_btrace_maybe_reopen ();
4381 /* The thread and inferior lists are now synchronized with the
4382 target, our symbols have been relocated, and we're merged the
4383 target's tracepoints with ours. We're done with basic start
4385 rs->starting_up = 0;
4387 /* Maybe breakpoints are global and need to be inserted now. */
4388 if (breakpoints_should_be_inserted_now ())
4389 insert_breakpoints ();
4392 /* Open a connection to a remote debugger.
4393 NAME is the filename used for communication. */
4396 remote_open (const char *name, int from_tty)
4398 remote_open_1 (name, from_tty, &remote_ops, 0);
4401 /* Open a connection to a remote debugger using the extended
4402 remote gdb protocol. NAME is the filename used for communication. */
4405 extended_remote_open (const char *name, int from_tty)
4407 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4410 /* Reset all packets back to "unknown support". Called when opening a
4411 new connection to a remote target. */
4414 reset_all_packet_configs_support (void)
4418 for (i = 0; i < PACKET_MAX; i++)
4419 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4422 /* Initialize all packet configs. */
4425 init_all_packet_configs (void)
4429 for (i = 0; i < PACKET_MAX; i++)
4431 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4432 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4436 /* Symbol look-up. */
4439 remote_check_symbols (void)
4441 struct remote_state *rs = get_remote_state ();
4442 char *msg, *reply, *tmp;
4445 struct cleanup *old_chain;
4447 /* The remote side has no concept of inferiors that aren't running
4448 yet, it only knows about running processes. If we're connected
4449 but our current inferior is not running, we should not invite the
4450 remote target to request symbol lookups related to its
4451 (unrelated) current process. */
4452 if (!target_has_execution)
4455 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4458 /* Make sure the remote is pointing at the right process. Note
4459 there's no way to select "no process". */
4460 set_general_process ();
4462 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4463 because we need both at the same time. */
4464 msg = (char *) xmalloc (get_remote_packet_size ());
4465 old_chain = make_cleanup (xfree, msg);
4466 reply = (char *) xmalloc (get_remote_packet_size ());
4467 make_cleanup (free_current_contents, &reply);
4468 reply_size = get_remote_packet_size ();
4470 /* Invite target to request symbol lookups. */
4472 putpkt ("qSymbol::");
4473 getpkt (&reply, &reply_size, 0);
4474 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4476 while (startswith (reply, "qSymbol:"))
4478 struct bound_minimal_symbol sym;
4481 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4483 sym = lookup_minimal_symbol (msg, NULL, NULL);
4484 if (sym.minsym == NULL)
4485 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4488 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4489 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4491 /* If this is a function address, return the start of code
4492 instead of any data function descriptor. */
4493 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4497 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4498 phex_nz (sym_addr, addr_size), &reply[8]);
4502 getpkt (&reply, &reply_size, 0);
4505 do_cleanups (old_chain);
4508 static struct serial *
4509 remote_serial_open (const char *name)
4511 static int udp_warning = 0;
4513 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4514 of in ser-tcp.c, because it is the remote protocol assuming that the
4515 serial connection is reliable and not the serial connection promising
4517 if (!udp_warning && startswith (name, "udp:"))
4519 warning (_("The remote protocol may be unreliable over UDP.\n"
4520 "Some events may be lost, rendering further debugging "
4525 return serial_open (name);
4528 /* Inform the target of our permission settings. The permission flags
4529 work without this, but if the target knows the settings, it can do
4530 a couple things. First, it can add its own check, to catch cases
4531 that somehow manage to get by the permissions checks in target
4532 methods. Second, if the target is wired to disallow particular
4533 settings (for instance, a system in the field that is not set up to
4534 be able to stop at a breakpoint), it can object to any unavailable
4538 remote_set_permissions (struct target_ops *self)
4540 struct remote_state *rs = get_remote_state ();
4542 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4543 "WriteReg:%x;WriteMem:%x;"
4544 "InsertBreak:%x;InsertTrace:%x;"
4545 "InsertFastTrace:%x;Stop:%x",
4546 may_write_registers, may_write_memory,
4547 may_insert_breakpoints, may_insert_tracepoints,
4548 may_insert_fast_tracepoints, may_stop);
4550 getpkt (&rs->buf, &rs->buf_size, 0);
4552 /* If the target didn't like the packet, warn the user. Do not try
4553 to undo the user's settings, that would just be maddening. */
4554 if (strcmp (rs->buf, "OK") != 0)
4555 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4558 /* This type describes each known response to the qSupported
4560 struct protocol_feature
4562 /* The name of this protocol feature. */
4565 /* The default for this protocol feature. */
4566 enum packet_support default_support;
4568 /* The function to call when this feature is reported, or after
4569 qSupported processing if the feature is not supported.
4570 The first argument points to this structure. The second
4571 argument indicates whether the packet requested support be
4572 enabled, disabled, or probed (or the default, if this function
4573 is being called at the end of processing and this feature was
4574 not reported). The third argument may be NULL; if not NULL, it
4575 is a NUL-terminated string taken from the packet following
4576 this feature's name and an equals sign. */
4577 void (*func) (const struct protocol_feature *, enum packet_support,
4580 /* The corresponding packet for this feature. Only used if
4581 FUNC is remote_supported_packet. */
4586 remote_supported_packet (const struct protocol_feature *feature,
4587 enum packet_support support,
4588 const char *argument)
4592 warning (_("Remote qSupported response supplied an unexpected value for"
4593 " \"%s\"."), feature->name);
4597 remote_protocol_packets[feature->packet].support = support;
4601 remote_packet_size (const struct protocol_feature *feature,
4602 enum packet_support support, const char *value)
4604 struct remote_state *rs = get_remote_state ();
4609 if (support != PACKET_ENABLE)
4612 if (value == NULL || *value == '\0')
4614 warning (_("Remote target reported \"%s\" without a size."),
4620 packet_size = strtol (value, &value_end, 16);
4621 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4623 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4624 feature->name, value);
4628 /* Record the new maximum packet size. */
4629 rs->explicit_packet_size = packet_size;
4632 static const struct protocol_feature remote_protocol_features[] = {
4633 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4634 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4635 PACKET_qXfer_auxv },
4636 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4637 PACKET_qXfer_exec_file },
4638 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4639 PACKET_qXfer_features },
4640 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4641 PACKET_qXfer_libraries },
4642 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4643 PACKET_qXfer_libraries_svr4 },
4644 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4645 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4646 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4647 PACKET_qXfer_memory_map },
4648 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4649 PACKET_qXfer_spu_read },
4650 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4651 PACKET_qXfer_spu_write },
4652 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4653 PACKET_qXfer_osdata },
4654 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4655 PACKET_qXfer_threads },
4656 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4657 PACKET_qXfer_traceframe_info },
4658 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4659 PACKET_QPassSignals },
4660 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4661 PACKET_QCatchSyscalls },
4662 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4663 PACKET_QProgramSignals },
4664 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4665 PACKET_QStartupWithShell },
4666 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4667 PACKET_QEnvironmentHexEncoded },
4668 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4669 PACKET_QEnvironmentReset },
4670 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4671 PACKET_QEnvironmentUnset },
4672 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4673 PACKET_QStartNoAckMode },
4674 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4675 PACKET_multiprocess_feature },
4676 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4677 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4678 PACKET_qXfer_siginfo_read },
4679 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4680 PACKET_qXfer_siginfo_write },
4681 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4682 PACKET_ConditionalTracepoints },
4683 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4684 PACKET_ConditionalBreakpoints },
4685 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4686 PACKET_BreakpointCommands },
4687 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4688 PACKET_FastTracepoints },
4689 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4690 PACKET_StaticTracepoints },
4691 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4692 PACKET_InstallInTrace},
4693 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4694 PACKET_DisconnectedTracing_feature },
4695 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4697 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4699 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4700 PACKET_TracepointSource },
4701 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4703 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4704 PACKET_EnableDisableTracepoints_feature },
4705 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4706 PACKET_qXfer_fdpic },
4707 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4709 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4710 PACKET_QDisableRandomization },
4711 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4712 { "QTBuffer:size", PACKET_DISABLE,
4713 remote_supported_packet, PACKET_QTBuffer_size},
4714 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4715 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4716 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4717 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4718 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4719 PACKET_qXfer_btrace },
4720 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4721 PACKET_qXfer_btrace_conf },
4722 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4723 PACKET_Qbtrace_conf_bts_size },
4724 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4725 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4726 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4727 PACKET_fork_event_feature },
4728 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4729 PACKET_vfork_event_feature },
4730 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4731 PACKET_exec_event_feature },
4732 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4733 PACKET_Qbtrace_conf_pt_size },
4734 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4735 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4736 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4739 static char *remote_support_xml;
4741 /* Register string appended to "xmlRegisters=" in qSupported query. */
4744 register_remote_support_xml (const char *xml)
4746 #if defined(HAVE_LIBEXPAT)
4747 if (remote_support_xml == NULL)
4748 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4751 char *copy = xstrdup (remote_support_xml + 13);
4752 char *p = strtok (copy, ",");
4756 if (strcmp (p, xml) == 0)
4763 while ((p = strtok (NULL, ",")) != NULL);
4766 remote_support_xml = reconcat (remote_support_xml,
4767 remote_support_xml, ",", xml,
4774 remote_query_supported_append (char *msg, const char *append)
4777 return reconcat (msg, msg, ";", append, (char *) NULL);
4779 return xstrdup (append);
4783 remote_query_supported (void)
4785 struct remote_state *rs = get_remote_state ();
4788 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4790 /* The packet support flags are handled differently for this packet
4791 than for most others. We treat an error, a disabled packet, and
4792 an empty response identically: any features which must be reported
4793 to be used will be automatically disabled. An empty buffer
4794 accomplishes this, since that is also the representation for a list
4795 containing no features. */
4798 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4801 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4803 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4804 q = remote_query_supported_append (q, "multiprocess+");
4806 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4807 q = remote_query_supported_append (q, "swbreak+");
4808 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4809 q = remote_query_supported_append (q, "hwbreak+");
4811 q = remote_query_supported_append (q, "qRelocInsn+");
4813 if (packet_set_cmd_state (PACKET_fork_event_feature)
4814 != AUTO_BOOLEAN_FALSE)
4815 q = remote_query_supported_append (q, "fork-events+");
4816 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4817 != AUTO_BOOLEAN_FALSE)
4818 q = remote_query_supported_append (q, "vfork-events+");
4819 if (packet_set_cmd_state (PACKET_exec_event_feature)
4820 != AUTO_BOOLEAN_FALSE)
4821 q = remote_query_supported_append (q, "exec-events+");
4823 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4824 q = remote_query_supported_append (q, "vContSupported+");
4826 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4827 q = remote_query_supported_append (q, "QThreadEvents+");
4829 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4830 q = remote_query_supported_append (q, "no-resumed+");
4832 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4833 the qSupported:xmlRegisters=i386 handling. */
4834 if (remote_support_xml != NULL)
4835 q = remote_query_supported_append (q, remote_support_xml);
4837 q = reconcat (q, "qSupported:", q, (char *) NULL);
4840 do_cleanups (old_chain);
4842 getpkt (&rs->buf, &rs->buf_size, 0);
4844 /* If an error occured, warn, but do not return - just reset the
4845 buffer to empty and go on to disable features. */
4846 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4849 warning (_("Remote failure reply: %s"), rs->buf);
4854 memset (seen, 0, sizeof (seen));
4859 enum packet_support is_supported;
4860 char *p, *end, *name_end, *value;
4862 /* First separate out this item from the rest of the packet. If
4863 there's another item after this, we overwrite the separator
4864 (terminated strings are much easier to work with). */
4866 end = strchr (p, ';');
4869 end = p + strlen (p);
4879 warning (_("empty item in \"qSupported\" response"));
4884 name_end = strchr (p, '=');
4887 /* This is a name=value entry. */
4888 is_supported = PACKET_ENABLE;
4889 value = name_end + 1;
4898 is_supported = PACKET_ENABLE;
4902 is_supported = PACKET_DISABLE;
4906 is_supported = PACKET_SUPPORT_UNKNOWN;
4910 warning (_("unrecognized item \"%s\" "
4911 "in \"qSupported\" response"), p);
4917 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4918 if (strcmp (remote_protocol_features[i].name, p) == 0)
4920 const struct protocol_feature *feature;
4923 feature = &remote_protocol_features[i];
4924 feature->func (feature, is_supported, value);
4929 /* If we increased the packet size, make sure to increase the global
4930 buffer size also. We delay this until after parsing the entire
4931 qSupported packet, because this is the same buffer we were
4933 if (rs->buf_size < rs->explicit_packet_size)
4935 rs->buf_size = rs->explicit_packet_size;
4936 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4939 /* Handle the defaults for unmentioned features. */
4940 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4943 const struct protocol_feature *feature;
4945 feature = &remote_protocol_features[i];
4946 feature->func (feature, feature->default_support, NULL);
4950 /* Serial QUIT handler for the remote serial descriptor.
4952 Defers handling a Ctrl-C until we're done with the current
4953 command/response packet sequence, unless:
4955 - We're setting up the connection. Don't send a remote interrupt
4956 request, as we're not fully synced yet. Quit immediately
4959 - The target has been resumed in the foreground
4960 (target_terminal::is_ours is false) with a synchronous resume
4961 packet, and we're blocked waiting for the stop reply, thus a
4962 Ctrl-C should be immediately sent to the target.
4964 - We get a second Ctrl-C while still within the same serial read or
4965 write. In that case the serial is seemingly wedged --- offer to
4968 - We see a second Ctrl-C without target response, after having
4969 previously interrupted the target. In that case the target/stub
4970 is probably wedged --- offer to quit/disconnect.
4974 remote_serial_quit_handler (void)
4976 struct remote_state *rs = get_remote_state ();
4978 if (check_quit_flag ())
4980 /* If we're starting up, we're not fully synced yet. Quit
4982 if (rs->starting_up)
4984 else if (rs->got_ctrlc_during_io)
4986 if (query (_("The target is not responding to GDB commands.\n"
4987 "Stop debugging it? ")))
4988 remote_unpush_and_throw ();
4990 /* If ^C has already been sent once, offer to disconnect. */
4991 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
4993 /* All-stop protocol, and blocked waiting for stop reply. Send
4994 an interrupt request. */
4995 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
4996 target_interrupt (inferior_ptid);
4998 rs->got_ctrlc_during_io = 1;
5002 /* Remove any of the remote.c targets from target stack. Upper targets depend
5003 on it so remove them first. */
5006 remote_unpush_target (void)
5008 pop_all_targets_at_and_above (process_stratum);
5012 remote_unpush_and_throw (void)
5014 remote_unpush_target ();
5015 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5019 remote_open_1 (const char *name, int from_tty,
5020 struct target_ops *target, int extended_p)
5022 struct remote_state *rs = get_remote_state ();
5025 error (_("To open a remote debug connection, you need to specify what\n"
5026 "serial device is attached to the remote system\n"
5027 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5029 /* See FIXME above. */
5030 if (!target_async_permitted)
5031 wait_forever_enabled_p = 1;
5033 /* If we're connected to a running target, target_preopen will kill it.
5034 Ask this question first, before target_preopen has a chance to kill
5036 if (rs->remote_desc != NULL && !have_inferiors ())
5039 && !query (_("Already connected to a remote target. Disconnect? ")))
5040 error (_("Still connected."));
5043 /* Here the possibly existing remote target gets unpushed. */
5044 target_preopen (from_tty);
5046 /* Make sure we send the passed signals list the next time we resume. */
5047 xfree (rs->last_pass_packet);
5048 rs->last_pass_packet = NULL;
5050 /* Make sure we send the program signals list the next time we
5052 xfree (rs->last_program_signals_packet);
5053 rs->last_program_signals_packet = NULL;
5055 remote_fileio_reset ();
5056 reopen_exec_file ();
5059 rs->remote_desc = remote_serial_open (name);
5060 if (!rs->remote_desc)
5061 perror_with_name (name);
5063 if (baud_rate != -1)
5065 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5067 /* The requested speed could not be set. Error out to
5068 top level after closing remote_desc. Take care to
5069 set remote_desc to NULL to avoid closing remote_desc
5071 serial_close (rs->remote_desc);
5072 rs->remote_desc = NULL;
5073 perror_with_name (name);
5077 serial_setparity (rs->remote_desc, serial_parity);
5078 serial_raw (rs->remote_desc);
5080 /* If there is something sitting in the buffer we might take it as a
5081 response to a command, which would be bad. */
5082 serial_flush_input (rs->remote_desc);
5086 puts_filtered ("Remote debugging using ");
5087 puts_filtered (name);
5088 puts_filtered ("\n");
5090 push_target (target); /* Switch to using remote target now. */
5092 /* Register extra event sources in the event loop. */
5093 remote_async_inferior_event_token
5094 = create_async_event_handler (remote_async_inferior_event_handler,
5096 rs->notif_state = remote_notif_state_allocate ();
5098 /* Reset the target state; these things will be queried either by
5099 remote_query_supported or as they are needed. */
5100 reset_all_packet_configs_support ();
5101 rs->cached_wait_status = 0;
5102 rs->explicit_packet_size = 0;
5104 rs->extended = extended_p;
5105 rs->waiting_for_stop_reply = 0;
5106 rs->ctrlc_pending_p = 0;
5107 rs->got_ctrlc_during_io = 0;
5109 rs->general_thread = not_sent_ptid;
5110 rs->continue_thread = not_sent_ptid;
5111 rs->remote_traceframe_number = -1;
5113 rs->last_resume_exec_dir = EXEC_FORWARD;
5115 /* Probe for ability to use "ThreadInfo" query, as required. */
5116 rs->use_threadinfo_query = 1;
5117 rs->use_threadextra_query = 1;
5119 readahead_cache_invalidate ();
5121 /* Start out by owning the terminal. */
5122 remote_async_terminal_ours_p = 1;
5124 if (target_async_permitted)
5126 /* FIXME: cagney/1999-09-23: During the initial connection it is
5127 assumed that the target is already ready and able to respond to
5128 requests. Unfortunately remote_start_remote() eventually calls
5129 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5130 around this. Eventually a mechanism that allows
5131 wait_for_inferior() to expect/get timeouts will be
5133 wait_forever_enabled_p = 0;
5136 /* First delete any symbols previously loaded from shared libraries. */
5137 no_shared_libraries (NULL, 0);
5140 init_thread_list ();
5142 /* Start the remote connection. If error() or QUIT, discard this
5143 target (we'd otherwise be in an inconsistent state) and then
5144 propogate the error on up the exception chain. This ensures that
5145 the caller doesn't stumble along blindly assuming that the
5146 function succeeded. The CLI doesn't have this problem but other
5147 UI's, such as MI do.
5149 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5150 this function should return an error indication letting the
5151 caller restore the previous state. Unfortunately the command
5152 ``target remote'' is directly wired to this function making that
5153 impossible. On a positive note, the CLI side of this problem has
5154 been fixed - the function set_cmd_context() makes it possible for
5155 all the ``target ....'' commands to share a common callback
5156 function. See cli-dump.c. */
5161 remote_start_remote (from_tty, target, extended_p);
5163 CATCH (ex, RETURN_MASK_ALL)
5165 /* Pop the partially set up target - unless something else did
5166 already before throwing the exception. */
5167 if (rs->remote_desc != NULL)
5168 remote_unpush_target ();
5169 if (target_async_permitted)
5170 wait_forever_enabled_p = 1;
5171 throw_exception (ex);
5176 remote_btrace_reset ();
5178 if (target_async_permitted)
5179 wait_forever_enabled_p = 1;
5182 /* Detach the specified process. */
5185 remote_detach_pid (int pid)
5187 struct remote_state *rs = get_remote_state ();
5189 if (remote_multi_process_p (rs))
5190 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5192 strcpy (rs->buf, "D");
5195 getpkt (&rs->buf, &rs->buf_size, 0);
5197 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5199 else if (rs->buf[0] == '\0')
5200 error (_("Remote doesn't know how to detach"));
5202 error (_("Can't detach process."));
5205 /* This detaches a program to which we previously attached, using
5206 inferior_ptid to identify the process. After this is done, GDB
5207 can be used to debug some other program. We better not have left
5208 any breakpoints in the target program or it'll die when it hits
5212 remote_detach_1 (const char *args, int from_tty)
5214 int pid = ptid_get_pid (inferior_ptid);
5215 struct remote_state *rs = get_remote_state ();
5216 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5220 error (_("Argument given to \"detach\" when remotely debugging."));
5222 if (!target_has_execution)
5223 error (_("No process to detach from."));
5225 target_announce_detach (from_tty);
5227 /* Tell the remote target to detach. */
5228 remote_detach_pid (pid);
5230 /* Exit only if this is the only active inferior. */
5231 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5232 puts_filtered (_("Ending remote debugging.\n"));
5234 /* Check to see if we are detaching a fork parent. Note that if we
5235 are detaching a fork child, tp == NULL. */
5236 is_fork_parent = (tp != NULL
5237 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5239 /* If doing detach-on-fork, we don't mourn, because that will delete
5240 breakpoints that should be available for the followed inferior. */
5241 if (!is_fork_parent)
5242 target_mourn_inferior (inferior_ptid);
5245 inferior_ptid = null_ptid;
5246 detach_inferior (pid);
5251 remote_detach (struct target_ops *ops, const char *args, int from_tty)
5253 remote_detach_1 (args, from_tty);
5257 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
5259 remote_detach_1 (args, from_tty);
5262 /* Target follow-fork function for remote targets. On entry, and
5263 at return, the current inferior is the fork parent.
5265 Note that although this is currently only used for extended-remote,
5266 it is named remote_follow_fork in anticipation of using it for the
5267 remote target as well. */
5270 remote_follow_fork (struct target_ops *ops, int follow_child,
5273 struct remote_state *rs = get_remote_state ();
5274 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5276 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5277 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5279 /* When following the parent and detaching the child, we detach
5280 the child here. For the case of following the child and
5281 detaching the parent, the detach is done in the target-
5282 independent follow fork code in infrun.c. We can't use
5283 target_detach when detaching an unfollowed child because
5284 the client side doesn't know anything about the child. */
5285 if (detach_fork && !follow_child)
5287 /* Detach the fork child. */
5291 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5292 child_pid = ptid_get_pid (child_ptid);
5294 remote_detach_pid (child_pid);
5295 detach_inferior (child_pid);
5301 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5302 in the program space of the new inferior. On entry and at return the
5303 current inferior is the exec'ing inferior. INF is the new exec'd
5304 inferior, which may be the same as the exec'ing inferior unless
5305 follow-exec-mode is "new". */
5308 remote_follow_exec (struct target_ops *ops,
5309 struct inferior *inf, char *execd_pathname)
5311 /* We know that this is a target file name, so if it has the "target:"
5312 prefix we strip it off before saving it in the program space. */
5313 if (is_target_filename (execd_pathname))
5314 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5316 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5319 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5322 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5325 error (_("Argument given to \"disconnect\" when remotely debugging."));
5327 /* Make sure we unpush even the extended remote targets. Calling
5328 target_mourn_inferior won't unpush, and remote_mourn won't
5329 unpush if there is more than one inferior left. */
5330 unpush_target (target);
5331 generic_mourn_inferior ();
5334 puts_filtered ("Ending remote debugging.\n");
5337 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5338 be chatty about it. */
5341 extended_remote_attach (struct target_ops *target, const char *args,
5344 struct remote_state *rs = get_remote_state ();
5346 char *wait_status = NULL;
5348 pid = parse_pid_to_attach (args);
5350 /* Remote PID can be freely equal to getpid, do not check it here the same
5351 way as in other targets. */
5353 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5354 error (_("This target does not support attaching to a process"));
5358 char *exec_file = get_exec_file (0);
5361 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5362 target_pid_to_str (pid_to_ptid (pid)));
5364 printf_unfiltered (_("Attaching to %s\n"),
5365 target_pid_to_str (pid_to_ptid (pid)));
5367 gdb_flush (gdb_stdout);
5370 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5372 getpkt (&rs->buf, &rs->buf_size, 0);
5374 switch (packet_ok (rs->buf,
5375 &remote_protocol_packets[PACKET_vAttach]))
5378 if (!target_is_non_stop_p ())
5380 /* Save the reply for later. */
5381 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5382 strcpy (wait_status, rs->buf);
5384 else if (strcmp (rs->buf, "OK") != 0)
5385 error (_("Attaching to %s failed with: %s"),
5386 target_pid_to_str (pid_to_ptid (pid)),
5389 case PACKET_UNKNOWN:
5390 error (_("This target does not support attaching to a process"));
5392 error (_("Attaching to %s failed"),
5393 target_pid_to_str (pid_to_ptid (pid)));
5396 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5398 inferior_ptid = pid_to_ptid (pid);
5400 if (target_is_non_stop_p ())
5402 struct thread_info *thread;
5404 /* Get list of threads. */
5405 remote_update_thread_list (target);
5407 thread = first_thread_of_process (pid);
5409 inferior_ptid = thread->ptid;
5411 inferior_ptid = pid_to_ptid (pid);
5413 /* Invalidate our notion of the remote current thread. */
5414 record_currthread (rs, minus_one_ptid);
5418 /* Now, if we have thread information, update inferior_ptid. */
5419 inferior_ptid = remote_current_thread (inferior_ptid);
5421 /* Add the main thread to the thread list. */
5422 add_thread_silent (inferior_ptid);
5425 /* Next, if the target can specify a description, read it. We do
5426 this before anything involving memory or registers. */
5427 target_find_description ();
5429 if (!target_is_non_stop_p ())
5431 /* Use the previously fetched status. */
5432 gdb_assert (wait_status != NULL);
5434 if (target_can_async_p ())
5436 struct notif_event *reply
5437 = remote_notif_parse (¬if_client_stop, wait_status);
5439 push_stop_reply ((struct stop_reply *) reply);
5445 gdb_assert (wait_status != NULL);
5446 strcpy (rs->buf, wait_status);
5447 rs->cached_wait_status = 1;
5451 gdb_assert (wait_status == NULL);
5454 /* Implementation of the to_post_attach method. */
5457 extended_remote_post_attach (struct target_ops *ops, int pid)
5459 /* Get text, data & bss offsets. */
5462 /* In certain cases GDB might not have had the chance to start
5463 symbol lookup up until now. This could happen if the debugged
5464 binary is not using shared libraries, the vsyscall page is not
5465 present (on Linux) and the binary itself hadn't changed since the
5466 debugging process was started. */
5467 if (symfile_objfile != NULL)
5468 remote_check_symbols();
5472 /* Check for the availability of vCont. This function should also check
5476 remote_vcont_probe (struct remote_state *rs)
5480 strcpy (rs->buf, "vCont?");
5482 getpkt (&rs->buf, &rs->buf_size, 0);
5485 /* Make sure that the features we assume are supported. */
5486 if (startswith (buf, "vCont"))
5489 int support_c, support_C;
5491 rs->supports_vCont.s = 0;
5492 rs->supports_vCont.S = 0;
5495 rs->supports_vCont.t = 0;
5496 rs->supports_vCont.r = 0;
5497 while (p && *p == ';')
5500 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5501 rs->supports_vCont.s = 1;
5502 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5503 rs->supports_vCont.S = 1;
5504 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5506 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5508 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5509 rs->supports_vCont.t = 1;
5510 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5511 rs->supports_vCont.r = 1;
5513 p = strchr (p, ';');
5516 /* If c, and C are not all supported, we can't use vCont. Clearing
5517 BUF will make packet_ok disable the packet. */
5518 if (!support_c || !support_C)
5522 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5525 /* Helper function for building "vCont" resumptions. Write a
5526 resumption to P. ENDP points to one-passed-the-end of the buffer
5527 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5528 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5529 resumed thread should be single-stepped and/or signalled. If PTID
5530 equals minus_one_ptid, then all threads are resumed; if PTID
5531 represents a process, then all threads of the process are resumed;
5532 the thread to be stepped and/or signalled is given in the global
5536 append_resumption (char *p, char *endp,
5537 ptid_t ptid, int step, enum gdb_signal siggnal)
5539 struct remote_state *rs = get_remote_state ();
5541 if (step && siggnal != GDB_SIGNAL_0)
5542 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5544 /* GDB is willing to range step. */
5545 && use_range_stepping
5546 /* Target supports range stepping. */
5547 && rs->supports_vCont.r
5548 /* We don't currently support range stepping multiple
5549 threads with a wildcard (though the protocol allows it,
5550 so stubs shouldn't make an active effort to forbid
5552 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5554 struct thread_info *tp;
5556 if (ptid_equal (ptid, minus_one_ptid))
5558 /* If we don't know about the target thread's tid, then
5559 we're resuming magic_null_ptid (see caller). */
5560 tp = find_thread_ptid (magic_null_ptid);
5563 tp = find_thread_ptid (ptid);
5564 gdb_assert (tp != NULL);
5566 if (tp->control.may_range_step)
5568 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5570 p += xsnprintf (p, endp - p, ";r%s,%s",
5571 phex_nz (tp->control.step_range_start,
5573 phex_nz (tp->control.step_range_end,
5577 p += xsnprintf (p, endp - p, ";s");
5580 p += xsnprintf (p, endp - p, ";s");
5581 else if (siggnal != GDB_SIGNAL_0)
5582 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5584 p += xsnprintf (p, endp - p, ";c");
5586 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5590 /* All (-1) threads of process. */
5591 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5593 p += xsnprintf (p, endp - p, ":");
5594 p = write_ptid (p, endp, nptid);
5596 else if (!ptid_equal (ptid, minus_one_ptid))
5598 p += xsnprintf (p, endp - p, ":");
5599 p = write_ptid (p, endp, ptid);
5605 /* Clear the thread's private info on resume. */
5608 resume_clear_thread_private_info (struct thread_info *thread)
5610 if (thread->priv != NULL)
5612 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5613 thread->priv->watch_data_address = 0;
5617 /* Append a vCont continue-with-signal action for threads that have a
5618 non-zero stop signal. */
5621 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5623 struct thread_info *thread;
5625 ALL_NON_EXITED_THREADS (thread)
5626 if (ptid_match (thread->ptid, ptid)
5627 && !ptid_equal (inferior_ptid, thread->ptid)
5628 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5630 p = append_resumption (p, endp, thread->ptid,
5631 0, thread->suspend.stop_signal);
5632 thread->suspend.stop_signal = GDB_SIGNAL_0;
5633 resume_clear_thread_private_info (thread);
5639 /* Set the target running, using the packets that use Hc
5643 remote_resume_with_hc (struct target_ops *ops,
5644 ptid_t ptid, int step, enum gdb_signal siggnal)
5646 struct remote_state *rs = get_remote_state ();
5647 struct thread_info *thread;
5650 rs->last_sent_signal = siggnal;
5651 rs->last_sent_step = step;
5653 /* The c/s/C/S resume packets use Hc, so set the continue
5655 if (ptid_equal (ptid, minus_one_ptid))
5656 set_continue_thread (any_thread_ptid);
5658 set_continue_thread (ptid);
5660 ALL_NON_EXITED_THREADS (thread)
5661 resume_clear_thread_private_info (thread);
5664 if (execution_direction == EXEC_REVERSE)
5666 /* We don't pass signals to the target in reverse exec mode. */
5667 if (info_verbose && siggnal != GDB_SIGNAL_0)
5668 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5671 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5672 error (_("Remote reverse-step not supported."));
5673 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5674 error (_("Remote reverse-continue not supported."));
5676 strcpy (buf, step ? "bs" : "bc");
5678 else if (siggnal != GDB_SIGNAL_0)
5680 buf[0] = step ? 'S' : 'C';
5681 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5682 buf[2] = tohex (((int) siggnal) & 0xf);
5686 strcpy (buf, step ? "s" : "c");
5691 /* Resume the remote inferior by using a "vCont" packet. The thread
5692 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5693 resumed thread should be single-stepped and/or signalled. If PTID
5694 equals minus_one_ptid, then all threads are resumed; the thread to
5695 be stepped and/or signalled is given in the global INFERIOR_PTID.
5696 This function returns non-zero iff it resumes the inferior.
5698 This function issues a strict subset of all possible vCont commands
5702 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5704 struct remote_state *rs = get_remote_state ();
5708 /* No reverse execution actions defined for vCont. */
5709 if (execution_direction == EXEC_REVERSE)
5712 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5713 remote_vcont_probe (rs);
5715 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5719 endp = rs->buf + get_remote_packet_size ();
5721 /* If we could generate a wider range of packets, we'd have to worry
5722 about overflowing BUF. Should there be a generic
5723 "multi-part-packet" packet? */
5725 p += xsnprintf (p, endp - p, "vCont");
5727 if (ptid_equal (ptid, magic_null_ptid))
5729 /* MAGIC_NULL_PTID means that we don't have any active threads,
5730 so we don't have any TID numbers the inferior will
5731 understand. Make sure to only send forms that do not specify
5733 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5735 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5737 /* Resume all threads (of all processes, or of a single
5738 process), with preference for INFERIOR_PTID. This assumes
5739 inferior_ptid belongs to the set of all threads we are about
5741 if (step || siggnal != GDB_SIGNAL_0)
5743 /* Step inferior_ptid, with or without signal. */
5744 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5747 /* Also pass down any pending signaled resumption for other
5748 threads not the current. */
5749 p = append_pending_thread_resumptions (p, endp, ptid);
5751 /* And continue others without a signal. */
5752 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5756 /* Scheduler locking; resume only PTID. */
5757 append_resumption (p, endp, ptid, step, siggnal);
5760 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5763 if (target_is_non_stop_p ())
5765 /* In non-stop, the stub replies to vCont with "OK". The stop
5766 reply will be reported asynchronously by means of a `%Stop'
5768 getpkt (&rs->buf, &rs->buf_size, 0);
5769 if (strcmp (rs->buf, "OK") != 0)
5770 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5776 /* Tell the remote machine to resume. */
5779 remote_resume (struct target_ops *ops,
5780 ptid_t ptid, int step, enum gdb_signal siggnal)
5782 struct remote_state *rs = get_remote_state ();
5784 /* When connected in non-stop mode, the core resumes threads
5785 individually. Resuming remote threads directly in target_resume
5786 would thus result in sending one packet per thread. Instead, to
5787 minimize roundtrip latency, here we just store the resume
5788 request; the actual remote resumption will be done in
5789 target_commit_resume / remote_commit_resume, where we'll be able
5790 to do vCont action coalescing. */
5791 if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5793 struct private_thread_info *remote_thr;
5795 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5796 remote_thr = get_private_info_ptid (inferior_ptid);
5798 remote_thr = get_private_info_ptid (ptid);
5799 remote_thr->last_resume_step = step;
5800 remote_thr->last_resume_sig = siggnal;
5804 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5805 (explained in remote-notif.c:handle_notification) so
5806 remote_notif_process is not called. We need find a place where
5807 it is safe to start a 'vNotif' sequence. It is good to do it
5808 before resuming inferior, because inferior was stopped and no RSP
5809 traffic at that moment. */
5810 if (!target_is_non_stop_p ())
5811 remote_notif_process (rs->notif_state, ¬if_client_stop);
5813 rs->last_resume_exec_dir = execution_direction;
5815 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
5816 if (!remote_resume_with_vcont (ptid, step, siggnal))
5817 remote_resume_with_hc (ops, ptid, step, siggnal);
5819 /* We are about to start executing the inferior, let's register it
5820 with the event loop. NOTE: this is the one place where all the
5821 execution commands end up. We could alternatively do this in each
5822 of the execution commands in infcmd.c. */
5823 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5824 into infcmd.c in order to allow inferior function calls to work
5825 NOT asynchronously. */
5826 if (target_can_async_p ())
5829 /* We've just told the target to resume. The remote server will
5830 wait for the inferior to stop, and then send a stop reply. In
5831 the mean time, we can't start another command/query ourselves
5832 because the stub wouldn't be ready to process it. This applies
5833 only to the base all-stop protocol, however. In non-stop (which
5834 only supports vCont), the stub replies with an "OK", and is
5835 immediate able to process further serial input. */
5836 if (!target_is_non_stop_p ())
5837 rs->waiting_for_stop_reply = 1;
5840 static void check_pending_events_prevent_wildcard_vcont
5841 (int *may_global_wildcard_vcont);
5842 static int is_pending_fork_parent_thread (struct thread_info *thread);
5844 /* Private per-inferior info for target remote processes. */
5846 struct private_inferior
5848 /* Whether we can send a wildcard vCont for this process. */
5849 int may_wildcard_vcont;
5852 /* Structure used to track the construction of a vCont packet in the
5853 outgoing packet buffer. This is used to send multiple vCont
5854 packets if we have more actions than would fit a single packet. */
5856 struct vcont_builder
5858 /* Pointer to the first action. P points here if no action has been
5862 /* Where the next action will be appended. */
5865 /* The end of the buffer. Must never write past this. */
5869 /* Prepare the outgoing buffer for a new vCont packet. */
5872 vcont_builder_restart (struct vcont_builder *builder)
5874 struct remote_state *rs = get_remote_state ();
5876 builder->p = rs->buf;
5877 builder->endp = rs->buf + get_remote_packet_size ();
5878 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5879 builder->first_action = builder->p;
5882 /* If the vCont packet being built has any action, send it to the
5886 vcont_builder_flush (struct vcont_builder *builder)
5888 struct remote_state *rs;
5890 if (builder->p == builder->first_action)
5893 rs = get_remote_state ();
5895 getpkt (&rs->buf, &rs->buf_size, 0);
5896 if (strcmp (rs->buf, "OK") != 0)
5897 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5900 /* The largest action is range-stepping, with its two addresses. This
5901 is more than sufficient. If a new, bigger action is created, it'll
5902 quickly trigger a failed assertion in append_resumption (and we'll
5904 #define MAX_ACTION_SIZE 200
5906 /* Append a new vCont action in the outgoing packet being built. If
5907 the action doesn't fit the packet along with previous actions, push
5908 what we've got so far to the remote end and start over a new vCont
5909 packet (with the new action). */
5912 vcont_builder_push_action (struct vcont_builder *builder,
5913 ptid_t ptid, int step, enum gdb_signal siggnal)
5915 char buf[MAX_ACTION_SIZE + 1];
5919 endp = append_resumption (buf, buf + sizeof (buf),
5920 ptid, step, siggnal);
5922 /* Check whether this new action would fit in the vCont packet along
5923 with previous actions. If not, send what we've got so far and
5924 start a new vCont packet. */
5926 if (rsize > builder->endp - builder->p)
5928 vcont_builder_flush (builder);
5929 vcont_builder_restart (builder);
5931 /* Should now fit. */
5932 gdb_assert (rsize <= builder->endp - builder->p);
5935 memcpy (builder->p, buf, rsize);
5936 builder->p += rsize;
5940 /* to_commit_resume implementation. */
5943 remote_commit_resume (struct target_ops *ops)
5945 struct remote_state *rs = get_remote_state ();
5946 struct inferior *inf;
5947 struct thread_info *tp;
5948 int any_process_wildcard;
5949 int may_global_wildcard_vcont;
5950 struct vcont_builder vcont_builder;
5952 /* If connected in all-stop mode, we'd send the remote resume
5953 request directly from remote_resume. Likewise if
5954 reverse-debugging, as there are no defined vCont actions for
5955 reverse execution. */
5956 if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5959 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5960 instead of resuming all threads of each process individually.
5961 However, if any thread of a process must remain halted, we can't
5962 send wildcard resumes and must send one action per thread.
5964 Care must be taken to not resume threads/processes the server
5965 side already told us are stopped, but the core doesn't know about
5966 yet, because the events are still in the vStopped notification
5969 #1 => vCont s:p1.1;c
5971 #3 <= %Stopped T05 p1.1
5976 #8 (infrun handles the stop for p1.1 and continues stepping)
5977 #9 => vCont s:p1.1;c
5979 The last vCont above would resume thread p1.2 by mistake, because
5980 the server has no idea that the event for p1.2 had not been
5983 The server side must similarly ignore resume actions for the
5984 thread that has a pending %Stopped notification (and any other
5985 threads with events pending), until GDB acks the notification
5986 with vStopped. Otherwise, e.g., the following case is
5989 #1 => g (or any other packet)
5991 #3 <= %Stopped T05 p1.2
5992 #4 => vCont s:p1.1;c
5995 Above, the server must not resume thread p1.2. GDB can't know
5996 that p1.2 stopped until it acks the %Stopped notification, and
5997 since from GDB's perspective all threads should be running, it
6000 Finally, special care must also be given to handling fork/vfork
6001 events. A (v)fork event actually tells us that two processes
6002 stopped -- the parent and the child. Until we follow the fork,
6003 we must not resume the child. Therefore, if we have a pending
6004 fork follow, we must not send a global wildcard resume action
6005 (vCont;c). We can still send process-wide wildcards though. */
6007 /* Start by assuming a global wildcard (vCont;c) is possible. */
6008 may_global_wildcard_vcont = 1;
6010 /* And assume every process is individually wildcard-able too. */
6011 ALL_NON_EXITED_INFERIORS (inf)
6013 if (inf->priv == NULL)
6014 inf->priv = XNEW (struct private_inferior);
6015 inf->priv->may_wildcard_vcont = 1;
6018 /* Check for any pending events (not reported or processed yet) and
6019 disable process and global wildcard resumes appropriately. */
6020 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6022 ALL_NON_EXITED_THREADS (tp)
6024 /* If a thread of a process is not meant to be resumed, then we
6025 can't wildcard that process. */
6028 tp->inf->priv->may_wildcard_vcont = 0;
6030 /* And if we can't wildcard a process, we can't wildcard
6031 everything either. */
6032 may_global_wildcard_vcont = 0;
6036 /* If a thread is the parent of an unfollowed fork, then we
6037 can't do a global wildcard, as that would resume the fork
6039 if (is_pending_fork_parent_thread (tp))
6040 may_global_wildcard_vcont = 0;
6043 /* Now let's build the vCont packet(s). Actions must be appended
6044 from narrower to wider scopes (thread -> process -> global). If
6045 we end up with too many actions for a single packet vcont_builder
6046 flushes the current vCont packet to the remote side and starts a
6048 vcont_builder_restart (&vcont_builder);
6050 /* Threads first. */
6051 ALL_NON_EXITED_THREADS (tp)
6053 struct private_thread_info *remote_thr = tp->priv;
6055 if (!tp->executing || remote_thr->vcont_resumed)
6058 gdb_assert (!thread_is_in_step_over_chain (tp));
6060 if (!remote_thr->last_resume_step
6061 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6062 && tp->inf->priv->may_wildcard_vcont)
6064 /* We'll send a wildcard resume instead. */
6065 remote_thr->vcont_resumed = 1;
6069 vcont_builder_push_action (&vcont_builder, tp->ptid,
6070 remote_thr->last_resume_step,
6071 remote_thr->last_resume_sig);
6072 remote_thr->vcont_resumed = 1;
6075 /* Now check whether we can send any process-wide wildcard. This is
6076 to avoid sending a global wildcard in the case nothing is
6077 supposed to be resumed. */
6078 any_process_wildcard = 0;
6080 ALL_NON_EXITED_INFERIORS (inf)
6082 if (inf->priv->may_wildcard_vcont)
6084 any_process_wildcard = 1;
6089 if (any_process_wildcard)
6091 /* If all processes are wildcard-able, then send a single "c"
6092 action, otherwise, send an "all (-1) threads of process"
6093 continue action for each running process, if any. */
6094 if (may_global_wildcard_vcont)
6096 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6101 ALL_NON_EXITED_INFERIORS (inf)
6103 if (inf->priv->may_wildcard_vcont)
6105 vcont_builder_push_action (&vcont_builder,
6106 pid_to_ptid (inf->pid),
6113 vcont_builder_flush (&vcont_builder);
6118 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6119 thread, all threads of a remote process, or all threads of all
6123 remote_stop_ns (ptid_t ptid)
6125 struct remote_state *rs = get_remote_state ();
6127 char *endp = rs->buf + get_remote_packet_size ();
6129 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6130 remote_vcont_probe (rs);
6132 if (!rs->supports_vCont.t)
6133 error (_("Remote server does not support stopping threads"));
6135 if (ptid_equal (ptid, minus_one_ptid)
6136 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6137 p += xsnprintf (p, endp - p, "vCont;t");
6142 p += xsnprintf (p, endp - p, "vCont;t:");
6144 if (ptid_is_pid (ptid))
6145 /* All (-1) threads of process. */
6146 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6149 /* Small optimization: if we already have a stop reply for
6150 this thread, no use in telling the stub we want this
6152 if (peek_stop_reply (ptid))
6158 write_ptid (p, endp, nptid);
6161 /* In non-stop, we get an immediate OK reply. The stop reply will
6162 come in asynchronously by notification. */
6164 getpkt (&rs->buf, &rs->buf_size, 0);
6165 if (strcmp (rs->buf, "OK") != 0)
6166 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6169 /* All-stop version of target_interrupt. Sends a break or a ^C to
6170 interrupt the remote target. It is undefined which thread of which
6171 process reports the interrupt. */
6174 remote_interrupt_as (void)
6176 struct remote_state *rs = get_remote_state ();
6178 rs->ctrlc_pending_p = 1;
6180 /* If the inferior is stopped already, but the core didn't know
6181 about it yet, just ignore the request. The cached wait status
6182 will be collected in remote_wait. */
6183 if (rs->cached_wait_status)
6186 /* Send interrupt_sequence to remote target. */
6187 send_interrupt_sequence ();
6190 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6191 the remote target. It is undefined which thread of which process
6192 reports the interrupt. Throws an error if the packet is not
6193 supported by the server. */
6196 remote_interrupt_ns (void)
6198 struct remote_state *rs = get_remote_state ();
6200 char *endp = rs->buf + get_remote_packet_size ();
6202 xsnprintf (p, endp - p, "vCtrlC");
6204 /* In non-stop, we get an immediate OK reply. The stop reply will
6205 come in asynchronously by notification. */
6207 getpkt (&rs->buf, &rs->buf_size, 0);
6209 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6213 case PACKET_UNKNOWN:
6214 error (_("No support for interrupting the remote target."));
6216 error (_("Interrupting target failed: %s"), rs->buf);
6220 /* Implement the to_stop function for the remote targets. */
6223 remote_stop (struct target_ops *self, ptid_t ptid)
6226 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6228 if (target_is_non_stop_p ())
6229 remote_stop_ns (ptid);
6232 /* We don't currently have a way to transparently pause the
6233 remote target in all-stop mode. Interrupt it instead. */
6234 remote_interrupt_as ();
6238 /* Implement the to_interrupt function for the remote targets. */
6241 remote_interrupt (struct target_ops *self, ptid_t ptid)
6243 struct remote_state *rs = get_remote_state ();
6246 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6248 if (target_is_non_stop_p ())
6249 remote_interrupt_ns ();
6251 remote_interrupt_as ();
6254 /* Implement the to_pass_ctrlc function for the remote targets. */
6257 remote_pass_ctrlc (struct target_ops *self)
6259 struct remote_state *rs = get_remote_state ();
6262 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6264 /* If we're starting up, we're not fully synced yet. Quit
6266 if (rs->starting_up)
6268 /* If ^C has already been sent once, offer to disconnect. */
6269 else if (rs->ctrlc_pending_p)
6272 target_interrupt (inferior_ptid);
6275 /* Ask the user what to do when an interrupt is received. */
6278 interrupt_query (void)
6280 struct remote_state *rs = get_remote_state ();
6282 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6284 if (query (_("The target is not responding to interrupt requests.\n"
6285 "Stop debugging it? ")))
6287 remote_unpush_target ();
6288 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6293 if (query (_("Interrupted while waiting for the program.\n"
6294 "Give up waiting? ")))
6299 /* Enable/disable target terminal ownership. Most targets can use
6300 terminal groups to control terminal ownership. Remote targets are
6301 different in that explicit transfer of ownership to/from GDB/target
6305 remote_terminal_inferior (struct target_ops *self)
6307 /* FIXME: cagney/1999-09-27: Make calls to target_terminal::*()
6308 idempotent. The event-loop GDB talking to an asynchronous target
6309 with a synchronous command calls this function from both
6310 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
6311 transfer the terminal to the target when it shouldn't this guard
6313 if (!remote_async_terminal_ours_p)
6315 remote_async_terminal_ours_p = 0;
6316 /* NOTE: At this point we could also register our selves as the
6317 recipient of all input. Any characters typed could then be
6318 passed on down to the target. */
6322 remote_terminal_ours (struct target_ops *self)
6324 /* See FIXME in remote_terminal_inferior. */
6325 if (remote_async_terminal_ours_p)
6327 remote_async_terminal_ours_p = 1;
6331 remote_console_output (char *msg)
6335 for (p = msg; p[0] && p[1]; p += 2)
6338 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6342 fputs_unfiltered (tb, gdb_stdtarg);
6344 gdb_flush (gdb_stdtarg);
6347 DEF_VEC_O(cached_reg_t);
6349 typedef struct stop_reply
6351 struct notif_event base;
6353 /* The identifier of the thread about this event */
6356 /* The remote state this event is associated with. When the remote
6357 connection, represented by a remote_state object, is closed,
6358 all the associated stop_reply events should be released. */
6359 struct remote_state *rs;
6361 struct target_waitstatus ws;
6363 /* Expedited registers. This makes remote debugging a bit more
6364 efficient for those targets that provide critical registers as
6365 part of their normal status mechanism (as another roundtrip to
6366 fetch them is avoided). */
6367 VEC(cached_reg_t) *regcache;
6369 enum target_stop_reason stop_reason;
6371 CORE_ADDR watch_data_address;
6376 DECLARE_QUEUE_P (stop_reply_p);
6377 DEFINE_QUEUE_P (stop_reply_p);
6378 /* The list of already fetched and acknowledged stop events. This
6379 queue is used for notification Stop, and other notifications
6380 don't need queue for their events, because the notification events
6381 of Stop can't be consumed immediately, so that events should be
6382 queued first, and be consumed by remote_wait_{ns,as} one per
6383 time. Other notifications can consume their events immediately,
6384 so queue is not needed for them. */
6385 static QUEUE (stop_reply_p) *stop_reply_queue;
6388 stop_reply_xfree (struct stop_reply *r)
6390 notif_event_xfree ((struct notif_event *) r);
6393 /* Return the length of the stop reply queue. */
6396 stop_reply_queue_length (void)
6398 return QUEUE_length (stop_reply_p, stop_reply_queue);
6402 remote_notif_stop_parse (struct notif_client *self, char *buf,
6403 struct notif_event *event)
6405 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6409 remote_notif_stop_ack (struct notif_client *self, char *buf,
6410 struct notif_event *event)
6412 struct stop_reply *stop_reply = (struct stop_reply *) event;
6415 putpkt (self->ack_command);
6417 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6418 /* We got an unknown stop reply. */
6419 error (_("Unknown stop reply"));
6421 push_stop_reply (stop_reply);
6425 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6427 /* We can't get pending events in remote_notif_process for
6428 notification stop, and we have to do this in remote_wait_ns
6429 instead. If we fetch all queued events from stub, remote stub
6430 may exit and we have no chance to process them back in
6432 mark_async_event_handler (remote_async_inferior_event_token);
6437 stop_reply_dtr (struct notif_event *event)
6439 struct stop_reply *r = (struct stop_reply *) event;
6444 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6448 VEC_free (cached_reg_t, r->regcache);
6451 static struct notif_event *
6452 remote_notif_stop_alloc_reply (void)
6454 /* We cast to a pointer to the "base class". */
6455 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6457 r->dtr = stop_reply_dtr;
6462 /* A client of notification Stop. */
6464 struct notif_client notif_client_stop =
6468 remote_notif_stop_parse,
6469 remote_notif_stop_ack,
6470 remote_notif_stop_can_get_pending_events,
6471 remote_notif_stop_alloc_reply,
6475 /* A parameter to pass data in and out. */
6477 struct queue_iter_param
6480 struct stop_reply *output;
6483 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6484 the pid of the process that owns the threads we want to check, or
6485 -1 if we want to check all threads. */
6488 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6491 if (ws->kind == TARGET_WAITKIND_FORKED
6492 || ws->kind == TARGET_WAITKIND_VFORKED)
6494 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6501 /* Return the thread's pending status used to determine whether the
6502 thread is a fork parent stopped at a fork event. */
6504 static struct target_waitstatus *
6505 thread_pending_fork_status (struct thread_info *thread)
6507 if (thread->suspend.waitstatus_pending_p)
6508 return &thread->suspend.waitstatus;
6510 return &thread->pending_follow;
6513 /* Determine if THREAD is a pending fork parent thread. */
6516 is_pending_fork_parent_thread (struct thread_info *thread)
6518 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6521 return is_pending_fork_parent (ws, pid, thread->ptid);
6524 /* Check whether EVENT is a fork event, and if it is, remove the
6525 fork child from the context list passed in DATA. */
6528 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6529 QUEUE_ITER (stop_reply_p) *iter,
6533 struct queue_iter_param *param = (struct queue_iter_param *) data;
6534 struct threads_listing_context *context
6535 = (struct threads_listing_context *) param->input;
6537 if (event->ws.kind == TARGET_WAITKIND_FORKED
6538 || event->ws.kind == TARGET_WAITKIND_VFORKED
6539 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6540 threads_listing_context_remove (&event->ws, context);
6545 /* If CONTEXT contains any fork child threads that have not been
6546 reported yet, remove them from the CONTEXT list. If such a
6547 thread exists it is because we are stopped at a fork catchpoint
6548 and have not yet called follow_fork, which will set up the
6549 host-side data structures for the new process. */
6552 remove_new_fork_children (struct threads_listing_context *context)
6554 struct thread_info * thread;
6556 struct notif_client *notif = ¬if_client_stop;
6557 struct queue_iter_param param;
6559 /* For any threads stopped at a fork event, remove the corresponding
6560 fork child threads from the CONTEXT list. */
6561 ALL_NON_EXITED_THREADS (thread)
6563 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6565 if (is_pending_fork_parent (ws, pid, thread->ptid))
6567 threads_listing_context_remove (ws, context);
6571 /* Check for any pending fork events (not reported or processed yet)
6572 in process PID and remove those fork child threads from the
6573 CONTEXT list as well. */
6574 remote_notif_get_pending_events (notif);
6575 param.input = context;
6576 param.output = NULL;
6577 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6578 remove_child_of_pending_fork, ¶m);
6581 /* Check whether EVENT would prevent a global or process wildcard
6585 check_pending_event_prevents_wildcard_vcont_callback
6586 (QUEUE (stop_reply_p) *q,
6587 QUEUE_ITER (stop_reply_p) *iter,
6591 struct inferior *inf;
6592 int *may_global_wildcard_vcont = (int *) data;
6594 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6595 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6598 if (event->ws.kind == TARGET_WAITKIND_FORKED
6599 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6600 *may_global_wildcard_vcont = 0;
6602 inf = find_inferior_ptid (event->ptid);
6604 /* This may be the first time we heard about this process.
6605 Regardless, we must not do a global wildcard resume, otherwise
6606 we'd resume this process too. */
6607 *may_global_wildcard_vcont = 0;
6609 inf->priv->may_wildcard_vcont = 0;
6614 /* Check whether any event pending in the vStopped queue would prevent
6615 a global or process wildcard vCont action. Clear
6616 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6617 and clear the event inferior's may_wildcard_vcont flag if we can't
6618 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6621 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6623 struct notif_client *notif = ¬if_client_stop;
6625 remote_notif_get_pending_events (notif);
6626 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6627 check_pending_event_prevents_wildcard_vcont_callback,
6628 may_global_wildcard);
6631 /* Remove stop replies in the queue if its pid is equal to the given
6635 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6636 QUEUE_ITER (stop_reply_p) *iter,
6640 struct queue_iter_param *param = (struct queue_iter_param *) data;
6641 struct inferior *inf = (struct inferior *) param->input;
6643 if (ptid_get_pid (event->ptid) == inf->pid)
6645 stop_reply_xfree (event);
6646 QUEUE_remove_elem (stop_reply_p, q, iter);
6652 /* Discard all pending stop replies of inferior INF. */
6655 discard_pending_stop_replies (struct inferior *inf)
6657 struct queue_iter_param param;
6658 struct stop_reply *reply;
6659 struct remote_state *rs = get_remote_state ();
6660 struct remote_notif_state *rns = rs->notif_state;
6662 /* This function can be notified when an inferior exists. When the
6663 target is not remote, the notification state is NULL. */
6664 if (rs->remote_desc == NULL)
6667 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6669 /* Discard the in-flight notification. */
6670 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6672 stop_reply_xfree (reply);
6673 rns->pending_event[notif_client_stop.id] = NULL;
6677 param.output = NULL;
6678 /* Discard the stop replies we have already pulled with
6680 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6681 remove_stop_reply_for_inferior, ¶m);
6684 /* If its remote state is equal to the given remote state,
6685 remove EVENT from the stop reply queue. */
6688 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6689 QUEUE_ITER (stop_reply_p) *iter,
6693 struct queue_iter_param *param = (struct queue_iter_param *) data;
6694 struct remote_state *rs = (struct remote_state *) param->input;
6696 if (event->rs == rs)
6698 stop_reply_xfree (event);
6699 QUEUE_remove_elem (stop_reply_p, q, iter);
6705 /* Discard the stop replies for RS in stop_reply_queue. */
6708 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6710 struct queue_iter_param param;
6713 param.output = NULL;
6714 /* Discard the stop replies we have already pulled with
6716 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6717 remove_stop_reply_of_remote_state, ¶m);
6720 /* A parameter to pass data in and out. */
6723 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6724 QUEUE_ITER (stop_reply_p) *iter,
6728 struct queue_iter_param *param = (struct queue_iter_param *) data;
6729 ptid_t *ptid = (ptid_t *) param->input;
6731 if (ptid_match (event->ptid, *ptid))
6733 param->output = event;
6734 QUEUE_remove_elem (stop_reply_p, q, iter);
6741 /* Remove the first reply in 'stop_reply_queue' which matches
6744 static struct stop_reply *
6745 remote_notif_remove_queued_reply (ptid_t ptid)
6747 struct queue_iter_param param;
6749 param.input = &ptid;
6750 param.output = NULL;
6752 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6753 remote_notif_remove_once_on_match, ¶m);
6755 fprintf_unfiltered (gdb_stdlog,
6756 "notif: discard queued event: 'Stop' in %s\n",
6757 target_pid_to_str (ptid));
6759 return param.output;
6762 /* Look for a queued stop reply belonging to PTID. If one is found,
6763 remove it from the queue, and return it. Returns NULL if none is
6764 found. If there are still queued events left to process, tell the
6765 event loop to get back to target_wait soon. */
6767 static struct stop_reply *
6768 queued_stop_reply (ptid_t ptid)
6770 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6772 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6773 /* There's still at least an event left. */
6774 mark_async_event_handler (remote_async_inferior_event_token);
6779 /* Push a fully parsed stop reply in the stop reply queue. Since we
6780 know that we now have at least one queued event left to pass to the
6781 core side, tell the event loop to get back to target_wait soon. */
6784 push_stop_reply (struct stop_reply *new_event)
6786 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6789 fprintf_unfiltered (gdb_stdlog,
6790 "notif: push 'Stop' %s to queue %d\n",
6791 target_pid_to_str (new_event->ptid),
6792 QUEUE_length (stop_reply_p,
6795 mark_async_event_handler (remote_async_inferior_event_token);
6799 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6800 QUEUE_ITER (stop_reply_p) *iter,
6801 struct stop_reply *event,
6804 ptid_t *ptid = (ptid_t *) data;
6806 return !(ptid_equal (*ptid, event->ptid)
6807 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6810 /* Returns true if we have a stop reply for PTID. */
6813 peek_stop_reply (ptid_t ptid)
6815 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6816 stop_reply_match_ptid_and_ws, &ptid);
6819 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
6820 starting with P and ending with PEND matches PREFIX. */
6823 strprefix (const char *p, const char *pend, const char *prefix)
6825 for ( ; p < pend; p++, prefix++)
6828 return *prefix == '\0';
6831 /* Parse the stop reply in BUF. Either the function succeeds, and the
6832 result is stored in EVENT, or throws an error. */
6835 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6837 struct remote_arch_state *rsa = get_remote_arch_state ();
6842 event->ptid = null_ptid;
6843 event->rs = get_remote_state ();
6844 event->ws.kind = TARGET_WAITKIND_IGNORE;
6845 event->ws.value.integer = 0;
6846 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6847 event->regcache = NULL;
6852 case 'T': /* Status with PC, SP, FP, ... */
6853 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6854 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6856 n... = register number
6857 r... = register contents
6860 p = &buf[3]; /* after Txx */
6866 p1 = strchr (p, ':');
6868 error (_("Malformed packet(a) (missing colon): %s\n\
6872 error (_("Malformed packet(a) (missing register number): %s\n\
6876 /* Some "registers" are actually extended stop information.
6877 Note if you're adding a new entry here: GDB 7.9 and
6878 earlier assume that all register "numbers" that start
6879 with an hex digit are real register numbers. Make sure
6880 the server only sends such a packet if it knows the
6881 client understands it. */
6883 if (strprefix (p, p1, "thread"))
6884 event->ptid = read_ptid (++p1, &p);
6885 else if (strprefix (p, p1, "syscall_entry"))
6889 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6890 p = unpack_varlen_hex (++p1, &sysno);
6891 event->ws.value.syscall_number = (int) sysno;
6893 else if (strprefix (p, p1, "syscall_return"))
6897 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6898 p = unpack_varlen_hex (++p1, &sysno);
6899 event->ws.value.syscall_number = (int) sysno;
6901 else if (strprefix (p, p1, "watch")
6902 || strprefix (p, p1, "rwatch")
6903 || strprefix (p, p1, "awatch"))
6905 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6906 p = unpack_varlen_hex (++p1, &addr);
6907 event->watch_data_address = (CORE_ADDR) addr;
6909 else if (strprefix (p, p1, "swbreak"))
6911 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6913 /* Make sure the stub doesn't forget to indicate support
6915 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6916 error (_("Unexpected swbreak stop reason"));
6918 /* The value part is documented as "must be empty",
6919 though we ignore it, in case we ever decide to make
6920 use of it in a backward compatible way. */
6921 p = strchrnul (p1 + 1, ';');
6923 else if (strprefix (p, p1, "hwbreak"))
6925 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6927 /* Make sure the stub doesn't forget to indicate support
6929 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6930 error (_("Unexpected hwbreak stop reason"));
6933 p = strchrnul (p1 + 1, ';');
6935 else if (strprefix (p, p1, "library"))
6937 event->ws.kind = TARGET_WAITKIND_LOADED;
6938 p = strchrnul (p1 + 1, ';');
6940 else if (strprefix (p, p1, "replaylog"))
6942 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6943 /* p1 will indicate "begin" or "end", but it makes
6944 no difference for now, so ignore it. */
6945 p = strchrnul (p1 + 1, ';');
6947 else if (strprefix (p, p1, "core"))
6951 p = unpack_varlen_hex (++p1, &c);
6954 else if (strprefix (p, p1, "fork"))
6956 event->ws.value.related_pid = read_ptid (++p1, &p);
6957 event->ws.kind = TARGET_WAITKIND_FORKED;
6959 else if (strprefix (p, p1, "vfork"))
6961 event->ws.value.related_pid = read_ptid (++p1, &p);
6962 event->ws.kind = TARGET_WAITKIND_VFORKED;
6964 else if (strprefix (p, p1, "vforkdone"))
6966 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6967 p = strchrnul (p1 + 1, ';');
6969 else if (strprefix (p, p1, "exec"))
6972 char pathname[PATH_MAX];
6975 /* Determine the length of the execd pathname. */
6976 p = unpack_varlen_hex (++p1, &ignored);
6977 pathlen = (p - p1) / 2;
6979 /* Save the pathname for event reporting and for
6980 the next run command. */
6981 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6982 pathname[pathlen] = '\0';
6984 /* This is freed during event handling. */
6985 event->ws.value.execd_pathname = xstrdup (pathname);
6986 event->ws.kind = TARGET_WAITKIND_EXECD;
6988 /* Skip the registers included in this packet, since
6989 they may be for an architecture different from the
6990 one used by the original program. */
6993 else if (strprefix (p, p1, "create"))
6995 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6996 p = strchrnul (p1 + 1, ';');
7005 p = strchrnul (p1 + 1, ';');
7010 /* Maybe a real ``P'' register number. */
7011 p_temp = unpack_varlen_hex (p, &pnum);
7012 /* If the first invalid character is the colon, we got a
7013 register number. Otherwise, it's an unknown stop
7017 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
7018 cached_reg_t cached_reg;
7019 struct gdbarch *gdbarch = target_gdbarch ();
7022 error (_("Remote sent bad register number %s: %s\n\
7024 hex_string (pnum), p, buf);
7026 cached_reg.num = reg->regnum;
7027 cached_reg.data = (gdb_byte *)
7028 xmalloc (register_size (gdbarch, reg->regnum));
7031 fieldsize = hex2bin (p, cached_reg.data,
7032 register_size (gdbarch, reg->regnum));
7034 if (fieldsize < register_size (gdbarch, reg->regnum))
7035 warning (_("Remote reply is too short: %s"), buf);
7037 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7041 /* Not a number. Silently skip unknown optional
7043 p = strchrnul (p1 + 1, ';');
7048 error (_("Remote register badly formatted: %s\nhere: %s"),
7053 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7057 case 'S': /* Old style status, just signal only. */
7061 event->ws.kind = TARGET_WAITKIND_STOPPED;
7062 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7063 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7064 event->ws.value.sig = (enum gdb_signal) sig;
7066 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7069 case 'w': /* Thread exited. */
7074 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7075 p = unpack_varlen_hex (&buf[1], &value);
7076 event->ws.value.integer = value;
7078 error (_("stop reply packet badly formatted: %s"), buf);
7079 event->ptid = read_ptid (++p, NULL);
7082 case 'W': /* Target exited. */
7089 /* GDB used to accept only 2 hex chars here. Stubs should
7090 only send more if they detect GDB supports multi-process
7092 p = unpack_varlen_hex (&buf[1], &value);
7096 /* The remote process exited. */
7097 event->ws.kind = TARGET_WAITKIND_EXITED;
7098 event->ws.value.integer = value;
7102 /* The remote process exited with a signal. */
7103 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7104 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7105 event->ws.value.sig = (enum gdb_signal) value;
7107 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7110 /* If no process is specified, assume inferior_ptid. */
7111 pid = ptid_get_pid (inferior_ptid);
7120 else if (startswith (p, "process:"))
7124 p += sizeof ("process:") - 1;
7125 unpack_varlen_hex (p, &upid);
7129 error (_("unknown stop reply packet: %s"), buf);
7132 error (_("unknown stop reply packet: %s"), buf);
7133 event->ptid = pid_to_ptid (pid);
7137 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7138 event->ptid = minus_one_ptid;
7142 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7143 error (_("No process or thread specified in stop reply: %s"), buf);
7146 /* When the stub wants to tell GDB about a new notification reply, it
7147 sends a notification (%Stop, for example). Those can come it at
7148 any time, hence, we have to make sure that any pending
7149 putpkt/getpkt sequence we're making is finished, before querying
7150 the stub for more events with the corresponding ack command
7151 (vStopped, for example). E.g., if we started a vStopped sequence
7152 immediately upon receiving the notification, something like this
7160 1.6) <-- (registers reply to step #1.3)
7162 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7165 To solve this, whenever we parse a %Stop notification successfully,
7166 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7167 doing whatever we were doing:
7173 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7174 2.5) <-- (registers reply to step #2.3)
7176 Eventualy after step #2.5, we return to the event loop, which
7177 notices there's an event on the
7178 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7179 associated callback --- the function below. At this point, we're
7180 always safe to start a vStopped sequence. :
7183 2.7) <-- T05 thread:2
7189 remote_notif_get_pending_events (struct notif_client *nc)
7191 struct remote_state *rs = get_remote_state ();
7193 if (rs->notif_state->pending_event[nc->id] != NULL)
7196 fprintf_unfiltered (gdb_stdlog,
7197 "notif: process: '%s' ack pending event\n",
7201 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7202 rs->notif_state->pending_event[nc->id] = NULL;
7206 getpkt (&rs->buf, &rs->buf_size, 0);
7207 if (strcmp (rs->buf, "OK") == 0)
7210 remote_notif_ack (nc, rs->buf);
7216 fprintf_unfiltered (gdb_stdlog,
7217 "notif: process: '%s' no pending reply\n",
7222 /* Called when it is decided that STOP_REPLY holds the info of the
7223 event that is to be returned to the core. This function always
7224 destroys STOP_REPLY. */
7227 process_stop_reply (struct stop_reply *stop_reply,
7228 struct target_waitstatus *status)
7232 *status = stop_reply->ws;
7233 ptid = stop_reply->ptid;
7235 /* If no thread/process was reported by the stub, assume the current
7237 if (ptid_equal (ptid, null_ptid))
7238 ptid = inferior_ptid;
7240 if (status->kind != TARGET_WAITKIND_EXITED
7241 && status->kind != TARGET_WAITKIND_SIGNALLED
7242 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7244 struct private_thread_info *remote_thr;
7246 /* Expedited registers. */
7247 if (stop_reply->regcache)
7249 struct regcache *regcache
7250 = get_thread_arch_regcache (ptid, target_gdbarch ());
7255 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7258 regcache_raw_supply (regcache, reg->num, reg->data);
7262 VEC_free (cached_reg_t, stop_reply->regcache);
7265 remote_notice_new_inferior (ptid, 0);
7266 remote_thr = get_private_info_ptid (ptid);
7267 remote_thr->core = stop_reply->core;
7268 remote_thr->stop_reason = stop_reply->stop_reason;
7269 remote_thr->watch_data_address = stop_reply->watch_data_address;
7270 remote_thr->vcont_resumed = 0;
7273 stop_reply_xfree (stop_reply);
7277 /* The non-stop mode version of target_wait. */
7280 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7282 struct remote_state *rs = get_remote_state ();
7283 struct stop_reply *stop_reply;
7287 /* If in non-stop mode, get out of getpkt even if a
7288 notification is received. */
7290 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7291 0 /* forever */, &is_notif);
7294 if (ret != -1 && !is_notif)
7297 case 'E': /* Error of some sort. */
7298 /* We're out of sync with the target now. Did it continue
7299 or not? We can't tell which thread it was in non-stop,
7300 so just ignore this. */
7301 warning (_("Remote failure reply: %s"), rs->buf);
7303 case 'O': /* Console output. */
7304 remote_console_output (rs->buf + 1);
7307 warning (_("Invalid remote reply: %s"), rs->buf);
7311 /* Acknowledge a pending stop reply that may have arrived in the
7313 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7314 remote_notif_get_pending_events (¬if_client_stop);
7316 /* If indeed we noticed a stop reply, we're done. */
7317 stop_reply = queued_stop_reply (ptid);
7318 if (stop_reply != NULL)
7319 return process_stop_reply (stop_reply, status);
7321 /* Still no event. If we're just polling for an event, then
7322 return to the event loop. */
7323 if (options & TARGET_WNOHANG)
7325 status->kind = TARGET_WAITKIND_IGNORE;
7326 return minus_one_ptid;
7329 /* Otherwise do a blocking wait. */
7330 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7331 1 /* forever */, &is_notif);
7335 /* Wait until the remote machine stops, then return, storing status in
7336 STATUS just as `wait' would. */
7339 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7341 struct remote_state *rs = get_remote_state ();
7342 ptid_t event_ptid = null_ptid;
7344 struct stop_reply *stop_reply;
7348 status->kind = TARGET_WAITKIND_IGNORE;
7349 status->value.integer = 0;
7351 stop_reply = queued_stop_reply (ptid);
7352 if (stop_reply != NULL)
7353 return process_stop_reply (stop_reply, status);
7355 if (rs->cached_wait_status)
7356 /* Use the cached wait status, but only once. */
7357 rs->cached_wait_status = 0;
7362 int forever = ((options & TARGET_WNOHANG) == 0
7363 && wait_forever_enabled_p);
7365 if (!rs->waiting_for_stop_reply)
7367 status->kind = TARGET_WAITKIND_NO_RESUMED;
7368 return minus_one_ptid;
7371 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7372 _never_ wait for ever -> test on target_is_async_p().
7373 However, before we do that we need to ensure that the caller
7374 knows how to take the target into/out of async mode. */
7375 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7376 forever, &is_notif);
7378 /* GDB gets a notification. Return to core as this event is
7380 if (ret != -1 && is_notif)
7381 return minus_one_ptid;
7383 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7384 return minus_one_ptid;
7389 /* Assume that the target has acknowledged Ctrl-C unless we receive
7390 an 'F' or 'O' packet. */
7391 if (buf[0] != 'F' && buf[0] != 'O')
7392 rs->ctrlc_pending_p = 0;
7396 case 'E': /* Error of some sort. */
7397 /* We're out of sync with the target now. Did it continue or
7398 not? Not is more likely, so report a stop. */
7399 rs->waiting_for_stop_reply = 0;
7401 warning (_("Remote failure reply: %s"), buf);
7402 status->kind = TARGET_WAITKIND_STOPPED;
7403 status->value.sig = GDB_SIGNAL_0;
7405 case 'F': /* File-I/O request. */
7406 /* GDB may access the inferior memory while handling the File-I/O
7407 request, but we don't want GDB accessing memory while waiting
7408 for a stop reply. See the comments in putpkt_binary. Set
7409 waiting_for_stop_reply to 0 temporarily. */
7410 rs->waiting_for_stop_reply = 0;
7411 remote_fileio_request (buf, rs->ctrlc_pending_p);
7412 rs->ctrlc_pending_p = 0;
7413 /* GDB handled the File-I/O request, and the target is running
7414 again. Keep waiting for events. */
7415 rs->waiting_for_stop_reply = 1;
7417 case 'N': case 'T': case 'S': case 'X': case 'W':
7419 struct stop_reply *stop_reply;
7421 /* There is a stop reply to handle. */
7422 rs->waiting_for_stop_reply = 0;
7425 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
7428 event_ptid = process_stop_reply (stop_reply, status);
7431 case 'O': /* Console output. */
7432 remote_console_output (buf + 1);
7435 if (rs->last_sent_signal != GDB_SIGNAL_0)
7437 /* Zero length reply means that we tried 'S' or 'C' and the
7438 remote system doesn't support it. */
7439 target_terminal::ours_for_output ();
7441 ("Can't send signals to this remote system. %s not sent.\n",
7442 gdb_signal_to_name (rs->last_sent_signal));
7443 rs->last_sent_signal = GDB_SIGNAL_0;
7444 target_terminal::inferior ();
7446 strcpy (buf, rs->last_sent_step ? "s" : "c");
7450 /* else fallthrough */
7452 warning (_("Invalid remote reply: %s"), buf);
7456 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7457 return minus_one_ptid;
7458 else if (status->kind == TARGET_WAITKIND_IGNORE)
7460 /* Nothing interesting happened. If we're doing a non-blocking
7461 poll, we're done. Otherwise, go back to waiting. */
7462 if (options & TARGET_WNOHANG)
7463 return minus_one_ptid;
7467 else if (status->kind != TARGET_WAITKIND_EXITED
7468 && status->kind != TARGET_WAITKIND_SIGNALLED)
7470 if (!ptid_equal (event_ptid, null_ptid))
7471 record_currthread (rs, event_ptid);
7473 event_ptid = inferior_ptid;
7476 /* A process exit. Invalidate our notion of current thread. */
7477 record_currthread (rs, minus_one_ptid);
7482 /* Wait until the remote machine stops, then return, storing status in
7483 STATUS just as `wait' would. */
7486 remote_wait (struct target_ops *ops,
7487 ptid_t ptid, struct target_waitstatus *status, int options)
7491 if (target_is_non_stop_p ())
7492 event_ptid = remote_wait_ns (ptid, status, options);
7494 event_ptid = remote_wait_as (ptid, status, options);
7496 if (target_is_async_p ())
7498 /* If there are are events left in the queue tell the event loop
7500 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7501 mark_async_event_handler (remote_async_inferior_event_token);
7507 /* Fetch a single register using a 'p' packet. */
7510 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7512 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7513 struct remote_state *rs = get_remote_state ();
7515 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7518 if (packet_support (PACKET_p) == PACKET_DISABLE)
7521 if (reg->pnum == -1)
7526 p += hexnumstr (p, reg->pnum);
7529 getpkt (&rs->buf, &rs->buf_size, 0);
7533 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7537 case PACKET_UNKNOWN:
7540 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7541 gdbarch_register_name (get_regcache_arch (regcache),
7546 /* If this register is unfetchable, tell the regcache. */
7549 regcache_raw_supply (regcache, reg->regnum, NULL);
7553 /* Otherwise, parse and supply the value. */
7559 error (_("fetch_register_using_p: early buf termination"));
7561 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7564 regcache_raw_supply (regcache, reg->regnum, regp);
7568 /* Fetch the registers included in the target's 'g' packet. */
7571 send_g_packet (void)
7573 struct remote_state *rs = get_remote_state ();
7576 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7577 remote_send (&rs->buf, &rs->buf_size);
7579 /* We can get out of synch in various cases. If the first character
7580 in the buffer is not a hex character, assume that has happened
7581 and try to fetch another packet to read. */
7582 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7583 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7584 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7585 && rs->buf[0] != 'x') /* New: unavailable register value. */
7588 fprintf_unfiltered (gdb_stdlog,
7589 "Bad register packet; fetching a new packet\n");
7590 getpkt (&rs->buf, &rs->buf_size, 0);
7593 buf_len = strlen (rs->buf);
7595 /* Sanity check the received packet. */
7596 if (buf_len % 2 != 0)
7597 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7603 process_g_packet (struct regcache *regcache)
7605 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7606 struct remote_state *rs = get_remote_state ();
7607 struct remote_arch_state *rsa = get_remote_arch_state ();
7612 buf_len = strlen (rs->buf);
7614 /* Further sanity checks, with knowledge of the architecture. */
7615 if (buf_len > 2 * rsa->sizeof_g_packet)
7616 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7617 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7619 /* Save the size of the packet sent to us by the target. It is used
7620 as a heuristic when determining the max size of packets that the
7621 target can safely receive. */
7622 if (rsa->actual_register_packet_size == 0)
7623 rsa->actual_register_packet_size = buf_len;
7625 /* If this is smaller than we guessed the 'g' packet would be,
7626 update our records. A 'g' reply that doesn't include a register's
7627 value implies either that the register is not available, or that
7628 the 'p' packet must be used. */
7629 if (buf_len < 2 * rsa->sizeof_g_packet)
7631 long sizeof_g_packet = buf_len / 2;
7633 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7635 long offset = rsa->regs[i].offset;
7636 long reg_size = register_size (gdbarch, i);
7638 if (rsa->regs[i].pnum == -1)
7641 if (offset >= sizeof_g_packet)
7642 rsa->regs[i].in_g_packet = 0;
7643 else if (offset + reg_size > sizeof_g_packet)
7644 error (_("Truncated register %d in remote 'g' packet"), i);
7646 rsa->regs[i].in_g_packet = 1;
7649 /* Looks valid enough, we can assume this is the correct length
7650 for a 'g' packet. It's important not to adjust
7651 rsa->sizeof_g_packet if we have truncated registers otherwise
7652 this "if" won't be run the next time the method is called
7653 with a packet of the same size and one of the internal errors
7654 below will trigger instead. */
7655 rsa->sizeof_g_packet = sizeof_g_packet;
7658 regs = (char *) alloca (rsa->sizeof_g_packet);
7660 /* Unimplemented registers read as all bits zero. */
7661 memset (regs, 0, rsa->sizeof_g_packet);
7663 /* Reply describes registers byte by byte, each byte encoded as two
7664 hex characters. Suck them all up, then supply them to the
7665 register cacheing/storage mechanism. */
7668 for (i = 0; i < rsa->sizeof_g_packet; i++)
7670 if (p[0] == 0 || p[1] == 0)
7671 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7672 internal_error (__FILE__, __LINE__,
7673 _("unexpected end of 'g' packet reply"));
7675 if (p[0] == 'x' && p[1] == 'x')
7676 regs[i] = 0; /* 'x' */
7678 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7682 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7684 struct packet_reg *r = &rsa->regs[i];
7685 long reg_size = register_size (gdbarch, i);
7689 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7690 /* This shouldn't happen - we adjusted in_g_packet above. */
7691 internal_error (__FILE__, __LINE__,
7692 _("unexpected end of 'g' packet reply"));
7693 else if (rs->buf[r->offset * 2] == 'x')
7695 gdb_assert (r->offset * 2 < strlen (rs->buf));
7696 /* The register isn't available, mark it as such (at
7697 the same time setting the value to zero). */
7698 regcache_raw_supply (regcache, r->regnum, NULL);
7701 regcache_raw_supply (regcache, r->regnum,
7708 fetch_registers_using_g (struct regcache *regcache)
7711 process_g_packet (regcache);
7714 /* Make the remote selected traceframe match GDB's selected
7718 set_remote_traceframe (void)
7721 struct remote_state *rs = get_remote_state ();
7723 if (rs->remote_traceframe_number == get_traceframe_number ())
7726 /* Avoid recursion, remote_trace_find calls us again. */
7727 rs->remote_traceframe_number = get_traceframe_number ();
7729 newnum = target_trace_find (tfind_number,
7730 get_traceframe_number (), 0, 0, NULL);
7732 /* Should not happen. If it does, all bets are off. */
7733 if (newnum != get_traceframe_number ())
7734 warning (_("could not set remote traceframe"));
7738 remote_fetch_registers (struct target_ops *ops,
7739 struct regcache *regcache, int regnum)
7741 struct remote_arch_state *rsa = get_remote_arch_state ();
7744 set_remote_traceframe ();
7745 set_general_thread (regcache_get_ptid (regcache));
7749 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7751 gdb_assert (reg != NULL);
7753 /* If this register might be in the 'g' packet, try that first -
7754 we are likely to read more than one register. If this is the
7755 first 'g' packet, we might be overly optimistic about its
7756 contents, so fall back to 'p'. */
7757 if (reg->in_g_packet)
7759 fetch_registers_using_g (regcache);
7760 if (reg->in_g_packet)
7764 if (fetch_register_using_p (regcache, reg))
7767 /* This register is not available. */
7768 regcache_raw_supply (regcache, reg->regnum, NULL);
7773 fetch_registers_using_g (regcache);
7775 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7776 if (!rsa->regs[i].in_g_packet)
7777 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7779 /* This register is not available. */
7780 regcache_raw_supply (regcache, i, NULL);
7784 /* Prepare to store registers. Since we may send them all (using a
7785 'G' request), we have to read out the ones we don't want to change
7789 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7791 struct remote_arch_state *rsa = get_remote_arch_state ();
7794 /* Make sure the entire registers array is valid. */
7795 switch (packet_support (PACKET_P))
7797 case PACKET_DISABLE:
7798 case PACKET_SUPPORT_UNKNOWN:
7799 /* Make sure all the necessary registers are cached. */
7800 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7801 if (rsa->regs[i].in_g_packet)
7802 regcache_raw_update (regcache, rsa->regs[i].regnum);
7809 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
7810 packet was not recognized. */
7813 store_register_using_P (const struct regcache *regcache,
7814 struct packet_reg *reg)
7816 struct gdbarch *gdbarch = get_regcache_arch (regcache);
7817 struct remote_state *rs = get_remote_state ();
7818 /* Try storing a single register. */
7819 char *buf = rs->buf;
7820 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7823 if (packet_support (PACKET_P) == PACKET_DISABLE)
7826 if (reg->pnum == -1)
7829 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7830 p = buf + strlen (buf);
7831 regcache_raw_collect (regcache, reg->regnum, regp);
7832 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7834 getpkt (&rs->buf, &rs->buf_size, 0);
7836 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7841 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7842 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7843 case PACKET_UNKNOWN:
7846 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7850 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7851 contents of the register cache buffer. FIXME: ignores errors. */
7854 store_registers_using_G (const struct regcache *regcache)
7856 struct remote_state *rs = get_remote_state ();
7857 struct remote_arch_state *rsa = get_remote_arch_state ();
7861 /* Extract all the registers in the regcache copying them into a
7866 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7867 memset (regs, 0, rsa->sizeof_g_packet);
7868 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7870 struct packet_reg *r = &rsa->regs[i];
7873 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7877 /* Command describes registers byte by byte,
7878 each byte encoded as two hex characters. */
7881 bin2hex (regs, p, rsa->sizeof_g_packet);
7883 getpkt (&rs->buf, &rs->buf_size, 0);
7884 if (packet_check_result (rs->buf) == PACKET_ERROR)
7885 error (_("Could not write registers; remote failure reply '%s'"),
7889 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7890 of the register cache buffer. FIXME: ignores errors. */
7893 remote_store_registers (struct target_ops *ops,
7894 struct regcache *regcache, int regnum)
7896 struct remote_arch_state *rsa = get_remote_arch_state ();
7899 set_remote_traceframe ();
7900 set_general_thread (regcache_get_ptid (regcache));
7904 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
7906 gdb_assert (reg != NULL);
7908 /* Always prefer to store registers using the 'P' packet if
7909 possible; we often change only a small number of registers.
7910 Sometimes we change a larger number; we'd need help from a
7911 higher layer to know to use 'G'. */
7912 if (store_register_using_P (regcache, reg))
7915 /* For now, don't complain if we have no way to write the
7916 register. GDB loses track of unavailable registers too
7917 easily. Some day, this may be an error. We don't have
7918 any way to read the register, either... */
7919 if (!reg->in_g_packet)
7922 store_registers_using_G (regcache);
7926 store_registers_using_G (regcache);
7928 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
7929 if (!rsa->regs[i].in_g_packet)
7930 if (!store_register_using_P (regcache, &rsa->regs[i]))
7931 /* See above for why we do not issue an error here. */
7936 /* Return the number of hex digits in num. */
7939 hexnumlen (ULONGEST num)
7943 for (i = 0; num != 0; i++)
7946 return std::max (i, 1);
7949 /* Set BUF to the minimum number of hex digits representing NUM. */
7952 hexnumstr (char *buf, ULONGEST num)
7954 int len = hexnumlen (num);
7956 return hexnumnstr (buf, num, len);
7960 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
7963 hexnumnstr (char *buf, ULONGEST num, int width)
7969 for (i = width - 1; i >= 0; i--)
7971 buf[i] = "0123456789abcdef"[(num & 0xf)];
7978 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
7981 remote_address_masked (CORE_ADDR addr)
7983 unsigned int address_size = remote_address_size;
7985 /* If "remoteaddresssize" was not set, default to target address size. */
7987 address_size = gdbarch_addr_bit (target_gdbarch ());
7989 if (address_size > 0
7990 && address_size < (sizeof (ULONGEST) * 8))
7992 /* Only create a mask when that mask can safely be constructed
7993 in a ULONGEST variable. */
7996 mask = (mask << address_size) - 1;
8002 /* Determine whether the remote target supports binary downloading.
8003 This is accomplished by sending a no-op memory write of zero length
8004 to the target at the specified address. It does not suffice to send
8005 the whole packet, since many stubs strip the eighth bit and
8006 subsequently compute a wrong checksum, which causes real havoc with
8009 NOTE: This can still lose if the serial line is not eight-bit
8010 clean. In cases like this, the user should clear "remote
8014 check_binary_download (CORE_ADDR addr)
8016 struct remote_state *rs = get_remote_state ();
8018 switch (packet_support (PACKET_X))
8020 case PACKET_DISABLE:
8024 case PACKET_SUPPORT_UNKNOWN:
8030 p += hexnumstr (p, (ULONGEST) addr);
8032 p += hexnumstr (p, (ULONGEST) 0);
8036 putpkt_binary (rs->buf, (int) (p - rs->buf));
8037 getpkt (&rs->buf, &rs->buf_size, 0);
8039 if (rs->buf[0] == '\0')
8042 fprintf_unfiltered (gdb_stdlog,
8043 "binary downloading NOT "
8044 "supported by target\n");
8045 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8050 fprintf_unfiltered (gdb_stdlog,
8051 "binary downloading supported by target\n");
8052 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8059 /* Helper function to resize the payload in order to try to get a good
8060 alignment. We try to write an amount of data such that the next write will
8061 start on an address aligned on REMOTE_ALIGN_WRITES. */
8064 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8066 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8069 /* Write memory data directly to the remote machine.
8070 This does not inform the data cache; the data cache uses this.
8071 HEADER is the starting part of the packet.
8072 MEMADDR is the address in the remote memory space.
8073 MYADDR is the address of the buffer in our space.
8074 LEN_UNITS is the number of addressable units to write.
8075 UNIT_SIZE is the length in bytes of an addressable unit.
8076 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8077 should send data as binary ('X'), or hex-encoded ('M').
8079 The function creates packet of the form
8080 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8082 where encoding of <DATA> is terminated by PACKET_FORMAT.
8084 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8087 Return the transferred status, error or OK (an
8088 'enum target_xfer_status' value). Save the number of addressable units
8089 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8091 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8092 exchange between gdb and the stub could look like (?? in place of the
8098 -> $M1000,3:eeeeffffeeee#??
8102 <- eeeeffffeeeedddd */
8104 static enum target_xfer_status
8105 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8106 const gdb_byte *myaddr, ULONGEST len_units,
8107 int unit_size, ULONGEST *xfered_len_units,
8108 char packet_format, int use_length)
8110 struct remote_state *rs = get_remote_state ();
8116 int payload_capacity_bytes;
8117 int payload_length_bytes;
8119 if (packet_format != 'X' && packet_format != 'M')
8120 internal_error (__FILE__, __LINE__,
8121 _("remote_write_bytes_aux: bad packet format"));
8124 return TARGET_XFER_EOF;
8126 payload_capacity_bytes = get_memory_write_packet_size ();
8128 /* The packet buffer will be large enough for the payload;
8129 get_memory_packet_size ensures this. */
8132 /* Compute the size of the actual payload by subtracting out the
8133 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8135 payload_capacity_bytes -= strlen ("$,:#NN");
8137 /* The comma won't be used. */
8138 payload_capacity_bytes += 1;
8139 payload_capacity_bytes -= strlen (header);
8140 payload_capacity_bytes -= hexnumlen (memaddr);
8142 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8144 strcat (rs->buf, header);
8145 p = rs->buf + strlen (header);
8147 /* Compute a best guess of the number of bytes actually transfered. */
8148 if (packet_format == 'X')
8150 /* Best guess at number of bytes that will fit. */
8151 todo_units = std::min (len_units,
8152 (ULONGEST) payload_capacity_bytes / unit_size);
8154 payload_capacity_bytes -= hexnumlen (todo_units);
8155 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8159 /* Number of bytes that will fit. */
8161 = std::min (len_units,
8162 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8164 payload_capacity_bytes -= hexnumlen (todo_units);
8165 todo_units = std::min (todo_units,
8166 (payload_capacity_bytes / unit_size) / 2);
8169 if (todo_units <= 0)
8170 internal_error (__FILE__, __LINE__,
8171 _("minimum packet size too small to write data"));
8173 /* If we already need another packet, then try to align the end
8174 of this packet to a useful boundary. */
8175 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8176 todo_units = align_for_efficient_write (todo_units, memaddr);
8178 /* Append "<memaddr>". */
8179 memaddr = remote_address_masked (memaddr);
8180 p += hexnumstr (p, (ULONGEST) memaddr);
8187 /* Append the length and retain its location and size. It may need to be
8188 adjusted once the packet body has been created. */
8190 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8198 /* Append the packet body. */
8199 if (packet_format == 'X')
8201 /* Binary mode. Send target system values byte by byte, in
8202 increasing byte addresses. Only escape certain critical
8204 payload_length_bytes =
8205 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8206 &units_written, payload_capacity_bytes);
8208 /* If not all TODO units fit, then we'll need another packet. Make
8209 a second try to keep the end of the packet aligned. Don't do
8210 this if the packet is tiny. */
8211 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8215 new_todo_units = align_for_efficient_write (units_written, memaddr);
8217 if (new_todo_units != units_written)
8218 payload_length_bytes =
8219 remote_escape_output (myaddr, new_todo_units, unit_size,
8220 (gdb_byte *) p, &units_written,
8221 payload_capacity_bytes);
8224 p += payload_length_bytes;
8225 if (use_length && units_written < todo_units)
8227 /* Escape chars have filled up the buffer prematurely,
8228 and we have actually sent fewer units than planned.
8229 Fix-up the length field of the packet. Use the same
8230 number of characters as before. */
8231 plen += hexnumnstr (plen, (ULONGEST) units_written,
8233 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8238 /* Normal mode: Send target system values byte by byte, in
8239 increasing byte addresses. Each byte is encoded as a two hex
8241 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8242 units_written = todo_units;
8245 putpkt_binary (rs->buf, (int) (p - rs->buf));
8246 getpkt (&rs->buf, &rs->buf_size, 0);
8248 if (rs->buf[0] == 'E')
8249 return TARGET_XFER_E_IO;
8251 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8252 send fewer units than we'd planned. */
8253 *xfered_len_units = (ULONGEST) units_written;
8254 return TARGET_XFER_OK;
8257 /* Write memory data directly to the remote machine.
8258 This does not inform the data cache; the data cache uses this.
8259 MEMADDR is the address in the remote memory space.
8260 MYADDR is the address of the buffer in our space.
8261 LEN is the number of bytes.
8263 Return the transferred status, error or OK (an
8264 'enum target_xfer_status' value). Save the number of bytes
8265 transferred in *XFERED_LEN. Only transfer a single packet. */
8267 static enum target_xfer_status
8268 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8269 int unit_size, ULONGEST *xfered_len)
8271 const char *packet_format = NULL;
8273 /* Check whether the target supports binary download. */
8274 check_binary_download (memaddr);
8276 switch (packet_support (PACKET_X))
8279 packet_format = "X";
8281 case PACKET_DISABLE:
8282 packet_format = "M";
8284 case PACKET_SUPPORT_UNKNOWN:
8285 internal_error (__FILE__, __LINE__,
8286 _("remote_write_bytes: bad internal state"));
8288 internal_error (__FILE__, __LINE__, _("bad switch"));
8291 return remote_write_bytes_aux (packet_format,
8292 memaddr, myaddr, len, unit_size, xfered_len,
8293 packet_format[0], 1);
8296 /* Read memory data directly from the remote machine.
8297 This does not use the data cache; the data cache uses this.
8298 MEMADDR is the address in the remote memory space.
8299 MYADDR is the address of the buffer in our space.
8300 LEN_UNITS is the number of addressable memory units to read..
8301 UNIT_SIZE is the length in bytes of an addressable unit.
8303 Return the transferred status, error or OK (an
8304 'enum target_xfer_status' value). Save the number of bytes
8305 transferred in *XFERED_LEN_UNITS.
8307 See the comment of remote_write_bytes_aux for an example of
8308 memory read/write exchange between gdb and the stub. */
8310 static enum target_xfer_status
8311 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8312 int unit_size, ULONGEST *xfered_len_units)
8314 struct remote_state *rs = get_remote_state ();
8315 int buf_size_bytes; /* Max size of packet output buffer. */
8320 buf_size_bytes = get_memory_read_packet_size ();
8321 /* The packet buffer will be large enough for the payload;
8322 get_memory_packet_size ensures this. */
8324 /* Number of units that will fit. */
8325 todo_units = std::min (len_units,
8326 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8328 /* Construct "m"<memaddr>","<len>". */
8329 memaddr = remote_address_masked (memaddr);
8332 p += hexnumstr (p, (ULONGEST) memaddr);
8334 p += hexnumstr (p, (ULONGEST) todo_units);
8337 getpkt (&rs->buf, &rs->buf_size, 0);
8338 if (rs->buf[0] == 'E'
8339 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8340 && rs->buf[3] == '\0')
8341 return TARGET_XFER_E_IO;
8342 /* Reply describes memory byte by byte, each byte encoded as two hex
8345 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8346 /* Return what we have. Let higher layers handle partial reads. */
8347 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8348 return TARGET_XFER_OK;
8351 /* Using the set of read-only target sections of remote, read live
8354 For interface/parameters/return description see target.h,
8357 static enum target_xfer_status
8358 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8359 ULONGEST memaddr, ULONGEST len,
8360 int unit_size, ULONGEST *xfered_len)
8362 struct target_section *secp;
8363 struct target_section_table *table;
8365 secp = target_section_by_addr (ops, memaddr);
8367 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8368 secp->the_bfd_section)
8371 struct target_section *p;
8372 ULONGEST memend = memaddr + len;
8374 table = target_get_section_table (ops);
8376 for (p = table->sections; p < table->sections_end; p++)
8378 if (memaddr >= p->addr)
8380 if (memend <= p->endaddr)
8382 /* Entire transfer is within this section. */
8383 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8386 else if (memaddr >= p->endaddr)
8388 /* This section ends before the transfer starts. */
8393 /* This section overlaps the transfer. Just do half. */
8394 len = p->endaddr - memaddr;
8395 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8402 return TARGET_XFER_EOF;
8405 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8406 first if the requested memory is unavailable in traceframe.
8407 Otherwise, fall back to remote_read_bytes_1. */
8409 static enum target_xfer_status
8410 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8411 gdb_byte *myaddr, ULONGEST len, int unit_size,
8412 ULONGEST *xfered_len)
8415 return TARGET_XFER_EOF;
8417 if (get_traceframe_number () != -1)
8419 VEC(mem_range_s) *available;
8421 /* If we fail to get the set of available memory, then the
8422 target does not support querying traceframe info, and so we
8423 attempt reading from the traceframe anyway (assuming the
8424 target implements the old QTro packet then). */
8425 if (traceframe_available_memory (&available, memaddr, len))
8427 struct cleanup *old_chain;
8429 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8431 if (VEC_empty (mem_range_s, available)
8432 || VEC_index (mem_range_s, available, 0)->start != memaddr)
8434 enum target_xfer_status res;
8436 /* Don't read into the traceframe's available
8438 if (!VEC_empty (mem_range_s, available))
8440 LONGEST oldlen = len;
8442 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8443 gdb_assert (len <= oldlen);
8446 do_cleanups (old_chain);
8448 /* This goes through the topmost target again. */
8449 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8450 len, unit_size, xfered_len);
8451 if (res == TARGET_XFER_OK)
8452 return TARGET_XFER_OK;
8455 /* No use trying further, we know some memory starting
8456 at MEMADDR isn't available. */
8458 return TARGET_XFER_UNAVAILABLE;
8462 /* Don't try to read more than how much is available, in
8463 case the target implements the deprecated QTro packet to
8464 cater for older GDBs (the target's knowledge of read-only
8465 sections may be outdated by now). */
8466 len = VEC_index (mem_range_s, available, 0)->length;
8468 do_cleanups (old_chain);
8472 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8477 /* Sends a packet with content determined by the printf format string
8478 FORMAT and the remaining arguments, then gets the reply. Returns
8479 whether the packet was a success, a failure, or unknown. */
8481 static enum packet_result remote_send_printf (const char *format, ...)
8482 ATTRIBUTE_PRINTF (1, 2);
8484 static enum packet_result
8485 remote_send_printf (const char *format, ...)
8487 struct remote_state *rs = get_remote_state ();
8488 int max_size = get_remote_packet_size ();
8491 va_start (ap, format);
8494 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8495 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8497 if (putpkt (rs->buf) < 0)
8498 error (_("Communication problem with target."));
8501 getpkt (&rs->buf, &rs->buf_size, 0);
8503 return packet_check_result (rs->buf);
8506 /* Flash writing can take quite some time. We'll set
8507 effectively infinite timeout for flash operations.
8508 In future, we'll need to decide on a better approach. */
8509 static const int remote_flash_timeout = 1000;
8512 remote_flash_erase (struct target_ops *ops,
8513 ULONGEST address, LONGEST length)
8515 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8516 enum packet_result ret;
8517 scoped_restore restore_timeout
8518 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8520 ret = remote_send_printf ("vFlashErase:%s,%s",
8521 phex (address, addr_size),
8525 case PACKET_UNKNOWN:
8526 error (_("Remote target does not support flash erase"));
8528 error (_("Error erasing flash with vFlashErase packet"));
8534 static enum target_xfer_status
8535 remote_flash_write (struct target_ops *ops, ULONGEST address,
8536 ULONGEST length, ULONGEST *xfered_len,
8537 const gdb_byte *data)
8539 scoped_restore restore_timeout
8540 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8541 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8546 remote_flash_done (struct target_ops *ops)
8550 scoped_restore restore_timeout
8551 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8553 ret = remote_send_printf ("vFlashDone");
8557 case PACKET_UNKNOWN:
8558 error (_("Remote target does not support vFlashDone"));
8560 error (_("Error finishing flash operation"));
8567 remote_files_info (struct target_ops *ignore)
8569 puts_filtered ("Debugging a target over a serial line.\n");
8572 /* Stuff for dealing with the packets which are part of this protocol.
8573 See comment at top of file for details. */
8575 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8576 error to higher layers. Called when a serial error is detected.
8577 The exception message is STRING, followed by a colon and a blank,
8578 the system error message for errno at function entry and final dot
8579 for output compatibility with throw_perror_with_name. */
8582 unpush_and_perror (const char *string)
8584 int saved_errno = errno;
8586 remote_unpush_target ();
8587 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8588 safe_strerror (saved_errno));
8591 /* Read a single character from the remote end. The current quit
8592 handler is overridden to avoid quitting in the middle of packet
8593 sequence, as that would break communication with the remote server.
8594 See remote_serial_quit_handler for more detail. */
8597 readchar (int timeout)
8600 struct remote_state *rs = get_remote_state ();
8603 scoped_restore restore_quit
8604 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8606 rs->got_ctrlc_during_io = 0;
8608 ch = serial_readchar (rs->remote_desc, timeout);
8610 if (rs->got_ctrlc_during_io)
8617 switch ((enum serial_rc) ch)
8620 remote_unpush_target ();
8621 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8624 unpush_and_perror (_("Remote communication error. "
8625 "Target disconnected."));
8627 case SERIAL_TIMEOUT:
8633 /* Wrapper for serial_write that closes the target and throws if
8634 writing fails. The current quit handler is overridden to avoid
8635 quitting in the middle of packet sequence, as that would break
8636 communication with the remote server. See
8637 remote_serial_quit_handler for more detail. */
8640 remote_serial_write (const char *str, int len)
8642 struct remote_state *rs = get_remote_state ();
8644 scoped_restore restore_quit
8645 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8647 rs->got_ctrlc_during_io = 0;
8649 if (serial_write (rs->remote_desc, str, len))
8651 unpush_and_perror (_("Remote communication error. "
8652 "Target disconnected."));
8655 if (rs->got_ctrlc_during_io)
8659 /* Send the command in *BUF to the remote machine, and read the reply
8660 into *BUF. Report an error if we get an error reply. Resize
8661 *BUF using xrealloc if necessary to hold the result, and update
8665 remote_send (char **buf,
8669 getpkt (buf, sizeof_buf, 0);
8671 if ((*buf)[0] == 'E')
8672 error (_("Remote failure reply: %s"), *buf);
8675 /* Return a string representing an escaped version of BUF, of len N.
8676 E.g. \n is converted to \\n, \t to \\t, etc. */
8679 escape_buffer (const char *buf, int n)
8683 stb.putstrn (buf, n, '\\');
8684 return std::move (stb.string ());
8687 /* Display a null-terminated packet on stdout, for debugging, using C
8691 print_packet (const char *buf)
8693 puts_filtered ("\"");
8694 fputstr_filtered (buf, '"', gdb_stdout);
8695 puts_filtered ("\"");
8699 putpkt (const char *buf)
8701 return putpkt_binary (buf, strlen (buf));
8704 /* Send a packet to the remote machine, with error checking. The data
8705 of the packet is in BUF. The string in BUF can be at most
8706 get_remote_packet_size () - 5 to account for the $, # and checksum,
8707 and for a possible /0 if we are debugging (remote_debug) and want
8708 to print the sent packet as a string. */
8711 putpkt_binary (const char *buf, int cnt)
8713 struct remote_state *rs = get_remote_state ();
8715 unsigned char csum = 0;
8716 char *buf2 = (char *) xmalloc (cnt + 6);
8717 struct cleanup *old_chain = make_cleanup (xfree, buf2);
8723 /* Catch cases like trying to read memory or listing threads while
8724 we're waiting for a stop reply. The remote server wouldn't be
8725 ready to handle this request, so we'd hang and timeout. We don't
8726 have to worry about this in synchronous mode, because in that
8727 case it's not possible to issue a command while the target is
8728 running. This is not a problem in non-stop mode, because in that
8729 case, the stub is always ready to process serial input. */
8730 if (!target_is_non_stop_p ()
8731 && target_is_async_p ()
8732 && rs->waiting_for_stop_reply)
8734 error (_("Cannot execute this command while the target is running.\n"
8735 "Use the \"interrupt\" command to stop the target\n"
8736 "and then try again."));
8739 /* We're sending out a new packet. Make sure we don't look at a
8740 stale cached response. */
8741 rs->cached_wait_status = 0;
8743 /* Copy the packet into buffer BUF2, encapsulating it
8744 and giving it a checksum. */
8749 for (i = 0; i < cnt; i++)
8755 *p++ = tohex ((csum >> 4) & 0xf);
8756 *p++ = tohex (csum & 0xf);
8758 /* Send it over and over until we get a positive ack. */
8762 int started_error_output = 0;
8768 int len = (int) (p - buf2);
8771 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8773 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8775 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
8777 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
8778 str.length () - REMOTE_DEBUG_MAX_CHAR);
8781 fprintf_unfiltered (gdb_stdlog, "...");
8783 gdb_flush (gdb_stdlog);
8785 remote_serial_write (buf2, p - buf2);
8787 /* If this is a no acks version of the remote protocol, send the
8788 packet and move on. */
8792 /* Read until either a timeout occurs (-2) or '+' is read.
8793 Handle any notification that arrives in the mean time. */
8796 ch = readchar (remote_timeout);
8804 case SERIAL_TIMEOUT:
8807 if (started_error_output)
8809 putchar_unfiltered ('\n');
8810 started_error_output = 0;
8819 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8820 do_cleanups (old_chain);
8824 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8826 case SERIAL_TIMEOUT:
8830 do_cleanups (old_chain);
8833 break; /* Retransmit buffer. */
8837 fprintf_unfiltered (gdb_stdlog,
8838 "Packet instead of Ack, ignoring it\n");
8839 /* It's probably an old response sent because an ACK
8840 was lost. Gobble up the packet and ack it so it
8841 doesn't get retransmitted when we resend this
8844 remote_serial_write ("+", 1);
8845 continue; /* Now, go look for +. */
8852 /* If we got a notification, handle it, and go back to looking
8854 /* We've found the start of a notification. Now
8855 collect the data. */
8856 val = read_frame (&rs->buf, &rs->buf_size);
8861 std::string str = escape_buffer (rs->buf, val);
8863 fprintf_unfiltered (gdb_stdlog,
8864 " Notification received: %s\n",
8867 handle_notification (rs->notif_state, rs->buf);
8868 /* We're in sync now, rewait for the ack. */
8875 if (!started_error_output)
8877 started_error_output = 1;
8878 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8880 fputc_unfiltered (ch & 0177, gdb_stdlog);
8881 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8890 if (!started_error_output)
8892 started_error_output = 1;
8893 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8895 fputc_unfiltered (ch & 0177, gdb_stdlog);
8899 break; /* Here to retransmit. */
8903 /* This is wrong. If doing a long backtrace, the user should be
8904 able to get out next time we call QUIT, without anything as
8905 violent as interrupt_query. If we want to provide a way out of
8906 here without getting to the next QUIT, it should be based on
8907 hitting ^C twice as in remote_wait. */
8916 do_cleanups (old_chain);
8920 /* Come here after finding the start of a frame when we expected an
8921 ack. Do our best to discard the rest of this packet. */
8930 c = readchar (remote_timeout);
8933 case SERIAL_TIMEOUT:
8934 /* Nothing we can do. */
8937 /* Discard the two bytes of checksum and stop. */
8938 c = readchar (remote_timeout);
8940 c = readchar (remote_timeout);
8943 case '*': /* Run length encoding. */
8944 /* Discard the repeat count. */
8945 c = readchar (remote_timeout);
8950 /* A regular character. */
8956 /* Come here after finding the start of the frame. Collect the rest
8957 into *BUF, verifying the checksum, length, and handling run-length
8958 compression. NUL terminate the buffer. If there is not enough room,
8959 expand *BUF using xrealloc.
8961 Returns -1 on error, number of characters in buffer (ignoring the
8962 trailing NULL) on success. (could be extended to return one of the
8963 SERIAL status indications). */
8966 read_frame (char **buf_p,
8973 struct remote_state *rs = get_remote_state ();
8980 c = readchar (remote_timeout);
8983 case SERIAL_TIMEOUT:
8985 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8989 fputs_filtered ("Saw new packet start in middle of old one\n",
8991 return -1; /* Start a new packet, count retries. */
8994 unsigned char pktcsum;
9000 check_0 = readchar (remote_timeout);
9002 check_1 = readchar (remote_timeout);
9004 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9007 fputs_filtered ("Timeout in checksum, retrying\n",
9011 else if (check_0 < 0 || check_1 < 0)
9014 fputs_filtered ("Communication error in checksum\n",
9019 /* Don't recompute the checksum; with no ack packets we
9020 don't have any way to indicate a packet retransmission
9025 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9026 if (csum == pktcsum)
9031 std::string str = escape_buffer (buf, bc);
9033 fprintf_unfiltered (gdb_stdlog,
9034 "Bad checksum, sentsum=0x%x, "
9035 "csum=0x%x, buf=%s\n",
9036 pktcsum, csum, str.c_str ());
9038 /* Number of characters in buffer ignoring trailing
9042 case '*': /* Run length encoding. */
9047 c = readchar (remote_timeout);
9049 repeat = c - ' ' + 3; /* Compute repeat count. */
9051 /* The character before ``*'' is repeated. */
9053 if (repeat > 0 && repeat <= 255 && bc > 0)
9055 if (bc + repeat - 1 >= *sizeof_buf - 1)
9057 /* Make some more room in the buffer. */
9058 *sizeof_buf += repeat;
9059 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9063 memset (&buf[bc], buf[bc - 1], repeat);
9069 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9073 if (bc >= *sizeof_buf - 1)
9075 /* Make some more room in the buffer. */
9077 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9088 /* Read a packet from the remote machine, with error checking, and
9089 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9090 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9091 rather than timing out; this is used (in synchronous mode) to wait
9092 for a target that is is executing user code to stop. */
9093 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9094 don't have to change all the calls to getpkt to deal with the
9095 return value, because at the moment I don't know what the right
9096 thing to do it for those. */
9102 getpkt_sane (buf, sizeof_buf, forever);
9106 /* Read a packet from the remote machine, with error checking, and
9107 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9108 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9109 rather than timing out; this is used (in synchronous mode) to wait
9110 for a target that is is executing user code to stop. If FOREVER ==
9111 0, this function is allowed to time out gracefully and return an
9112 indication of this to the caller. Otherwise return the number of
9113 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9114 enough reason to return to the caller. *IS_NOTIF is an output
9115 boolean that indicates whether *BUF holds a notification or not
9116 (a regular packet). */
9119 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9120 int expecting_notif, int *is_notif)
9122 struct remote_state *rs = get_remote_state ();
9128 /* We're reading a new response. Make sure we don't look at a
9129 previously cached response. */
9130 rs->cached_wait_status = 0;
9132 strcpy (*buf, "timeout");
9135 timeout = watchdog > 0 ? watchdog : -1;
9136 else if (expecting_notif)
9137 timeout = 0; /* There should already be a char in the buffer. If
9140 timeout = remote_timeout;
9144 /* Process any number of notifications, and then return when
9148 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9150 for (tries = 1; tries <= MAX_TRIES; tries++)
9152 /* This can loop forever if the remote side sends us
9153 characters continuously, but if it pauses, we'll get
9154 SERIAL_TIMEOUT from readchar because of timeout. Then
9155 we'll count that as a retry.
9157 Note that even when forever is set, we will only wait
9158 forever prior to the start of a packet. After that, we
9159 expect characters to arrive at a brisk pace. They should
9160 show up within remote_timeout intervals. */
9162 c = readchar (timeout);
9163 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9165 if (c == SERIAL_TIMEOUT)
9167 if (expecting_notif)
9168 return -1; /* Don't complain, it's normal to not get
9169 anything in this case. */
9171 if (forever) /* Watchdog went off? Kill the target. */
9173 remote_unpush_target ();
9174 throw_error (TARGET_CLOSE_ERROR,
9175 _("Watchdog timeout has expired. "
9176 "Target detached."));
9179 fputs_filtered ("Timed out.\n", gdb_stdlog);
9183 /* We've found the start of a packet or notification.
9184 Now collect the data. */
9185 val = read_frame (buf, sizeof_buf);
9190 remote_serial_write ("-", 1);
9193 if (tries > MAX_TRIES)
9195 /* We have tried hard enough, and just can't receive the
9196 packet/notification. Give up. */
9197 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9199 /* Skip the ack char if we're in no-ack mode. */
9200 if (!rs->noack_mode)
9201 remote_serial_write ("+", 1);
9205 /* If we got an ordinary packet, return that to our caller. */
9211 = escape_buffer (*buf,
9212 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9214 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9217 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
9219 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
9220 str.length () - REMOTE_DEBUG_MAX_CHAR);
9223 fprintf_unfiltered (gdb_stdlog, "\n");
9226 /* Skip the ack char if we're in no-ack mode. */
9227 if (!rs->noack_mode)
9228 remote_serial_write ("+", 1);
9229 if (is_notif != NULL)
9234 /* If we got a notification, handle it, and go back to looking
9238 gdb_assert (c == '%');
9242 std::string str = escape_buffer (*buf, val);
9244 fprintf_unfiltered (gdb_stdlog,
9245 " Notification received: %s\n",
9248 if (is_notif != NULL)
9251 handle_notification (rs->notif_state, *buf);
9253 /* Notifications require no acknowledgement. */
9255 if (expecting_notif)
9262 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9264 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9268 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9271 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9275 /* Check whether EVENT is a fork event for the process specified
9276 by the pid passed in DATA, and if it is, kill the fork child. */
9279 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9280 QUEUE_ITER (stop_reply_p) *iter,
9284 struct queue_iter_param *param = (struct queue_iter_param *) data;
9285 int parent_pid = *(int *) param->input;
9287 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9289 struct remote_state *rs = get_remote_state ();
9290 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9293 res = remote_vkill (child_pid, rs);
9295 error (_("Can't kill fork child process %d"), child_pid);
9301 /* Kill any new fork children of process PID that haven't been
9302 processed by follow_fork. */
9305 kill_new_fork_children (int pid, struct remote_state *rs)
9307 struct thread_info *thread;
9308 struct notif_client *notif = ¬if_client_stop;
9309 struct queue_iter_param param;
9311 /* Kill the fork child threads of any threads in process PID
9312 that are stopped at a fork event. */
9313 ALL_NON_EXITED_THREADS (thread)
9315 struct target_waitstatus *ws = &thread->pending_follow;
9317 if (is_pending_fork_parent (ws, pid, thread->ptid))
9319 struct remote_state *rs = get_remote_state ();
9320 int child_pid = ptid_get_pid (ws->value.related_pid);
9323 res = remote_vkill (child_pid, rs);
9325 error (_("Can't kill fork child process %d"), child_pid);
9329 /* Check for any pending fork events (not reported or processed yet)
9330 in process PID and kill those fork child threads as well. */
9331 remote_notif_get_pending_events (notif);
9333 param.output = NULL;
9334 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9335 kill_child_of_pending_fork, ¶m);
9339 /* Target hook to kill the current inferior. */
9342 remote_kill (struct target_ops *ops)
9345 int pid = ptid_get_pid (inferior_ptid);
9346 struct remote_state *rs = get_remote_state ();
9348 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9350 /* If we're stopped while forking and we haven't followed yet,
9351 kill the child task. We need to do this before killing the
9352 parent task because if this is a vfork then the parent will
9354 kill_new_fork_children (pid, rs);
9356 res = remote_vkill (pid, rs);
9359 target_mourn_inferior (inferior_ptid);
9364 /* If we are in 'target remote' mode and we are killing the only
9365 inferior, then we will tell gdbserver to exit and unpush the
9367 if (res == -1 && !remote_multi_process_p (rs)
9368 && number_of_live_inferiors () == 1)
9372 /* We've killed the remote end, we get to mourn it. If we are
9373 not in extended mode, mourning the inferior also unpushes
9374 remote_ops from the target stack, which closes the remote
9376 target_mourn_inferior (inferior_ptid);
9381 error (_("Can't kill process"));
9384 /* Send a kill request to the target using the 'vKill' packet. */
9387 remote_vkill (int pid, struct remote_state *rs)
9389 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9392 /* Tell the remote target to detach. */
9393 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9395 getpkt (&rs->buf, &rs->buf_size, 0);
9397 switch (packet_ok (rs->buf,
9398 &remote_protocol_packets[PACKET_vKill]))
9404 case PACKET_UNKNOWN:
9407 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9411 /* Send a kill request to the target using the 'k' packet. */
9414 remote_kill_k (void)
9416 /* Catch errors so the user can quit from gdb even when we
9417 aren't on speaking terms with the remote system. */
9422 CATCH (ex, RETURN_MASK_ERROR)
9424 if (ex.error == TARGET_CLOSE_ERROR)
9426 /* If we got an (EOF) error that caused the target
9427 to go away, then we're done, that's what we wanted.
9428 "k" is susceptible to cause a premature EOF, given
9429 that the remote server isn't actually required to
9430 reply to "k", and it can happen that it doesn't
9431 even get to reply ACK to the "k". */
9435 /* Otherwise, something went wrong. We didn't actually kill
9436 the target. Just propagate the exception, and let the
9437 user or higher layers decide what to do. */
9438 throw_exception (ex);
9444 remote_mourn (struct target_ops *target)
9446 struct remote_state *rs = get_remote_state ();
9448 /* In 'target remote' mode with one inferior, we close the connection. */
9449 if (!rs->extended && number_of_live_inferiors () <= 1)
9451 unpush_target (target);
9453 /* remote_close takes care of doing most of the clean up. */
9454 generic_mourn_inferior ();
9458 /* In case we got here due to an error, but we're going to stay
9460 rs->waiting_for_stop_reply = 0;
9462 /* If the current general thread belonged to the process we just
9463 detached from or has exited, the remote side current general
9464 thread becomes undefined. Considering a case like this:
9466 - We just got here due to a detach.
9467 - The process that we're detaching from happens to immediately
9468 report a global breakpoint being hit in non-stop mode, in the
9469 same thread we had selected before.
9470 - GDB attaches to this process again.
9471 - This event happens to be the next event we handle.
9473 GDB would consider that the current general thread didn't need to
9474 be set on the stub side (with Hg), since for all it knew,
9475 GENERAL_THREAD hadn't changed.
9477 Notice that although in all-stop mode, the remote server always
9478 sets the current thread to the thread reporting the stop event,
9479 that doesn't happen in non-stop mode; in non-stop, the stub *must
9480 not* change the current thread when reporting a breakpoint hit,
9481 due to the decoupling of event reporting and event handling.
9483 To keep things simple, we always invalidate our notion of the
9485 record_currthread (rs, minus_one_ptid);
9487 /* Call common code to mark the inferior as not running. */
9488 generic_mourn_inferior ();
9490 if (!have_inferiors ())
9492 if (!remote_multi_process_p (rs))
9494 /* Check whether the target is running now - some remote stubs
9495 automatically restart after kill. */
9497 getpkt (&rs->buf, &rs->buf_size, 0);
9499 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9501 /* Assume that the target has been restarted. Set
9502 inferior_ptid so that bits of core GDB realizes
9503 there's something here, e.g., so that the user can
9504 say "kill" again. */
9505 inferior_ptid = magic_null_ptid;
9512 extended_remote_supports_disable_randomization (struct target_ops *self)
9514 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9518 extended_remote_disable_randomization (int val)
9520 struct remote_state *rs = get_remote_state ();
9523 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9526 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9528 error (_("Target does not support QDisableRandomization."));
9529 if (strcmp (reply, "OK") != 0)
9530 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9534 extended_remote_run (const std::string &args)
9536 struct remote_state *rs = get_remote_state ();
9538 const char *remote_exec_file = get_remote_exec_file ();
9540 /* If the user has disabled vRun support, or we have detected that
9541 support is not available, do not try it. */
9542 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9545 strcpy (rs->buf, "vRun;");
9546 len = strlen (rs->buf);
9548 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9549 error (_("Remote file name too long for run packet"));
9550 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9551 strlen (remote_exec_file));
9557 gdb_argv argv (args.c_str ());
9558 for (i = 0; argv[i] != NULL; i++)
9560 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9561 error (_("Argument list too long for run packet"));
9562 rs->buf[len++] = ';';
9563 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9568 rs->buf[len++] = '\0';
9571 getpkt (&rs->buf, &rs->buf_size, 0);
9573 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9576 /* We have a wait response. All is well. */
9578 case PACKET_UNKNOWN:
9581 if (remote_exec_file[0] == '\0')
9582 error (_("Running the default executable on the remote target failed; "
9583 "try \"set remote exec-file\"?"));
9585 error (_("Running \"%s\" on the remote target failed"),
9588 gdb_assert_not_reached (_("bad switch"));
9592 /* Helper function to send set/unset environment packets. ACTION is
9593 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9594 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9598 send_environment_packet (struct remote_state *rs,
9603 /* Convert the environment variable to an hex string, which
9604 is the best format to be transmitted over the wire. */
9605 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9608 xsnprintf (rs->buf, get_remote_packet_size (),
9609 "%s:%s", packet, encoded_value.c_str ());
9612 getpkt (&rs->buf, &rs->buf_size, 0);
9613 if (strcmp (rs->buf, "OK") != 0)
9614 warning (_("Unable to %s environment variable '%s' on remote."),
9618 /* Helper function to handle the QEnvironment* packets. */
9621 extended_remote_environment_support (struct remote_state *rs)
9623 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9625 putpkt ("QEnvironmentReset");
9626 getpkt (&rs->buf, &rs->buf_size, 0);
9627 if (strcmp (rs->buf, "OK") != 0)
9628 warning (_("Unable to reset environment on remote."));
9631 gdb_environ *e = ¤t_inferior ()->environment;
9633 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9634 for (const std::string &el : e->user_set_env ())
9635 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9638 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9639 for (const std::string &el : e->user_unset_env ())
9640 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9643 /* In the extended protocol we want to be able to do things like
9644 "run" and have them basically work as expected. So we need
9645 a special create_inferior function. We support changing the
9646 executable file and the command line arguments, but not the
9650 extended_remote_create_inferior (struct target_ops *ops,
9651 const char *exec_file,
9652 const std::string &args,
9653 char **env, int from_tty)
9657 struct remote_state *rs = get_remote_state ();
9658 const char *remote_exec_file = get_remote_exec_file ();
9660 /* If running asynchronously, register the target file descriptor
9661 with the event loop. */
9662 if (target_can_async_p ())
9665 /* Disable address space randomization if requested (and supported). */
9666 if (extended_remote_supports_disable_randomization (ops))
9667 extended_remote_disable_randomization (disable_randomization);
9669 /* If startup-with-shell is on, we inform gdbserver to start the
9670 remote inferior using a shell. */
9671 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9673 xsnprintf (rs->buf, get_remote_packet_size (),
9674 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9676 getpkt (&rs->buf, &rs->buf_size, 0);
9677 if (strcmp (rs->buf, "OK") != 0)
9679 Remote replied unexpectedly while setting startup-with-shell: %s"),
9683 extended_remote_environment_support (rs);
9685 /* Now restart the remote server. */
9686 run_worked = extended_remote_run (args) != -1;
9689 /* vRun was not supported. Fail if we need it to do what the
9691 if (remote_exec_file[0])
9692 error (_("Remote target does not support \"set remote exec-file\""));
9694 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9696 /* Fall back to "R". */
9697 extended_remote_restart ();
9700 if (!have_inferiors ())
9702 /* Clean up from the last time we ran, before we mark the target
9703 running again. This will mark breakpoints uninserted, and
9704 get_offsets may insert breakpoints. */
9705 init_thread_list ();
9706 init_wait_for_inferior ();
9709 /* vRun's success return is a stop reply. */
9710 stop_reply = run_worked ? rs->buf : NULL;
9711 add_current_inferior_and_thread (stop_reply);
9713 /* Get updated offsets, if the stub uses qOffsets. */
9718 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9719 the list of conditions (in agent expression bytecode format), if any, the
9720 target needs to evaluate. The output is placed into the packet buffer
9721 started from BUF and ended at BUF_END. */
9724 remote_add_target_side_condition (struct gdbarch *gdbarch,
9725 struct bp_target_info *bp_tgt, char *buf,
9728 if (bp_tgt->conditions.empty ())
9731 buf += strlen (buf);
9732 xsnprintf (buf, buf_end - buf, "%s", ";");
9735 /* Send conditions to the target. */
9736 for (agent_expr *aexpr : bp_tgt->conditions)
9738 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9739 buf += strlen (buf);
9740 for (int i = 0; i < aexpr->len; ++i)
9741 buf = pack_hex_byte (buf, aexpr->buf[i]);
9748 remote_add_target_side_commands (struct gdbarch *gdbarch,
9749 struct bp_target_info *bp_tgt, char *buf)
9751 if (bp_tgt->tcommands.empty ())
9754 buf += strlen (buf);
9756 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9757 buf += strlen (buf);
9759 /* Concatenate all the agent expressions that are commands into the
9761 for (agent_expr *aexpr : bp_tgt->tcommands)
9763 sprintf (buf, "X%x,", aexpr->len);
9764 buf += strlen (buf);
9765 for (int i = 0; i < aexpr->len; ++i)
9766 buf = pack_hex_byte (buf, aexpr->buf[i]);
9771 /* Insert a breakpoint. On targets that have software breakpoint
9772 support, we ask the remote target to do the work; on targets
9773 which don't, we insert a traditional memory breakpoint. */
9776 remote_insert_breakpoint (struct target_ops *ops,
9777 struct gdbarch *gdbarch,
9778 struct bp_target_info *bp_tgt)
9780 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9781 If it succeeds, then set the support to PACKET_ENABLE. If it
9782 fails, and the user has explicitly requested the Z support then
9783 report an error, otherwise, mark it disabled and go on. */
9785 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9787 CORE_ADDR addr = bp_tgt->reqstd_address;
9788 struct remote_state *rs;
9792 /* Make sure the remote is pointing at the right process, if
9794 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9795 set_general_process ();
9797 rs = get_remote_state ();
9799 endbuf = rs->buf + get_remote_packet_size ();
9804 addr = (ULONGEST) remote_address_masked (addr);
9805 p += hexnumstr (p, addr);
9806 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9808 if (remote_supports_cond_breakpoints (ops))
9809 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9811 if (remote_can_run_breakpoint_commands (ops))
9812 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9815 getpkt (&rs->buf, &rs->buf_size, 0);
9817 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9823 case PACKET_UNKNOWN:
9828 /* If this breakpoint has target-side commands but this stub doesn't
9829 support Z0 packets, throw error. */
9830 if (!bp_tgt->tcommands.empty ())
9831 throw_error (NOT_SUPPORTED_ERROR, _("\
9832 Target doesn't support breakpoints that have target side commands."));
9834 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9838 remote_remove_breakpoint (struct target_ops *ops,
9839 struct gdbarch *gdbarch,
9840 struct bp_target_info *bp_tgt,
9841 enum remove_bp_reason reason)
9843 CORE_ADDR addr = bp_tgt->placed_address;
9844 struct remote_state *rs = get_remote_state ();
9846 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9849 char *endbuf = rs->buf + get_remote_packet_size ();
9851 /* Make sure the remote is pointing at the right process, if
9853 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9854 set_general_process ();
9860 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9861 p += hexnumstr (p, addr);
9862 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9865 getpkt (&rs->buf, &rs->buf_size, 0);
9867 return (rs->buf[0] == 'E');
9870 return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
9873 static enum Z_packet_type
9874 watchpoint_to_Z_packet (int type)
9879 return Z_PACKET_WRITE_WP;
9882 return Z_PACKET_READ_WP;
9885 return Z_PACKET_ACCESS_WP;
9888 internal_error (__FILE__, __LINE__,
9889 _("hw_bp_to_z: bad watchpoint type %d"), type);
9894 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9895 enum target_hw_bp_type type, struct expression *cond)
9897 struct remote_state *rs = get_remote_state ();
9898 char *endbuf = rs->buf + get_remote_packet_size ();
9900 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9902 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9905 /* Make sure the remote is pointing at the right process, if
9907 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9908 set_general_process ();
9910 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9911 p = strchr (rs->buf, '\0');
9912 addr = remote_address_masked (addr);
9913 p += hexnumstr (p, (ULONGEST) addr);
9914 xsnprintf (p, endbuf - p, ",%x", len);
9917 getpkt (&rs->buf, &rs->buf_size, 0);
9919 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9923 case PACKET_UNKNOWN:
9928 internal_error (__FILE__, __LINE__,
9929 _("remote_insert_watchpoint: reached end of function"));
9933 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9934 CORE_ADDR start, int length)
9936 CORE_ADDR diff = remote_address_masked (addr - start);
9938 return diff < length;
9943 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9944 enum target_hw_bp_type type, struct expression *cond)
9946 struct remote_state *rs = get_remote_state ();
9947 char *endbuf = rs->buf + get_remote_packet_size ();
9949 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9951 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9954 /* Make sure the remote is pointing at the right process, if
9956 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9957 set_general_process ();
9959 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9960 p = strchr (rs->buf, '\0');
9961 addr = remote_address_masked (addr);
9962 p += hexnumstr (p, (ULONGEST) addr);
9963 xsnprintf (p, endbuf - p, ",%x", len);
9965 getpkt (&rs->buf, &rs->buf_size, 0);
9967 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9970 case PACKET_UNKNOWN:
9975 internal_error (__FILE__, __LINE__,
9976 _("remote_remove_watchpoint: reached end of function"));
9980 int remote_hw_watchpoint_limit = -1;
9981 int remote_hw_watchpoint_length_limit = -1;
9982 int remote_hw_breakpoint_limit = -1;
9985 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9986 CORE_ADDR addr, int len)
9988 if (remote_hw_watchpoint_length_limit == 0)
9990 else if (remote_hw_watchpoint_length_limit < 0)
9992 else if (len <= remote_hw_watchpoint_length_limit)
9999 remote_check_watch_resources (struct target_ops *self,
10000 enum bptype type, int cnt, int ot)
10002 if (type == bp_hardware_breakpoint)
10004 if (remote_hw_breakpoint_limit == 0)
10006 else if (remote_hw_breakpoint_limit < 0)
10008 else if (cnt <= remote_hw_breakpoint_limit)
10013 if (remote_hw_watchpoint_limit == 0)
10015 else if (remote_hw_watchpoint_limit < 0)
10019 else if (cnt <= remote_hw_watchpoint_limit)
10025 /* The to_stopped_by_sw_breakpoint method of target remote. */
10028 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
10030 struct thread_info *thread = inferior_thread ();
10032 return (thread->priv != NULL
10033 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
10036 /* The to_supports_stopped_by_sw_breakpoint method of target
10040 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
10042 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10045 /* The to_stopped_by_hw_breakpoint method of target remote. */
10048 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
10050 struct thread_info *thread = inferior_thread ();
10052 return (thread->priv != NULL
10053 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
10056 /* The to_supports_stopped_by_hw_breakpoint method of target
10060 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
10062 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10066 remote_stopped_by_watchpoint (struct target_ops *ops)
10068 struct thread_info *thread = inferior_thread ();
10070 return (thread->priv != NULL
10071 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
10075 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
10077 struct thread_info *thread = inferior_thread ();
10079 if (thread->priv != NULL
10080 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
10082 *addr_p = thread->priv->watch_data_address;
10091 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10092 struct bp_target_info *bp_tgt)
10094 CORE_ADDR addr = bp_tgt->reqstd_address;
10095 struct remote_state *rs;
10099 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10102 /* Make sure the remote is pointing at the right process, if
10104 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10105 set_general_process ();
10107 rs = get_remote_state ();
10109 endbuf = rs->buf + get_remote_packet_size ();
10115 addr = remote_address_masked (addr);
10116 p += hexnumstr (p, (ULONGEST) addr);
10117 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10119 if (remote_supports_cond_breakpoints (self))
10120 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10122 if (remote_can_run_breakpoint_commands (self))
10123 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10126 getpkt (&rs->buf, &rs->buf_size, 0);
10128 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10131 if (rs->buf[1] == '.')
10133 message = strchr (rs->buf + 2, '.');
10135 error (_("Remote failure reply: %s"), message + 1);
10138 case PACKET_UNKNOWN:
10143 internal_error (__FILE__, __LINE__,
10144 _("remote_insert_hw_breakpoint: reached end of function"));
10149 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10150 struct bp_target_info *bp_tgt)
10153 struct remote_state *rs = get_remote_state ();
10155 char *endbuf = rs->buf + get_remote_packet_size ();
10157 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10160 /* Make sure the remote is pointing at the right process, if
10162 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10163 set_general_process ();
10169 addr = remote_address_masked (bp_tgt->placed_address);
10170 p += hexnumstr (p, (ULONGEST) addr);
10171 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10174 getpkt (&rs->buf, &rs->buf_size, 0);
10176 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10179 case PACKET_UNKNOWN:
10184 internal_error (__FILE__, __LINE__,
10185 _("remote_remove_hw_breakpoint: reached end of function"));
10188 /* Verify memory using the "qCRC:" request. */
10191 remote_verify_memory (struct target_ops *ops,
10192 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10194 struct remote_state *rs = get_remote_state ();
10195 unsigned long host_crc, target_crc;
10198 /* It doesn't make sense to use qCRC if the remote target is
10199 connected but not running. */
10200 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10202 enum packet_result result;
10204 /* Make sure the remote is pointing at the right process. */
10205 set_general_process ();
10207 /* FIXME: assumes lma can fit into long. */
10208 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10209 (long) lma, (long) size);
10212 /* Be clever; compute the host_crc before waiting for target
10214 host_crc = xcrc32 (data, size, 0xffffffff);
10216 getpkt (&rs->buf, &rs->buf_size, 0);
10218 result = packet_ok (rs->buf,
10219 &remote_protocol_packets[PACKET_qCRC]);
10220 if (result == PACKET_ERROR)
10222 else if (result == PACKET_OK)
10224 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10225 target_crc = target_crc * 16 + fromhex (*tmp);
10227 return (host_crc == target_crc);
10231 return simple_verify_memory (ops, data, lma, size);
10234 /* compare-sections command
10236 With no arguments, compares each loadable section in the exec bfd
10237 with the same memory range on the target, and reports mismatches.
10238 Useful for verifying the image on the target against the exec file. */
10241 compare_sections_command (const char *args, int from_tty)
10244 struct cleanup *old_chain;
10245 gdb_byte *sectdata;
10246 const char *sectname;
10247 bfd_size_type size;
10250 int mismatched = 0;
10255 error (_("command cannot be used without an exec file"));
10257 /* Make sure the remote is pointing at the right process. */
10258 set_general_process ();
10260 if (args != NULL && strcmp (args, "-r") == 0)
10266 for (s = exec_bfd->sections; s; s = s->next)
10268 if (!(s->flags & SEC_LOAD))
10269 continue; /* Skip non-loadable section. */
10271 if (read_only && (s->flags & SEC_READONLY) == 0)
10272 continue; /* Skip writeable sections */
10274 size = bfd_get_section_size (s);
10276 continue; /* Skip zero-length section. */
10278 sectname = bfd_get_section_name (exec_bfd, s);
10279 if (args && strcmp (args, sectname) != 0)
10280 continue; /* Not the section selected by user. */
10282 matched = 1; /* Do this section. */
10285 sectdata = (gdb_byte *) xmalloc (size);
10286 old_chain = make_cleanup (xfree, sectdata);
10287 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
10289 res = target_verify_memory (sectdata, lma, size);
10292 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10293 paddress (target_gdbarch (), lma),
10294 paddress (target_gdbarch (), lma + size));
10296 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10297 paddress (target_gdbarch (), lma),
10298 paddress (target_gdbarch (), lma + size));
10300 printf_filtered ("matched.\n");
10303 printf_filtered ("MIS-MATCHED!\n");
10307 do_cleanups (old_chain);
10309 if (mismatched > 0)
10310 warning (_("One or more sections of the target image does not match\n\
10311 the loaded file\n"));
10312 if (args && !matched)
10313 printf_filtered (_("No loaded section named '%s'.\n"), args);
10316 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10317 into remote target. The number of bytes written to the remote
10318 target is returned, or -1 for error. */
10320 static enum target_xfer_status
10321 remote_write_qxfer (struct target_ops *ops, const char *object_name,
10322 const char *annex, const gdb_byte *writebuf,
10323 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10324 struct packet_config *packet)
10328 struct remote_state *rs = get_remote_state ();
10329 int max_size = get_memory_write_packet_size ();
10331 if (packet->support == PACKET_DISABLE)
10332 return TARGET_XFER_E_IO;
10334 /* Insert header. */
10335 i = snprintf (rs->buf, max_size,
10336 "qXfer:%s:write:%s:%s:",
10337 object_name, annex ? annex : "",
10338 phex_nz (offset, sizeof offset));
10339 max_size -= (i + 1);
10341 /* Escape as much data as fits into rs->buf. */
10342 buf_len = remote_escape_output
10343 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10345 if (putpkt_binary (rs->buf, i + buf_len) < 0
10346 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10347 || packet_ok (rs->buf, packet) != PACKET_OK)
10348 return TARGET_XFER_E_IO;
10350 unpack_varlen_hex (rs->buf, &n);
10353 return TARGET_XFER_OK;
10356 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10357 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10358 number of bytes read is returned, or 0 for EOF, or -1 for error.
10359 The number of bytes read may be less than LEN without indicating an
10360 EOF. PACKET is checked and updated to indicate whether the remote
10361 target supports this object. */
10363 static enum target_xfer_status
10364 remote_read_qxfer (struct target_ops *ops, const char *object_name,
10366 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10367 ULONGEST *xfered_len,
10368 struct packet_config *packet)
10370 struct remote_state *rs = get_remote_state ();
10371 LONGEST i, n, packet_len;
10373 if (packet->support == PACKET_DISABLE)
10374 return TARGET_XFER_E_IO;
10376 /* Check whether we've cached an end-of-object packet that matches
10378 if (rs->finished_object)
10380 if (strcmp (object_name, rs->finished_object) == 0
10381 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10382 && offset == rs->finished_offset)
10383 return TARGET_XFER_EOF;
10386 /* Otherwise, we're now reading something different. Discard
10388 xfree (rs->finished_object);
10389 xfree (rs->finished_annex);
10390 rs->finished_object = NULL;
10391 rs->finished_annex = NULL;
10394 /* Request only enough to fit in a single packet. The actual data
10395 may not, since we don't know how much of it will need to be escaped;
10396 the target is free to respond with slightly less data. We subtract
10397 five to account for the response type and the protocol frame. */
10398 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10399 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10400 object_name, annex ? annex : "",
10401 phex_nz (offset, sizeof offset),
10402 phex_nz (n, sizeof n));
10403 i = putpkt (rs->buf);
10405 return TARGET_XFER_E_IO;
10408 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10409 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10410 return TARGET_XFER_E_IO;
10412 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10413 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10415 /* 'm' means there is (or at least might be) more data after this
10416 batch. That does not make sense unless there's at least one byte
10417 of data in this reply. */
10418 if (rs->buf[0] == 'm' && packet_len == 1)
10419 error (_("Remote qXfer reply contained no data."));
10421 /* Got some data. */
10422 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10423 packet_len - 1, readbuf, n);
10425 /* 'l' is an EOF marker, possibly including a final block of data,
10426 or possibly empty. If we have the final block of a non-empty
10427 object, record this fact to bypass a subsequent partial read. */
10428 if (rs->buf[0] == 'l' && offset + i > 0)
10430 rs->finished_object = xstrdup (object_name);
10431 rs->finished_annex = xstrdup (annex ? annex : "");
10432 rs->finished_offset = offset + i;
10436 return TARGET_XFER_EOF;
10440 return TARGET_XFER_OK;
10444 static enum target_xfer_status
10445 remote_xfer_partial (struct target_ops *ops, enum target_object object,
10446 const char *annex, gdb_byte *readbuf,
10447 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10448 ULONGEST *xfered_len)
10450 struct remote_state *rs;
10454 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10456 set_remote_traceframe ();
10457 set_general_thread (inferior_ptid);
10459 rs = get_remote_state ();
10461 /* Handle memory using the standard memory routines. */
10462 if (object == TARGET_OBJECT_MEMORY)
10464 /* If the remote target is connected but not running, we should
10465 pass this request down to a lower stratum (e.g. the executable
10467 if (!target_has_execution)
10468 return TARGET_XFER_EOF;
10470 if (writebuf != NULL)
10471 return remote_write_bytes (offset, writebuf, len, unit_size,
10474 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10478 /* Handle SPU memory using qxfer packets. */
10479 if (object == TARGET_OBJECT_SPU)
10482 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
10483 xfered_len, &remote_protocol_packets
10484 [PACKET_qXfer_spu_read]);
10486 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
10487 xfered_len, &remote_protocol_packets
10488 [PACKET_qXfer_spu_write]);
10491 /* Handle extra signal info using qxfer packets. */
10492 if (object == TARGET_OBJECT_SIGNAL_INFO)
10495 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10496 xfered_len, &remote_protocol_packets
10497 [PACKET_qXfer_siginfo_read]);
10499 return remote_write_qxfer (ops, "siginfo", annex,
10500 writebuf, offset, len, xfered_len,
10501 &remote_protocol_packets
10502 [PACKET_qXfer_siginfo_write]);
10505 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10508 return remote_read_qxfer (ops, "statictrace", annex,
10509 readbuf, offset, len, xfered_len,
10510 &remote_protocol_packets
10511 [PACKET_qXfer_statictrace_read]);
10513 return TARGET_XFER_E_IO;
10516 /* Only handle flash writes. */
10517 if (writebuf != NULL)
10521 case TARGET_OBJECT_FLASH:
10522 return remote_flash_write (ops, offset, len, xfered_len,
10526 return TARGET_XFER_E_IO;
10530 /* Map pre-existing objects onto letters. DO NOT do this for new
10531 objects!!! Instead specify new query packets. */
10534 case TARGET_OBJECT_AVR:
10538 case TARGET_OBJECT_AUXV:
10539 gdb_assert (annex == NULL);
10540 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10542 &remote_protocol_packets[PACKET_qXfer_auxv]);
10544 case TARGET_OBJECT_AVAILABLE_FEATURES:
10545 return remote_read_qxfer
10546 (ops, "features", annex, readbuf, offset, len, xfered_len,
10547 &remote_protocol_packets[PACKET_qXfer_features]);
10549 case TARGET_OBJECT_LIBRARIES:
10550 return remote_read_qxfer
10551 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10552 &remote_protocol_packets[PACKET_qXfer_libraries]);
10554 case TARGET_OBJECT_LIBRARIES_SVR4:
10555 return remote_read_qxfer
10556 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10557 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10559 case TARGET_OBJECT_MEMORY_MAP:
10560 gdb_assert (annex == NULL);
10561 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10563 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10565 case TARGET_OBJECT_OSDATA:
10566 /* Should only get here if we're connected. */
10567 gdb_assert (rs->remote_desc);
10568 return remote_read_qxfer
10569 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10570 &remote_protocol_packets[PACKET_qXfer_osdata]);
10572 case TARGET_OBJECT_THREADS:
10573 gdb_assert (annex == NULL);
10574 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10576 &remote_protocol_packets[PACKET_qXfer_threads]);
10578 case TARGET_OBJECT_TRACEFRAME_INFO:
10579 gdb_assert (annex == NULL);
10580 return remote_read_qxfer
10581 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10582 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10584 case TARGET_OBJECT_FDPIC:
10585 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10587 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10589 case TARGET_OBJECT_OPENVMS_UIB:
10590 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10592 &remote_protocol_packets[PACKET_qXfer_uib]);
10594 case TARGET_OBJECT_BTRACE:
10595 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10597 &remote_protocol_packets[PACKET_qXfer_btrace]);
10599 case TARGET_OBJECT_BTRACE_CONF:
10600 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10602 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10604 case TARGET_OBJECT_EXEC_FILE:
10605 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10607 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10610 return TARGET_XFER_E_IO;
10613 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10614 large enough let the caller deal with it. */
10615 if (len < get_remote_packet_size ())
10616 return TARGET_XFER_E_IO;
10617 len = get_remote_packet_size ();
10619 /* Except for querying the minimum buffer size, target must be open. */
10620 if (!rs->remote_desc)
10621 error (_("remote query is only available after target open"));
10623 gdb_assert (annex != NULL);
10624 gdb_assert (readbuf != NULL);
10628 *p2++ = query_type;
10630 /* We used one buffer char for the remote protocol q command and
10631 another for the query type. As the remote protocol encapsulation
10632 uses 4 chars plus one extra in case we are debugging
10633 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10636 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10638 /* Bad caller may have sent forbidden characters. */
10639 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10644 gdb_assert (annex[i] == '\0');
10646 i = putpkt (rs->buf);
10648 return TARGET_XFER_E_IO;
10650 getpkt (&rs->buf, &rs->buf_size, 0);
10651 strcpy ((char *) readbuf, rs->buf);
10653 *xfered_len = strlen ((char *) readbuf);
10654 return TARGET_XFER_OK;
10657 /* Implementation of to_get_memory_xfer_limit. */
10660 remote_get_memory_xfer_limit (struct target_ops *ops)
10662 return get_memory_write_packet_size ();
10666 remote_search_memory (struct target_ops* ops,
10667 CORE_ADDR start_addr, ULONGEST search_space_len,
10668 const gdb_byte *pattern, ULONGEST pattern_len,
10669 CORE_ADDR *found_addrp)
10671 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10672 struct remote_state *rs = get_remote_state ();
10673 int max_size = get_memory_write_packet_size ();
10674 struct packet_config *packet =
10675 &remote_protocol_packets[PACKET_qSearch_memory];
10676 /* Number of packet bytes used to encode the pattern;
10677 this could be more than PATTERN_LEN due to escape characters. */
10678 int escaped_pattern_len;
10679 /* Amount of pattern that was encodable in the packet. */
10680 int used_pattern_len;
10683 ULONGEST found_addr;
10685 /* Don't go to the target if we don't have to.
10686 This is done before checking packet->support to avoid the possibility that
10687 a success for this edge case means the facility works in general. */
10688 if (pattern_len > search_space_len)
10690 if (pattern_len == 0)
10692 *found_addrp = start_addr;
10696 /* If we already know the packet isn't supported, fall back to the simple
10697 way of searching memory. */
10699 if (packet_config_support (packet) == PACKET_DISABLE)
10701 /* Target doesn't provided special support, fall back and use the
10702 standard support (copy memory and do the search here). */
10703 return simple_search_memory (ops, start_addr, search_space_len,
10704 pattern, pattern_len, found_addrp);
10707 /* Make sure the remote is pointing at the right process. */
10708 set_general_process ();
10710 /* Insert header. */
10711 i = snprintf (rs->buf, max_size,
10712 "qSearch:memory:%s;%s;",
10713 phex_nz (start_addr, addr_size),
10714 phex_nz (search_space_len, sizeof (search_space_len)));
10715 max_size -= (i + 1);
10717 /* Escape as much data as fits into rs->buf. */
10718 escaped_pattern_len =
10719 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10720 &used_pattern_len, max_size);
10722 /* Bail if the pattern is too large. */
10723 if (used_pattern_len != pattern_len)
10724 error (_("Pattern is too large to transmit to remote target."));
10726 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10727 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10728 || packet_ok (rs->buf, packet) != PACKET_OK)
10730 /* The request may not have worked because the command is not
10731 supported. If so, fall back to the simple way. */
10732 if (packet->support == PACKET_DISABLE)
10734 return simple_search_memory (ops, start_addr, search_space_len,
10735 pattern, pattern_len, found_addrp);
10740 if (rs->buf[0] == '0')
10742 else if (rs->buf[0] == '1')
10745 if (rs->buf[1] != ',')
10746 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10747 unpack_varlen_hex (rs->buf + 2, &found_addr);
10748 *found_addrp = found_addr;
10751 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10757 remote_rcmd (struct target_ops *self, const char *command,
10758 struct ui_file *outbuf)
10760 struct remote_state *rs = get_remote_state ();
10763 if (!rs->remote_desc)
10764 error (_("remote rcmd is only available after target open"));
10766 /* Send a NULL command across as an empty command. */
10767 if (command == NULL)
10770 /* The query prefix. */
10771 strcpy (rs->buf, "qRcmd,");
10772 p = strchr (rs->buf, '\0');
10774 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10775 > get_remote_packet_size ())
10776 error (_("\"monitor\" command ``%s'' is too long."), command);
10778 /* Encode the actual command. */
10779 bin2hex ((const gdb_byte *) command, p, strlen (command));
10781 if (putpkt (rs->buf) < 0)
10782 error (_("Communication problem with target."));
10784 /* get/display the response */
10789 /* XXX - see also remote_get_noisy_reply(). */
10790 QUIT; /* Allow user to bail out with ^C. */
10792 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10794 /* Timeout. Continue to (try to) read responses.
10795 This is better than stopping with an error, assuming the stub
10796 is still executing the (long) monitor command.
10797 If needed, the user can interrupt gdb using C-c, obtaining
10798 an effect similar to stop on timeout. */
10802 if (buf[0] == '\0')
10803 error (_("Target does not support this command."));
10804 if (buf[0] == 'O' && buf[1] != 'K')
10806 remote_console_output (buf + 1); /* 'O' message from stub. */
10809 if (strcmp (buf, "OK") == 0)
10811 if (strlen (buf) == 3 && buf[0] == 'E'
10812 && isdigit (buf[1]) && isdigit (buf[2]))
10814 error (_("Protocol error with Rcmd"));
10816 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10818 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10820 fputc_unfiltered (c, outbuf);
10826 static VEC(mem_region_s) *
10827 remote_memory_map (struct target_ops *ops)
10829 VEC(mem_region_s) *result = NULL;
10830 char *text = target_read_stralloc (¤t_target,
10831 TARGET_OBJECT_MEMORY_MAP, NULL);
10835 struct cleanup *back_to = make_cleanup (xfree, text);
10837 result = parse_memory_map (text);
10838 do_cleanups (back_to);
10845 packet_command (const char *args, int from_tty)
10847 struct remote_state *rs = get_remote_state ();
10849 if (!rs->remote_desc)
10850 error (_("command can only be used with remote target"));
10853 error (_("remote-packet command requires packet text as argument"));
10855 puts_filtered ("sending: ");
10856 print_packet (args);
10857 puts_filtered ("\n");
10860 getpkt (&rs->buf, &rs->buf_size, 0);
10861 puts_filtered ("received: ");
10862 print_packet (rs->buf);
10863 puts_filtered ("\n");
10867 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10869 static void display_thread_info (struct gdb_ext_thread_info *info);
10871 static void threadset_test_cmd (char *cmd, int tty);
10873 static void threadalive_test (char *cmd, int tty);
10875 static void threadlist_test_cmd (char *cmd, int tty);
10877 int get_and_display_threadinfo (threadref *ref);
10879 static void threadinfo_test_cmd (char *cmd, int tty);
10881 static int thread_display_step (threadref *ref, void *context);
10883 static void threadlist_update_test_cmd (char *cmd, int tty);
10885 static void init_remote_threadtests (void);
10887 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
10890 threadset_test_cmd (char *cmd, int tty)
10892 int sample_thread = SAMPLE_THREAD;
10894 printf_filtered (_("Remote threadset test\n"));
10895 set_general_thread (sample_thread);
10900 threadalive_test (char *cmd, int tty)
10902 int sample_thread = SAMPLE_THREAD;
10903 int pid = ptid_get_pid (inferior_ptid);
10904 ptid_t ptid = ptid_build (pid, sample_thread, 0);
10906 if (remote_thread_alive (ptid))
10907 printf_filtered ("PASS: Thread alive test\n");
10909 printf_filtered ("FAIL: Thread alive test\n");
10912 void output_threadid (char *title, threadref *ref);
10915 output_threadid (char *title, threadref *ref)
10919 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
10921 printf_filtered ("%s %s\n", title, (&hexid[0]));
10925 threadlist_test_cmd (char *cmd, int tty)
10928 threadref nextthread;
10929 int done, result_count;
10930 threadref threadlist[3];
10932 printf_filtered ("Remote Threadlist test\n");
10933 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10934 &result_count, &threadlist[0]))
10935 printf_filtered ("FAIL: threadlist test\n");
10938 threadref *scan = threadlist;
10939 threadref *limit = scan + result_count;
10941 while (scan < limit)
10942 output_threadid (" thread ", scan++);
10947 display_thread_info (struct gdb_ext_thread_info *info)
10949 output_threadid ("Threadid: ", &info->threadid);
10950 printf_filtered ("Name: %s\n ", info->shortname);
10951 printf_filtered ("State: %s\n", info->display);
10952 printf_filtered ("other: %s\n\n", info->more_display);
10956 get_and_display_threadinfo (threadref *ref)
10960 struct gdb_ext_thread_info threadinfo;
10962 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10963 | TAG_MOREDISPLAY | TAG_DISPLAY;
10964 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10965 display_thread_info (&threadinfo);
10970 threadinfo_test_cmd (char *cmd, int tty)
10972 int athread = SAMPLE_THREAD;
10976 int_to_threadref (&thread, athread);
10977 printf_filtered ("Remote Threadinfo test\n");
10978 if (!get_and_display_threadinfo (&thread))
10979 printf_filtered ("FAIL cannot get thread info\n");
10983 thread_display_step (threadref *ref, void *context)
10985 /* output_threadid(" threadstep ",ref); *//* simple test */
10986 return get_and_display_threadinfo (ref);
10990 threadlist_update_test_cmd (char *cmd, int tty)
10992 printf_filtered ("Remote Threadlist update test\n");
10993 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10997 init_remote_threadtests (void)
10999 add_com ("tlist", class_obscure, threadlist_test_cmd,
11000 _("Fetch and print the remote list of "
11001 "thread identifiers, one pkt only"));
11002 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11003 _("Fetch and display info about one thread"));
11004 add_com ("tset", class_obscure, threadset_test_cmd,
11005 _("Test setting to a different thread"));
11006 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11007 _("Iterate through updating all remote thread info"));
11008 add_com ("talive", class_obscure, threadalive_test,
11009 _(" Remote thread alive test "));
11014 /* Convert a thread ID to a string. Returns the string in a static
11017 static const char *
11018 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
11020 static char buf[64];
11021 struct remote_state *rs = get_remote_state ();
11023 if (ptid_equal (ptid, null_ptid))
11024 return normal_pid_to_str (ptid);
11025 else if (ptid_is_pid (ptid))
11027 /* Printing an inferior target id. */
11029 /* When multi-process extensions are off, there's no way in the
11030 remote protocol to know the remote process id, if there's any
11031 at all. There's one exception --- when we're connected with
11032 target extended-remote, and we manually attached to a process
11033 with "attach PID". We don't record anywhere a flag that
11034 allows us to distinguish that case from the case of
11035 connecting with extended-remote and the stub already being
11036 attached to a process, and reporting yes to qAttached, hence
11037 no smart special casing here. */
11038 if (!remote_multi_process_p (rs))
11040 xsnprintf (buf, sizeof buf, "Remote target");
11044 return normal_pid_to_str (ptid);
11048 if (ptid_equal (magic_null_ptid, ptid))
11049 xsnprintf (buf, sizeof buf, "Thread <main>");
11050 else if (remote_multi_process_p (rs))
11051 if (ptid_get_lwp (ptid) == 0)
11052 return normal_pid_to_str (ptid);
11054 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11055 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11057 xsnprintf (buf, sizeof buf, "Thread %ld",
11058 ptid_get_lwp (ptid));
11063 /* Get the address of the thread local variable in OBJFILE which is
11064 stored at OFFSET within the thread local storage for thread PTID. */
11067 remote_get_thread_local_address (struct target_ops *ops,
11068 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
11070 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11072 struct remote_state *rs = get_remote_state ();
11074 char *endp = rs->buf + get_remote_packet_size ();
11075 enum packet_result result;
11077 strcpy (p, "qGetTLSAddr:");
11079 p = write_ptid (p, endp, ptid);
11081 p += hexnumstr (p, offset);
11083 p += hexnumstr (p, lm);
11087 getpkt (&rs->buf, &rs->buf_size, 0);
11088 result = packet_ok (rs->buf,
11089 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11090 if (result == PACKET_OK)
11094 unpack_varlen_hex (rs->buf, &result);
11097 else if (result == PACKET_UNKNOWN)
11098 throw_error (TLS_GENERIC_ERROR,
11099 _("Remote target doesn't support qGetTLSAddr packet"));
11101 throw_error (TLS_GENERIC_ERROR,
11102 _("Remote target failed to process qGetTLSAddr request"));
11105 throw_error (TLS_GENERIC_ERROR,
11106 _("TLS not supported or disabled on this target"));
11111 /* Provide thread local base, i.e. Thread Information Block address.
11112 Returns 1 if ptid is found and thread_local_base is non zero. */
11115 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
11117 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11119 struct remote_state *rs = get_remote_state ();
11121 char *endp = rs->buf + get_remote_packet_size ();
11122 enum packet_result result;
11124 strcpy (p, "qGetTIBAddr:");
11126 p = write_ptid (p, endp, ptid);
11130 getpkt (&rs->buf, &rs->buf_size, 0);
11131 result = packet_ok (rs->buf,
11132 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11133 if (result == PACKET_OK)
11137 unpack_varlen_hex (rs->buf, &result);
11139 *addr = (CORE_ADDR) result;
11142 else if (result == PACKET_UNKNOWN)
11143 error (_("Remote target doesn't support qGetTIBAddr packet"));
11145 error (_("Remote target failed to process qGetTIBAddr request"));
11148 error (_("qGetTIBAddr not supported or disabled on this target"));
11153 /* Support for inferring a target description based on the current
11154 architecture and the size of a 'g' packet. While the 'g' packet
11155 can have any size (since optional registers can be left off the
11156 end), some sizes are easily recognizable given knowledge of the
11157 approximate architecture. */
11159 struct remote_g_packet_guess
11162 const struct target_desc *tdesc;
11164 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11165 DEF_VEC_O(remote_g_packet_guess_s);
11167 struct remote_g_packet_data
11169 VEC(remote_g_packet_guess_s) *guesses;
11172 static struct gdbarch_data *remote_g_packet_data_handle;
11175 remote_g_packet_data_init (struct obstack *obstack)
11177 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11181 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11182 const struct target_desc *tdesc)
11184 struct remote_g_packet_data *data
11185 = ((struct remote_g_packet_data *)
11186 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11187 struct remote_g_packet_guess new_guess, *guess;
11190 gdb_assert (tdesc != NULL);
11193 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11195 if (guess->bytes == bytes)
11196 internal_error (__FILE__, __LINE__,
11197 _("Duplicate g packet description added for size %d"),
11200 new_guess.bytes = bytes;
11201 new_guess.tdesc = tdesc;
11202 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11205 /* Return 1 if remote_read_description would do anything on this target
11206 and architecture, 0 otherwise. */
11209 remote_read_description_p (struct target_ops *target)
11211 struct remote_g_packet_data *data
11212 = ((struct remote_g_packet_data *)
11213 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11215 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11221 static const struct target_desc *
11222 remote_read_description (struct target_ops *target)
11224 struct remote_g_packet_data *data
11225 = ((struct remote_g_packet_data *)
11226 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11228 /* Do not try this during initial connection, when we do not know
11229 whether there is a running but stopped thread. */
11230 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11231 return target->beneath->to_read_description (target->beneath);
11233 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11235 struct remote_g_packet_guess *guess;
11237 int bytes = send_g_packet ();
11240 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11242 if (guess->bytes == bytes)
11243 return guess->tdesc;
11245 /* We discard the g packet. A minor optimization would be to
11246 hold on to it, and fill the register cache once we have selected
11247 an architecture, but it's too tricky to do safely. */
11250 return target->beneath->to_read_description (target->beneath);
11253 /* Remote file transfer support. This is host-initiated I/O, not
11254 target-initiated; for target-initiated, see remote-fileio.c. */
11256 /* If *LEFT is at least the length of STRING, copy STRING to
11257 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11258 decrease *LEFT. Otherwise raise an error. */
11261 remote_buffer_add_string (char **buffer, int *left, const char *string)
11263 int len = strlen (string);
11266 error (_("Packet too long for target."));
11268 memcpy (*buffer, string, len);
11272 /* NUL-terminate the buffer as a convenience, if there is
11278 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11279 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11280 decrease *LEFT. Otherwise raise an error. */
11283 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11286 if (2 * len > *left)
11287 error (_("Packet too long for target."));
11289 bin2hex (bytes, *buffer, len);
11290 *buffer += 2 * len;
11293 /* NUL-terminate the buffer as a convenience, if there is
11299 /* If *LEFT is large enough, convert VALUE to hex and add it to
11300 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11301 decrease *LEFT. Otherwise raise an error. */
11304 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11306 int len = hexnumlen (value);
11309 error (_("Packet too long for target."));
11311 hexnumstr (*buffer, value);
11315 /* NUL-terminate the buffer as a convenience, if there is
11321 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11322 value, *REMOTE_ERRNO to the remote error number or zero if none
11323 was included, and *ATTACHMENT to point to the start of the annex
11324 if any. The length of the packet isn't needed here; there may
11325 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11327 Return 0 if the packet could be parsed, -1 if it could not. If
11328 -1 is returned, the other variables may not be initialized. */
11331 remote_hostio_parse_result (char *buffer, int *retcode,
11332 int *remote_errno, char **attachment)
11337 *attachment = NULL;
11339 if (buffer[0] != 'F')
11343 *retcode = strtol (&buffer[1], &p, 16);
11344 if (errno != 0 || p == &buffer[1])
11347 /* Check for ",errno". */
11351 *remote_errno = strtol (p + 1, &p2, 16);
11352 if (errno != 0 || p + 1 == p2)
11357 /* Check for ";attachment". If there is no attachment, the
11358 packet should end here. */
11361 *attachment = p + 1;
11364 else if (*p == '\0')
11370 /* Send a prepared I/O packet to the target and read its response.
11371 The prepared packet is in the global RS->BUF before this function
11372 is called, and the answer is there when we return.
11374 COMMAND_BYTES is the length of the request to send, which may include
11375 binary data. WHICH_PACKET is the packet configuration to check
11376 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11377 is set to the error number and -1 is returned. Otherwise the value
11378 returned by the function is returned.
11380 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11381 attachment is expected; an error will be reported if there's a
11382 mismatch. If one is found, *ATTACHMENT will be set to point into
11383 the packet buffer and *ATTACHMENT_LEN will be set to the
11384 attachment's length. */
11387 remote_hostio_send_command (int command_bytes, int which_packet,
11388 int *remote_errno, char **attachment,
11389 int *attachment_len)
11391 struct remote_state *rs = get_remote_state ();
11392 int ret, bytes_read;
11393 char *attachment_tmp;
11395 if (!rs->remote_desc
11396 || packet_support (which_packet) == PACKET_DISABLE)
11398 *remote_errno = FILEIO_ENOSYS;
11402 putpkt_binary (rs->buf, command_bytes);
11403 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11405 /* If it timed out, something is wrong. Don't try to parse the
11407 if (bytes_read < 0)
11409 *remote_errno = FILEIO_EINVAL;
11413 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11416 *remote_errno = FILEIO_EINVAL;
11418 case PACKET_UNKNOWN:
11419 *remote_errno = FILEIO_ENOSYS;
11425 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11428 *remote_errno = FILEIO_EINVAL;
11432 /* Make sure we saw an attachment if and only if we expected one. */
11433 if ((attachment_tmp == NULL && attachment != NULL)
11434 || (attachment_tmp != NULL && attachment == NULL))
11436 *remote_errno = FILEIO_EINVAL;
11440 /* If an attachment was found, it must point into the packet buffer;
11441 work out how many bytes there were. */
11442 if (attachment_tmp != NULL)
11444 *attachment = attachment_tmp;
11445 *attachment_len = bytes_read - (*attachment - rs->buf);
11451 /* Invalidate the readahead cache. */
11454 readahead_cache_invalidate (void)
11456 struct remote_state *rs = get_remote_state ();
11458 rs->readahead_cache.fd = -1;
11461 /* Invalidate the readahead cache if it is holding data for FD. */
11464 readahead_cache_invalidate_fd (int fd)
11466 struct remote_state *rs = get_remote_state ();
11468 if (rs->readahead_cache.fd == fd)
11469 rs->readahead_cache.fd = -1;
11472 /* Set the filesystem remote_hostio functions that take FILENAME
11473 arguments will use. Return 0 on success, or -1 if an error
11474 occurs (and set *REMOTE_ERRNO). */
11477 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11479 struct remote_state *rs = get_remote_state ();
11480 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11482 int left = get_remote_packet_size () - 1;
11486 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11489 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11492 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11494 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11495 remote_buffer_add_string (&p, &left, arg);
11497 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11498 remote_errno, NULL, NULL);
11500 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11504 rs->fs_pid = required_pid;
11509 /* Implementation of to_fileio_open. */
11512 remote_hostio_open (struct target_ops *self,
11513 struct inferior *inf, const char *filename,
11514 int flags, int mode, int warn_if_slow,
11517 struct remote_state *rs = get_remote_state ();
11519 int left = get_remote_packet_size () - 1;
11523 static int warning_issued = 0;
11525 printf_unfiltered (_("Reading %s from remote target...\n"),
11528 if (!warning_issued)
11530 warning (_("File transfers from remote targets can be slow."
11531 " Use \"set sysroot\" to access files locally"
11533 warning_issued = 1;
11537 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11540 remote_buffer_add_string (&p, &left, "vFile:open:");
11542 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11543 strlen (filename));
11544 remote_buffer_add_string (&p, &left, ",");
11546 remote_buffer_add_int (&p, &left, flags);
11547 remote_buffer_add_string (&p, &left, ",");
11549 remote_buffer_add_int (&p, &left, mode);
11551 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11552 remote_errno, NULL, NULL);
11555 /* Implementation of to_fileio_pwrite. */
11558 remote_hostio_pwrite (struct target_ops *self,
11559 int fd, const gdb_byte *write_buf, int len,
11560 ULONGEST offset, int *remote_errno)
11562 struct remote_state *rs = get_remote_state ();
11564 int left = get_remote_packet_size ();
11567 readahead_cache_invalidate_fd (fd);
11569 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11571 remote_buffer_add_int (&p, &left, fd);
11572 remote_buffer_add_string (&p, &left, ",");
11574 remote_buffer_add_int (&p, &left, offset);
11575 remote_buffer_add_string (&p, &left, ",");
11577 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11578 get_remote_packet_size () - (p - rs->buf));
11580 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11581 remote_errno, NULL, NULL);
11584 /* Helper for the implementation of to_fileio_pread. Read the file
11585 from the remote side with vFile:pread. */
11588 remote_hostio_pread_vFile (struct target_ops *self,
11589 int fd, gdb_byte *read_buf, int len,
11590 ULONGEST offset, int *remote_errno)
11592 struct remote_state *rs = get_remote_state ();
11595 int left = get_remote_packet_size ();
11596 int ret, attachment_len;
11599 remote_buffer_add_string (&p, &left, "vFile:pread:");
11601 remote_buffer_add_int (&p, &left, fd);
11602 remote_buffer_add_string (&p, &left, ",");
11604 remote_buffer_add_int (&p, &left, len);
11605 remote_buffer_add_string (&p, &left, ",");
11607 remote_buffer_add_int (&p, &left, offset);
11609 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11610 remote_errno, &attachment,
11616 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11618 if (read_len != ret)
11619 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11624 /* Serve pread from the readahead cache. Returns number of bytes
11625 read, or 0 if the request can't be served from the cache. */
11628 remote_hostio_pread_from_cache (struct remote_state *rs,
11629 int fd, gdb_byte *read_buf, size_t len,
11632 struct readahead_cache *cache = &rs->readahead_cache;
11634 if (cache->fd == fd
11635 && cache->offset <= offset
11636 && offset < cache->offset + cache->bufsize)
11638 ULONGEST max = cache->offset + cache->bufsize;
11640 if (offset + len > max)
11641 len = max - offset;
11643 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11650 /* Implementation of to_fileio_pread. */
11653 remote_hostio_pread (struct target_ops *self,
11654 int fd, gdb_byte *read_buf, int len,
11655 ULONGEST offset, int *remote_errno)
11658 struct remote_state *rs = get_remote_state ();
11659 struct readahead_cache *cache = &rs->readahead_cache;
11661 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11664 cache->hit_count++;
11667 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11668 pulongest (cache->hit_count));
11672 cache->miss_count++;
11674 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11675 pulongest (cache->miss_count));
11678 cache->offset = offset;
11679 cache->bufsize = get_remote_packet_size ();
11680 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11682 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11683 cache->offset, remote_errno);
11686 readahead_cache_invalidate_fd (fd);
11690 cache->bufsize = ret;
11691 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11694 /* Implementation of to_fileio_close. */
11697 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11699 struct remote_state *rs = get_remote_state ();
11701 int left = get_remote_packet_size () - 1;
11703 readahead_cache_invalidate_fd (fd);
11705 remote_buffer_add_string (&p, &left, "vFile:close:");
11707 remote_buffer_add_int (&p, &left, fd);
11709 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11710 remote_errno, NULL, NULL);
11713 /* Implementation of to_fileio_unlink. */
11716 remote_hostio_unlink (struct target_ops *self,
11717 struct inferior *inf, const char *filename,
11720 struct remote_state *rs = get_remote_state ();
11722 int left = get_remote_packet_size () - 1;
11724 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11727 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11729 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11730 strlen (filename));
11732 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11733 remote_errno, NULL, NULL);
11736 /* Implementation of to_fileio_readlink. */
11739 remote_hostio_readlink (struct target_ops *self,
11740 struct inferior *inf, const char *filename,
11743 struct remote_state *rs = get_remote_state ();
11746 int left = get_remote_packet_size ();
11747 int len, attachment_len;
11751 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11754 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11756 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11757 strlen (filename));
11759 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11760 remote_errno, &attachment,
11766 ret = (char *) xmalloc (len + 1);
11768 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11769 (gdb_byte *) ret, len);
11770 if (read_len != len)
11771 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11777 /* Implementation of to_fileio_fstat. */
11780 remote_hostio_fstat (struct target_ops *self,
11781 int fd, struct stat *st,
11784 struct remote_state *rs = get_remote_state ();
11786 int left = get_remote_packet_size ();
11787 int attachment_len, ret;
11789 struct fio_stat fst;
11792 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11794 remote_buffer_add_int (&p, &left, fd);
11796 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11797 remote_errno, &attachment,
11801 if (*remote_errno != FILEIO_ENOSYS)
11804 /* Strictly we should return -1, ENOSYS here, but when
11805 "set sysroot remote:" was implemented in August 2008
11806 BFD's need for a stat function was sidestepped with
11807 this hack. This was not remedied until March 2015
11808 so we retain the previous behavior to avoid breaking
11811 Note that the memset is a March 2015 addition; older
11812 GDBs set st_size *and nothing else* so the structure
11813 would have garbage in all other fields. This might
11814 break something but retaining the previous behavior
11815 here would be just too wrong. */
11817 memset (st, 0, sizeof (struct stat));
11818 st->st_size = INT_MAX;
11822 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11823 (gdb_byte *) &fst, sizeof (fst));
11825 if (read_len != ret)
11826 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11828 if (read_len != sizeof (fst))
11829 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11830 read_len, (int) sizeof (fst));
11832 remote_fileio_to_host_stat (&fst, st);
11837 /* Implementation of to_filesystem_is_local. */
11840 remote_filesystem_is_local (struct target_ops *self)
11842 /* Valgrind GDB presents itself as a remote target but works
11843 on the local filesystem: it does not implement remote get
11844 and users are not expected to set a sysroot. To handle
11845 this case we treat the remote filesystem as local if the
11846 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11847 does not support vFile:open. */
11848 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11850 enum packet_support ps = packet_support (PACKET_vFile_open);
11852 if (ps == PACKET_SUPPORT_UNKNOWN)
11854 int fd, remote_errno;
11856 /* Try opening a file to probe support. The supplied
11857 filename is irrelevant, we only care about whether
11858 the stub recognizes the packet or not. */
11859 fd = remote_hostio_open (self, NULL, "just probing",
11860 FILEIO_O_RDONLY, 0700, 0,
11864 remote_hostio_close (self, fd, &remote_errno);
11866 ps = packet_support (PACKET_vFile_open);
11869 if (ps == PACKET_DISABLE)
11871 static int warning_issued = 0;
11873 if (!warning_issued)
11875 warning (_("remote target does not support file"
11876 " transfer, attempting to access files"
11877 " from local filesystem."));
11878 warning_issued = 1;
11889 remote_fileio_errno_to_host (int errnum)
11895 case FILEIO_ENOENT:
11903 case FILEIO_EACCES:
11905 case FILEIO_EFAULT:
11909 case FILEIO_EEXIST:
11911 case FILEIO_ENODEV:
11913 case FILEIO_ENOTDIR:
11915 case FILEIO_EISDIR:
11917 case FILEIO_EINVAL:
11919 case FILEIO_ENFILE:
11921 case FILEIO_EMFILE:
11925 case FILEIO_ENOSPC:
11927 case FILEIO_ESPIPE:
11931 case FILEIO_ENOSYS:
11933 case FILEIO_ENAMETOOLONG:
11934 return ENAMETOOLONG;
11940 remote_hostio_error (int errnum)
11942 int host_error = remote_fileio_errno_to_host (errnum);
11944 if (host_error == -1)
11945 error (_("Unknown remote I/O error %d"), errnum);
11947 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11951 remote_hostio_close_cleanup (void *opaque)
11953 int fd = *(int *) opaque;
11956 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11960 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11962 struct cleanup *back_to, *close_cleanup;
11963 int retcode, fd, remote_errno, bytes, io_size;
11965 int bytes_in_buffer;
11968 struct remote_state *rs = get_remote_state ();
11970 if (!rs->remote_desc)
11971 error (_("command can only be used with remote target"));
11973 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
11975 perror_with_name (local_file);
11977 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11978 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11980 0700, 0, &remote_errno);
11982 remote_hostio_error (remote_errno);
11984 /* Send up to this many bytes at once. They won't all fit in the
11985 remote packet limit, so we'll transfer slightly fewer. */
11986 io_size = get_remote_packet_size ();
11987 buffer = (gdb_byte *) xmalloc (io_size);
11988 back_to = make_cleanup (xfree, buffer);
11990 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11992 bytes_in_buffer = 0;
11995 while (bytes_in_buffer || !saw_eof)
11999 bytes = fread (buffer + bytes_in_buffer, 1,
12000 io_size - bytes_in_buffer,
12004 if (ferror (file.get ()))
12005 error (_("Error reading %s."), local_file);
12008 /* EOF. Unless there is something still in the
12009 buffer from the last iteration, we are done. */
12011 if (bytes_in_buffer == 0)
12019 bytes += bytes_in_buffer;
12020 bytes_in_buffer = 0;
12022 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12024 offset, &remote_errno);
12027 remote_hostio_error (remote_errno);
12028 else if (retcode == 0)
12029 error (_("Remote write of %d bytes returned 0!"), bytes);
12030 else if (retcode < bytes)
12032 /* Short write. Save the rest of the read data for the next
12034 bytes_in_buffer = bytes - retcode;
12035 memmove (buffer, buffer + retcode, bytes_in_buffer);
12041 discard_cleanups (close_cleanup);
12042 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12043 remote_hostio_error (remote_errno);
12046 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12047 do_cleanups (back_to);
12051 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12053 struct cleanup *back_to, *close_cleanup;
12054 int fd, remote_errno, bytes, io_size;
12057 struct remote_state *rs = get_remote_state ();
12059 if (!rs->remote_desc)
12060 error (_("command can only be used with remote target"));
12062 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12063 remote_file, FILEIO_O_RDONLY, 0, 0,
12066 remote_hostio_error (remote_errno);
12068 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12070 perror_with_name (local_file);
12072 /* Send up to this many bytes at once. They won't all fit in the
12073 remote packet limit, so we'll transfer slightly fewer. */
12074 io_size = get_remote_packet_size ();
12075 buffer = (gdb_byte *) xmalloc (io_size);
12076 back_to = make_cleanup (xfree, buffer);
12078 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12083 bytes = remote_hostio_pread (find_target_at (process_stratum),
12084 fd, buffer, io_size, offset, &remote_errno);
12086 /* Success, but no bytes, means end-of-file. */
12089 remote_hostio_error (remote_errno);
12093 bytes = fwrite (buffer, 1, bytes, file.get ());
12095 perror_with_name (local_file);
12098 discard_cleanups (close_cleanup);
12099 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12100 remote_hostio_error (remote_errno);
12103 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12104 do_cleanups (back_to);
12108 remote_file_delete (const char *remote_file, int from_tty)
12110 int retcode, remote_errno;
12111 struct remote_state *rs = get_remote_state ();
12113 if (!rs->remote_desc)
12114 error (_("command can only be used with remote target"));
12116 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12117 NULL, remote_file, &remote_errno);
12119 remote_hostio_error (remote_errno);
12122 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12126 remote_put_command (const char *args, int from_tty)
12129 error_no_arg (_("file to put"));
12131 gdb_argv argv (args);
12132 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12133 error (_("Invalid parameters to remote put"));
12135 remote_file_put (argv[0], argv[1], from_tty);
12139 remote_get_command (const char *args, int from_tty)
12142 error_no_arg (_("file to get"));
12144 gdb_argv argv (args);
12145 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12146 error (_("Invalid parameters to remote get"));
12148 remote_file_get (argv[0], argv[1], from_tty);
12152 remote_delete_command (const char *args, int from_tty)
12155 error_no_arg (_("file to delete"));
12157 gdb_argv argv (args);
12158 if (argv[0] == NULL || argv[1] != NULL)
12159 error (_("Invalid parameters to remote delete"));
12161 remote_file_delete (argv[0], from_tty);
12165 remote_command (char *args, int from_tty)
12167 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12171 remote_can_execute_reverse (struct target_ops *self)
12173 if (packet_support (PACKET_bs) == PACKET_ENABLE
12174 || packet_support (PACKET_bc) == PACKET_ENABLE)
12181 remote_supports_non_stop (struct target_ops *self)
12187 remote_supports_disable_randomization (struct target_ops *self)
12189 /* Only supported in extended mode. */
12194 remote_supports_multi_process (struct target_ops *self)
12196 struct remote_state *rs = get_remote_state ();
12198 return remote_multi_process_p (rs);
12202 remote_supports_cond_tracepoints (void)
12204 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12208 remote_supports_cond_breakpoints (struct target_ops *self)
12210 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12214 remote_supports_fast_tracepoints (void)
12216 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12220 remote_supports_static_tracepoints (void)
12222 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12226 remote_supports_install_in_trace (void)
12228 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12232 remote_supports_enable_disable_tracepoint (struct target_ops *self)
12234 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12239 remote_supports_string_tracing (struct target_ops *self)
12241 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12245 remote_can_run_breakpoint_commands (struct target_ops *self)
12247 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12251 remote_trace_init (struct target_ops *self)
12254 remote_get_noisy_reply (&target_buf, &target_buf_size);
12255 if (strcmp (target_buf, "OK") != 0)
12256 error (_("Target does not support this command."));
12259 static void free_actions_list (char **actions_list);
12260 static void free_actions_list_cleanup_wrapper (void *);
12262 free_actions_list_cleanup_wrapper (void *al)
12264 free_actions_list ((char **) al);
12268 free_actions_list (char **actions_list)
12272 if (actions_list == 0)
12275 for (ndx = 0; actions_list[ndx]; ndx++)
12276 xfree (actions_list[ndx]);
12278 xfree (actions_list);
12281 /* Recursive routine to walk through command list including loops, and
12282 download packets for each command. */
12285 remote_download_command_source (int num, ULONGEST addr,
12286 struct command_line *cmds)
12288 struct remote_state *rs = get_remote_state ();
12289 struct command_line *cmd;
12291 for (cmd = cmds; cmd; cmd = cmd->next)
12293 QUIT; /* Allow user to bail out with ^C. */
12294 strcpy (rs->buf, "QTDPsrc:");
12295 encode_source_string (num, addr, "cmd", cmd->line,
12296 rs->buf + strlen (rs->buf),
12297 rs->buf_size - strlen (rs->buf));
12299 remote_get_noisy_reply (&target_buf, &target_buf_size);
12300 if (strcmp (target_buf, "OK"))
12301 warning (_("Target does not support source download."));
12303 if (cmd->control_type == while_control
12304 || cmd->control_type == while_stepping_control)
12306 remote_download_command_source (num, addr, *cmd->body_list);
12308 QUIT; /* Allow user to bail out with ^C. */
12309 strcpy (rs->buf, "QTDPsrc:");
12310 encode_source_string (num, addr, "cmd", "end",
12311 rs->buf + strlen (rs->buf),
12312 rs->buf_size - strlen (rs->buf));
12314 remote_get_noisy_reply (&target_buf, &target_buf_size);
12315 if (strcmp (target_buf, "OK"))
12316 warning (_("Target does not support source download."));
12322 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
12324 #define BUF_SIZE 2048
12328 char buf[BUF_SIZE];
12329 char **tdp_actions;
12330 char **stepping_actions;
12332 struct cleanup *old_chain = NULL;
12334 struct breakpoint *b = loc->owner;
12335 struct tracepoint *t = (struct tracepoint *) b;
12337 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12338 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
12340 (void) make_cleanup (free_actions_list_cleanup_wrapper,
12343 tpaddr = loc->address;
12344 sprintf_vma (addrbuf, tpaddr);
12345 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12346 addrbuf, /* address */
12347 (b->enable_state == bp_enabled ? 'E' : 'D'),
12348 t->step_count, t->pass_count);
12349 /* Fast tracepoints are mostly handled by the target, but we can
12350 tell the target how big of an instruction block should be moved
12352 if (b->type == bp_fast_tracepoint)
12354 /* Only test for support at download time; we may not know
12355 target capabilities at definition time. */
12356 if (remote_supports_fast_tracepoints ())
12358 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12360 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12361 gdb_insn_length (loc->gdbarch, tpaddr));
12363 /* If it passed validation at definition but fails now,
12364 something is very wrong. */
12365 internal_error (__FILE__, __LINE__,
12366 _("Fast tracepoint not "
12367 "valid during download"));
12370 /* Fast tracepoints are functionally identical to regular
12371 tracepoints, so don't take lack of support as a reason to
12372 give up on the trace run. */
12373 warning (_("Target does not support fast tracepoints, "
12374 "downloading %d as regular tracepoint"), b->number);
12376 else if (b->type == bp_static_tracepoint)
12378 /* Only test for support at download time; we may not know
12379 target capabilities at definition time. */
12380 if (remote_supports_static_tracepoints ())
12382 struct static_tracepoint_marker marker;
12384 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12385 strcat (buf, ":S");
12387 error (_("Static tracepoint not valid during download"));
12390 /* Fast tracepoints are functionally identical to regular
12391 tracepoints, so don't take lack of support as a reason
12392 to give up on the trace run. */
12393 error (_("Target does not support static tracepoints"));
12395 /* If the tracepoint has a conditional, make it into an agent
12396 expression and append to the definition. */
12399 /* Only test support at download time, we may not know target
12400 capabilities at definition time. */
12401 if (remote_supports_cond_tracepoints ())
12403 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12404 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12406 pkt = buf + strlen (buf);
12407 for (ndx = 0; ndx < aexpr->len; ++ndx)
12408 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12412 warning (_("Target does not support conditional tracepoints, "
12413 "ignoring tp %d cond"), b->number);
12416 if (b->commands || *default_collect)
12419 remote_get_noisy_reply (&target_buf, &target_buf_size);
12420 if (strcmp (target_buf, "OK"))
12421 error (_("Target does not support tracepoints."));
12423 /* do_single_steps (t); */
12426 for (ndx = 0; tdp_actions[ndx]; ndx++)
12428 QUIT; /* Allow user to bail out with ^C. */
12429 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12430 b->number, addrbuf, /* address */
12432 ((tdp_actions[ndx + 1] || stepping_actions)
12435 remote_get_noisy_reply (&target_buf,
12437 if (strcmp (target_buf, "OK"))
12438 error (_("Error on target while setting tracepoints."));
12441 if (stepping_actions)
12443 for (ndx = 0; stepping_actions[ndx]; ndx++)
12445 QUIT; /* Allow user to bail out with ^C. */
12446 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12447 b->number, addrbuf, /* address */
12448 ((ndx == 0) ? "S" : ""),
12449 stepping_actions[ndx],
12450 (stepping_actions[ndx + 1] ? "-" : ""));
12452 remote_get_noisy_reply (&target_buf,
12454 if (strcmp (target_buf, "OK"))
12455 error (_("Error on target while setting tracepoints."));
12459 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12461 if (b->location != NULL)
12463 strcpy (buf, "QTDPsrc:");
12464 encode_source_string (b->number, loc->address, "at",
12465 event_location_to_string (b->location.get ()),
12466 buf + strlen (buf), 2048 - strlen (buf));
12468 remote_get_noisy_reply (&target_buf, &target_buf_size);
12469 if (strcmp (target_buf, "OK"))
12470 warning (_("Target does not support source download."));
12472 if (b->cond_string)
12474 strcpy (buf, "QTDPsrc:");
12475 encode_source_string (b->number, loc->address,
12476 "cond", b->cond_string, buf + strlen (buf),
12477 2048 - strlen (buf));
12479 remote_get_noisy_reply (&target_buf, &target_buf_size);
12480 if (strcmp (target_buf, "OK"))
12481 warning (_("Target does not support source download."));
12483 remote_download_command_source (b->number, loc->address,
12484 breakpoint_commands (b));
12487 do_cleanups (old_chain);
12491 remote_can_download_tracepoint (struct target_ops *self)
12493 struct remote_state *rs = get_remote_state ();
12494 struct trace_status *ts;
12497 /* Don't try to install tracepoints until we've relocated our
12498 symbols, and fetched and merged the target's tracepoint list with
12500 if (rs->starting_up)
12503 ts = current_trace_status ();
12504 status = remote_get_trace_status (self, ts);
12506 if (status == -1 || !ts->running_known || !ts->running)
12509 /* If we are in a tracing experiment, but remote stub doesn't support
12510 installing tracepoint in trace, we have to return. */
12511 if (!remote_supports_install_in_trace ())
12519 remote_download_trace_state_variable (struct target_ops *self,
12520 struct trace_state_variable *tsv)
12522 struct remote_state *rs = get_remote_state ();
12525 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12526 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12528 p = rs->buf + strlen (rs->buf);
12529 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12530 error (_("Trace state variable name too long for tsv definition packet"));
12531 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
12534 remote_get_noisy_reply (&target_buf, &target_buf_size);
12535 if (*target_buf == '\0')
12536 error (_("Target does not support this command."));
12537 if (strcmp (target_buf, "OK") != 0)
12538 error (_("Error on target while downloading trace state variable."));
12542 remote_enable_tracepoint (struct target_ops *self,
12543 struct bp_location *location)
12545 struct remote_state *rs = get_remote_state ();
12548 sprintf_vma (addr_buf, location->address);
12549 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12550 location->owner->number, addr_buf);
12552 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12553 if (*rs->buf == '\0')
12554 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12555 if (strcmp (rs->buf, "OK") != 0)
12556 error (_("Error on target while enabling tracepoint."));
12560 remote_disable_tracepoint (struct target_ops *self,
12561 struct bp_location *location)
12563 struct remote_state *rs = get_remote_state ();
12566 sprintf_vma (addr_buf, location->address);
12567 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12568 location->owner->number, addr_buf);
12570 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12571 if (*rs->buf == '\0')
12572 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12573 if (strcmp (rs->buf, "OK") != 0)
12574 error (_("Error on target while disabling tracepoint."));
12578 remote_trace_set_readonly_regions (struct target_ops *self)
12582 bfd_size_type size;
12588 return; /* No information to give. */
12590 strcpy (target_buf, "QTro");
12591 offset = strlen (target_buf);
12592 for (s = exec_bfd->sections; s; s = s->next)
12594 char tmp1[40], tmp2[40];
12597 if ((s->flags & SEC_LOAD) == 0 ||
12598 /* (s->flags & SEC_CODE) == 0 || */
12599 (s->flags & SEC_READONLY) == 0)
12603 vma = bfd_get_section_vma (abfd, s);
12604 size = bfd_get_section_size (s);
12605 sprintf_vma (tmp1, vma);
12606 sprintf_vma (tmp2, vma + size);
12607 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12608 if (offset + sec_length + 1 > target_buf_size)
12610 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12612 Too many sections for read-only sections definition packet."));
12615 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12617 offset += sec_length;
12621 putpkt (target_buf);
12622 getpkt (&target_buf, &target_buf_size, 0);
12627 remote_trace_start (struct target_ops *self)
12629 putpkt ("QTStart");
12630 remote_get_noisy_reply (&target_buf, &target_buf_size);
12631 if (*target_buf == '\0')
12632 error (_("Target does not support this command."));
12633 if (strcmp (target_buf, "OK") != 0)
12634 error (_("Bogus reply from target: %s"), target_buf);
12638 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12640 /* Initialize it just to avoid a GCC false warning. */
12642 /* FIXME we need to get register block size some other way. */
12643 extern int trace_regblock_size;
12644 enum packet_result result;
12646 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12649 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12651 putpkt ("qTStatus");
12655 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12657 CATCH (ex, RETURN_MASK_ERROR)
12659 if (ex.error != TARGET_CLOSE_ERROR)
12661 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12664 throw_exception (ex);
12668 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12670 /* If the remote target doesn't do tracing, flag it. */
12671 if (result == PACKET_UNKNOWN)
12674 /* We're working with a live target. */
12675 ts->filename = NULL;
12678 error (_("Bogus trace status reply from target: %s"), target_buf);
12680 /* Function 'parse_trace_status' sets default value of each field of
12681 'ts' at first, so we don't have to do it here. */
12682 parse_trace_status (p, ts);
12684 return ts->running;
12688 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12689 struct uploaded_tp *utp)
12691 struct remote_state *rs = get_remote_state ();
12693 struct bp_location *loc;
12694 struct tracepoint *tp = (struct tracepoint *) bp;
12695 size_t size = get_remote_packet_size ();
12700 tp->traceframe_usage = 0;
12701 for (loc = tp->loc; loc; loc = loc->next)
12703 /* If the tracepoint was never downloaded, don't go asking for
12705 if (tp->number_on_target == 0)
12707 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12708 phex_nz (loc->address, 0));
12710 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12711 if (reply && *reply)
12714 parse_tracepoint_status (reply + 1, bp, utp);
12720 utp->hit_count = 0;
12721 utp->traceframe_usage = 0;
12722 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12723 phex_nz (utp->addr, 0));
12725 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12726 if (reply && *reply)
12729 parse_tracepoint_status (reply + 1, bp, utp);
12735 remote_trace_stop (struct target_ops *self)
12738 remote_get_noisy_reply (&target_buf, &target_buf_size);
12739 if (*target_buf == '\0')
12740 error (_("Target does not support this command."));
12741 if (strcmp (target_buf, "OK") != 0)
12742 error (_("Bogus reply from target: %s"), target_buf);
12746 remote_trace_find (struct target_ops *self,
12747 enum trace_find_type type, int num,
12748 CORE_ADDR addr1, CORE_ADDR addr2,
12751 struct remote_state *rs = get_remote_state ();
12752 char *endbuf = rs->buf + get_remote_packet_size ();
12754 int target_frameno = -1, target_tracept = -1;
12756 /* Lookups other than by absolute frame number depend on the current
12757 trace selected, so make sure it is correct on the remote end
12759 if (type != tfind_number)
12760 set_remote_traceframe ();
12763 strcpy (p, "QTFrame:");
12764 p = strchr (p, '\0');
12768 xsnprintf (p, endbuf - p, "%x", num);
12771 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12774 xsnprintf (p, endbuf - p, "tdp:%x", num);
12777 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12778 phex_nz (addr2, 0));
12780 case tfind_outside:
12781 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12782 phex_nz (addr2, 0));
12785 error (_("Unknown trace find type %d"), type);
12789 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
12790 if (*reply == '\0')
12791 error (_("Target does not support this command."));
12793 while (reply && *reply)
12798 target_frameno = (int) strtol (p, &reply, 16);
12800 error (_("Unable to parse trace frame number"));
12801 /* Don't update our remote traceframe number cache on failure
12802 to select a remote traceframe. */
12803 if (target_frameno == -1)
12808 target_tracept = (int) strtol (p, &reply, 16);
12810 error (_("Unable to parse tracepoint number"));
12812 case 'O': /* "OK"? */
12813 if (reply[1] == 'K' && reply[2] == '\0')
12816 error (_("Bogus reply from target: %s"), reply);
12819 error (_("Bogus reply from target: %s"), reply);
12822 *tpp = target_tracept;
12824 rs->remote_traceframe_number = target_frameno;
12825 return target_frameno;
12829 remote_get_trace_state_variable_value (struct target_ops *self,
12830 int tsvnum, LONGEST *val)
12832 struct remote_state *rs = get_remote_state ();
12836 set_remote_traceframe ();
12838 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12840 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12841 if (reply && *reply)
12845 unpack_varlen_hex (reply + 1, &uval);
12846 *val = (LONGEST) uval;
12854 remote_save_trace_data (struct target_ops *self, const char *filename)
12856 struct remote_state *rs = get_remote_state ();
12860 strcpy (p, "QTSave:");
12862 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12863 error (_("Remote file name too long for trace save packet"));
12864 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12867 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12868 if (*reply == '\0')
12869 error (_("Target does not support this command."));
12870 if (strcmp (reply, "OK") != 0)
12871 error (_("Bogus reply from target: %s"), reply);
12875 /* This is basically a memory transfer, but needs to be its own packet
12876 because we don't know how the target actually organizes its trace
12877 memory, plus we want to be able to ask for as much as possible, but
12878 not be unhappy if we don't get as much as we ask for. */
12881 remote_get_raw_trace_data (struct target_ops *self,
12882 gdb_byte *buf, ULONGEST offset, LONGEST len)
12884 struct remote_state *rs = get_remote_state ();
12890 strcpy (p, "qTBuffer:");
12892 p += hexnumstr (p, offset);
12894 p += hexnumstr (p, len);
12898 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12899 if (reply && *reply)
12901 /* 'l' by itself means we're at the end of the buffer and
12902 there is nothing more to get. */
12906 /* Convert the reply into binary. Limit the number of bytes to
12907 convert according to our passed-in buffer size, rather than
12908 what was returned in the packet; if the target is
12909 unexpectedly generous and gives us a bigger reply than we
12910 asked for, we don't want to crash. */
12911 rslt = hex2bin (target_buf, buf, len);
12915 /* Something went wrong, flag as an error. */
12920 remote_set_disconnected_tracing (struct target_ops *self, int val)
12922 struct remote_state *rs = get_remote_state ();
12924 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12928 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12930 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12931 if (*reply == '\0')
12932 error (_("Target does not support this command."));
12933 if (strcmp (reply, "OK") != 0)
12934 error (_("Bogus reply from target: %s"), reply);
12937 warning (_("Target does not support disconnected tracing."));
12941 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12943 struct thread_info *info = find_thread_ptid (ptid);
12945 if (info && info->priv)
12946 return info->priv->core;
12951 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12953 struct remote_state *rs = get_remote_state ();
12956 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12958 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12959 if (*reply == '\0')
12960 error (_("Target does not support this command."));
12961 if (strcmp (reply, "OK") != 0)
12962 error (_("Bogus reply from target: %s"), reply);
12965 static struct traceframe_info *
12966 remote_traceframe_info (struct target_ops *self)
12970 text = target_read_stralloc (¤t_target,
12971 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12974 struct traceframe_info *info;
12975 struct cleanup *back_to = make_cleanup (xfree, text);
12977 info = parse_traceframe_info (text);
12978 do_cleanups (back_to);
12985 /* Handle the qTMinFTPILen packet. Returns the minimum length of
12986 instruction on which a fast tracepoint may be placed. Returns -1
12987 if the packet is not supported, and 0 if the minimum instruction
12988 length is unknown. */
12991 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12993 struct remote_state *rs = get_remote_state ();
12996 /* If we're not debugging a process yet, the IPA can't be
12998 if (!target_has_execution)
13001 /* Make sure the remote is pointing at the right process. */
13002 set_general_process ();
13004 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13006 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
13007 if (*reply == '\0')
13011 ULONGEST min_insn_len;
13013 unpack_varlen_hex (reply, &min_insn_len);
13015 return (int) min_insn_len;
13020 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
13022 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13024 struct remote_state *rs = get_remote_state ();
13025 char *buf = rs->buf;
13026 char *endbuf = rs->buf + get_remote_packet_size ();
13027 enum packet_result result;
13029 gdb_assert (val >= 0 || val == -1);
13030 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13031 /* Send -1 as literal "-1" to avoid host size dependency. */
13035 buf += hexnumstr (buf, (ULONGEST) -val);
13038 buf += hexnumstr (buf, (ULONGEST) val);
13041 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
13042 result = packet_ok (rs->buf,
13043 &remote_protocol_packets[PACKET_QTBuffer_size]);
13045 if (result != PACKET_OK)
13046 warning (_("Bogus reply from target: %s"), rs->buf);
13051 remote_set_trace_notes (struct target_ops *self,
13052 const char *user, const char *notes,
13053 const char *stop_notes)
13055 struct remote_state *rs = get_remote_state ();
13057 char *buf = rs->buf;
13058 char *endbuf = rs->buf + get_remote_packet_size ();
13061 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13064 buf += xsnprintf (buf, endbuf - buf, "user:");
13065 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13071 buf += xsnprintf (buf, endbuf - buf, "notes:");
13072 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13078 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13079 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13083 /* Ensure the buffer is terminated. */
13087 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
13088 if (*reply == '\0')
13091 if (strcmp (reply, "OK") != 0)
13092 error (_("Bogus reply from target: %s"), reply);
13098 remote_use_agent (struct target_ops *self, int use)
13100 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13102 struct remote_state *rs = get_remote_state ();
13104 /* If the stub supports QAgent. */
13105 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13107 getpkt (&rs->buf, &rs->buf_size, 0);
13109 if (strcmp (rs->buf, "OK") == 0)
13120 remote_can_use_agent (struct target_ops *self)
13122 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13125 struct btrace_target_info
13127 /* The ptid of the traced thread. */
13130 /* The obtained branch trace configuration. */
13131 struct btrace_config conf;
13134 /* Reset our idea of our target's btrace configuration. */
13137 remote_btrace_reset (void)
13139 struct remote_state *rs = get_remote_state ();
13141 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13144 /* Check whether the target supports branch tracing. */
13147 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
13149 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
13151 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
13156 case BTRACE_FORMAT_NONE:
13159 case BTRACE_FORMAT_BTS:
13160 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
13162 case BTRACE_FORMAT_PT:
13163 /* The trace is decoded on the host. Even if our target supports it,
13164 we still need to have libipt to decode the trace. */
13165 #if defined (HAVE_LIBIPT)
13166 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
13167 #else /* !defined (HAVE_LIBIPT) */
13169 #endif /* !defined (HAVE_LIBIPT) */
13172 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
13175 /* Synchronize the configuration with the target. */
13178 btrace_sync_conf (const struct btrace_config *conf)
13180 struct packet_config *packet;
13181 struct remote_state *rs;
13182 char *buf, *pos, *endbuf;
13184 rs = get_remote_state ();
13186 endbuf = buf + get_remote_packet_size ();
13188 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13189 if (packet_config_support (packet) == PACKET_ENABLE
13190 && conf->bts.size != rs->btrace_config.bts.size)
13193 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13197 getpkt (&buf, &rs->buf_size, 0);
13199 if (packet_ok (buf, packet) == PACKET_ERROR)
13201 if (buf[0] == 'E' && buf[1] == '.')
13202 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13204 error (_("Failed to configure the BTS buffer size."));
13207 rs->btrace_config.bts.size = conf->bts.size;
13210 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13211 if (packet_config_support (packet) == PACKET_ENABLE
13212 && conf->pt.size != rs->btrace_config.pt.size)
13215 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13219 getpkt (&buf, &rs->buf_size, 0);
13221 if (packet_ok (buf, packet) == PACKET_ERROR)
13223 if (buf[0] == 'E' && buf[1] == '.')
13224 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13226 error (_("Failed to configure the trace buffer size."));
13229 rs->btrace_config.pt.size = conf->pt.size;
13233 /* Read the current thread's btrace configuration from the target and
13234 store it into CONF. */
13237 btrace_read_config (struct btrace_config *conf)
13241 xml = target_read_stralloc (¤t_target,
13242 TARGET_OBJECT_BTRACE_CONF, "");
13245 struct cleanup *cleanup;
13247 cleanup = make_cleanup (xfree, xml);
13248 parse_xml_btrace_conf (conf, xml);
13249 do_cleanups (cleanup);
13253 /* Maybe reopen target btrace. */
13256 remote_btrace_maybe_reopen (void)
13258 struct remote_state *rs = get_remote_state ();
13259 struct thread_info *tp;
13260 int btrace_target_pushed = 0;
13263 scoped_restore_current_thread restore_thread;
13265 ALL_NON_EXITED_THREADS (tp)
13267 set_general_thread (tp->ptid);
13269 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13270 btrace_read_config (&rs->btrace_config);
13272 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13275 #if !defined (HAVE_LIBIPT)
13276 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13281 warning (_("GDB does not support Intel Processor Trace. "
13282 "\"record\" will not work in this session."));
13287 #endif /* !defined (HAVE_LIBIPT) */
13289 /* Push target, once, but before anything else happens. This way our
13290 changes to the threads will be cleaned up by unpushing the target
13291 in case btrace_read_config () throws. */
13292 if (!btrace_target_pushed)
13294 btrace_target_pushed = 1;
13295 record_btrace_push_target ();
13296 printf_filtered (_("Target is recording using %s.\n"),
13297 btrace_format_string (rs->btrace_config.format));
13300 tp->btrace.target = XCNEW (struct btrace_target_info);
13301 tp->btrace.target->ptid = tp->ptid;
13302 tp->btrace.target->conf = rs->btrace_config;
13306 /* Enable branch tracing. */
13308 static struct btrace_target_info *
13309 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13310 const struct btrace_config *conf)
13312 struct btrace_target_info *tinfo = NULL;
13313 struct packet_config *packet = NULL;
13314 struct remote_state *rs = get_remote_state ();
13315 char *buf = rs->buf;
13316 char *endbuf = rs->buf + get_remote_packet_size ();
13318 switch (conf->format)
13320 case BTRACE_FORMAT_BTS:
13321 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13324 case BTRACE_FORMAT_PT:
13325 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13329 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13330 error (_("Target does not support branch tracing."));
13332 btrace_sync_conf (conf);
13334 set_general_thread (ptid);
13336 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13338 getpkt (&rs->buf, &rs->buf_size, 0);
13340 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13342 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13343 error (_("Could not enable branch tracing for %s: %s"),
13344 target_pid_to_str (ptid), rs->buf + 2);
13346 error (_("Could not enable branch tracing for %s."),
13347 target_pid_to_str (ptid));
13350 tinfo = XCNEW (struct btrace_target_info);
13351 tinfo->ptid = ptid;
13353 /* If we fail to read the configuration, we lose some information, but the
13354 tracing itself is not impacted. */
13357 btrace_read_config (&tinfo->conf);
13359 CATCH (err, RETURN_MASK_ERROR)
13361 if (err.message != NULL)
13362 warning ("%s", err.message);
13369 /* Disable branch tracing. */
13372 remote_disable_btrace (struct target_ops *self,
13373 struct btrace_target_info *tinfo)
13375 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13376 struct remote_state *rs = get_remote_state ();
13377 char *buf = rs->buf;
13378 char *endbuf = rs->buf + get_remote_packet_size ();
13380 if (packet_config_support (packet) != PACKET_ENABLE)
13381 error (_("Target does not support branch tracing."));
13383 set_general_thread (tinfo->ptid);
13385 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13387 getpkt (&rs->buf, &rs->buf_size, 0);
13389 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13391 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13392 error (_("Could not disable branch tracing for %s: %s"),
13393 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13395 error (_("Could not disable branch tracing for %s."),
13396 target_pid_to_str (tinfo->ptid));
13402 /* Teardown branch tracing. */
13405 remote_teardown_btrace (struct target_ops *self,
13406 struct btrace_target_info *tinfo)
13408 /* We must not talk to the target during teardown. */
13412 /* Read the branch trace. */
13414 static enum btrace_error
13415 remote_read_btrace (struct target_ops *self,
13416 struct btrace_data *btrace,
13417 struct btrace_target_info *tinfo,
13418 enum btrace_read_type type)
13420 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13421 struct cleanup *cleanup;
13425 if (packet_config_support (packet) != PACKET_ENABLE)
13426 error (_("Target does not support branch tracing."));
13428 #if !defined(HAVE_LIBEXPAT)
13429 error (_("Cannot process branch tracing result. XML parsing not supported."));
13434 case BTRACE_READ_ALL:
13437 case BTRACE_READ_NEW:
13440 case BTRACE_READ_DELTA:
13444 internal_error (__FILE__, __LINE__,
13445 _("Bad branch tracing read type: %u."),
13446 (unsigned int) type);
13449 xml = target_read_stralloc (¤t_target,
13450 TARGET_OBJECT_BTRACE, annex);
13452 return BTRACE_ERR_UNKNOWN;
13454 cleanup = make_cleanup (xfree, xml);
13455 parse_xml_btrace (btrace, xml);
13456 do_cleanups (cleanup);
13458 return BTRACE_ERR_NONE;
13461 static const struct btrace_config *
13462 remote_btrace_conf (struct target_ops *self,
13463 const struct btrace_target_info *tinfo)
13465 return &tinfo->conf;
13469 remote_augmented_libraries_svr4_read (struct target_ops *self)
13471 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13475 /* Implementation of to_load. */
13478 remote_load (struct target_ops *self, const char *name, int from_tty)
13480 generic_load (name, from_tty);
13483 /* Accepts an integer PID; returns a string representing a file that
13484 can be opened on the remote side to get the symbols for the child
13485 process. Returns NULL if the operation is not supported. */
13488 remote_pid_to_exec_file (struct target_ops *self, int pid)
13490 static char *filename = NULL;
13491 struct inferior *inf;
13492 char *annex = NULL;
13494 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13497 if (filename != NULL)
13500 inf = find_inferior_pid (pid);
13502 internal_error (__FILE__, __LINE__,
13503 _("not currently attached to process %d"), pid);
13505 if (!inf->fake_pid_p)
13507 const int annex_size = 9;
13509 annex = (char *) alloca (annex_size);
13510 xsnprintf (annex, annex_size, "%x", pid);
13513 filename = target_read_stralloc (¤t_target,
13514 TARGET_OBJECT_EXEC_FILE, annex);
13519 /* Implement the to_can_do_single_step target_ops method. */
13522 remote_can_do_single_step (struct target_ops *ops)
13524 /* We can only tell whether target supports single step or not by
13525 supported s and S vCont actions if the stub supports vContSupported
13526 feature. If the stub doesn't support vContSupported feature,
13527 we have conservatively to think target doesn't supports single
13529 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13531 struct remote_state *rs = get_remote_state ();
13533 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13534 remote_vcont_probe (rs);
13536 return rs->supports_vCont.s && rs->supports_vCont.S;
13542 /* Implementation of the to_execution_direction method for the remote
13545 static enum exec_direction_kind
13546 remote_execution_direction (struct target_ops *self)
13548 struct remote_state *rs = get_remote_state ();
13550 return rs->last_resume_exec_dir;
13553 /* Return pointer to the thread_info struct which corresponds to
13554 THREAD_HANDLE (having length HANDLE_LEN). */
13556 static struct thread_info *
13557 remote_thread_handle_to_thread_info (struct target_ops *ops,
13558 const gdb_byte *thread_handle,
13560 struct inferior *inf)
13562 struct thread_info *tp;
13564 ALL_NON_EXITED_THREADS (tp)
13566 struct private_thread_info *priv = get_private_info_thread (tp);
13568 if (tp->inf == inf && priv != NULL)
13570 if (handle_len != priv->thread_handle->size ())
13571 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13572 handle_len, priv->thread_handle->size ());
13573 if (memcmp (thread_handle, priv->thread_handle->data (),
13583 init_remote_ops (void)
13585 remote_ops.to_shortname = "remote";
13586 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13587 remote_ops.to_doc =
13588 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13589 Specify the serial device it is connected to\n\
13590 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13591 remote_ops.to_open = remote_open;
13592 remote_ops.to_close = remote_close;
13593 remote_ops.to_detach = remote_detach;
13594 remote_ops.to_disconnect = remote_disconnect;
13595 remote_ops.to_resume = remote_resume;
13596 remote_ops.to_commit_resume = remote_commit_resume;
13597 remote_ops.to_wait = remote_wait;
13598 remote_ops.to_fetch_registers = remote_fetch_registers;
13599 remote_ops.to_store_registers = remote_store_registers;
13600 remote_ops.to_prepare_to_store = remote_prepare_to_store;
13601 remote_ops.to_files_info = remote_files_info;
13602 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13603 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13604 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13605 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13606 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13607 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13608 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13609 remote_ops.to_stopped_data_address = remote_stopped_data_address;
13610 remote_ops.to_watchpoint_addr_within_range =
13611 remote_watchpoint_addr_within_range;
13612 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13613 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13614 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13615 remote_ops.to_region_ok_for_hw_watchpoint
13616 = remote_region_ok_for_hw_watchpoint;
13617 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13618 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13619 remote_ops.to_kill = remote_kill;
13620 remote_ops.to_load = remote_load;
13621 remote_ops.to_mourn_inferior = remote_mourn;
13622 remote_ops.to_pass_signals = remote_pass_signals;
13623 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13624 remote_ops.to_program_signals = remote_program_signals;
13625 remote_ops.to_thread_alive = remote_thread_alive;
13626 remote_ops.to_thread_name = remote_thread_name;
13627 remote_ops.to_update_thread_list = remote_update_thread_list;
13628 remote_ops.to_pid_to_str = remote_pid_to_str;
13629 remote_ops.to_extra_thread_info = remote_threads_extra_info;
13630 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13631 remote_ops.to_stop = remote_stop;
13632 remote_ops.to_interrupt = remote_interrupt;
13633 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13634 remote_ops.to_xfer_partial = remote_xfer_partial;
13635 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
13636 remote_ops.to_rcmd = remote_rcmd;
13637 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13638 remote_ops.to_log_command = serial_log_command;
13639 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13640 remote_ops.to_stratum = process_stratum;
13641 remote_ops.to_has_all_memory = default_child_has_all_memory;
13642 remote_ops.to_has_memory = default_child_has_memory;
13643 remote_ops.to_has_stack = default_child_has_stack;
13644 remote_ops.to_has_registers = default_child_has_registers;
13645 remote_ops.to_has_execution = default_child_has_execution;
13646 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
13647 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13648 remote_ops.to_magic = OPS_MAGIC;
13649 remote_ops.to_memory_map = remote_memory_map;
13650 remote_ops.to_flash_erase = remote_flash_erase;
13651 remote_ops.to_flash_done = remote_flash_done;
13652 remote_ops.to_read_description = remote_read_description;
13653 remote_ops.to_search_memory = remote_search_memory;
13654 remote_ops.to_can_async_p = remote_can_async_p;
13655 remote_ops.to_is_async_p = remote_is_async_p;
13656 remote_ops.to_async = remote_async;
13657 remote_ops.to_thread_events = remote_thread_events;
13658 remote_ops.to_can_do_single_step = remote_can_do_single_step;
13659 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13660 remote_ops.to_terminal_ours = remote_terminal_ours;
13661 remote_ops.to_supports_non_stop = remote_supports_non_stop;
13662 remote_ops.to_supports_multi_process = remote_supports_multi_process;
13663 remote_ops.to_supports_disable_randomization
13664 = remote_supports_disable_randomization;
13665 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13666 remote_ops.to_fileio_open = remote_hostio_open;
13667 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13668 remote_ops.to_fileio_pread = remote_hostio_pread;
13669 remote_ops.to_fileio_fstat = remote_hostio_fstat;
13670 remote_ops.to_fileio_close = remote_hostio_close;
13671 remote_ops.to_fileio_unlink = remote_hostio_unlink;
13672 remote_ops.to_fileio_readlink = remote_hostio_readlink;
13673 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13674 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13675 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13676 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13677 remote_ops.to_trace_init = remote_trace_init;
13678 remote_ops.to_download_tracepoint = remote_download_tracepoint;
13679 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13680 remote_ops.to_download_trace_state_variable
13681 = remote_download_trace_state_variable;
13682 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13683 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13684 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13685 remote_ops.to_trace_start = remote_trace_start;
13686 remote_ops.to_get_trace_status = remote_get_trace_status;
13687 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13688 remote_ops.to_trace_stop = remote_trace_stop;
13689 remote_ops.to_trace_find = remote_trace_find;
13690 remote_ops.to_get_trace_state_variable_value
13691 = remote_get_trace_state_variable_value;
13692 remote_ops.to_save_trace_data = remote_save_trace_data;
13693 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13694 remote_ops.to_upload_trace_state_variables
13695 = remote_upload_trace_state_variables;
13696 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13697 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13698 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13699 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13700 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13701 remote_ops.to_set_trace_notes = remote_set_trace_notes;
13702 remote_ops.to_core_of_thread = remote_core_of_thread;
13703 remote_ops.to_verify_memory = remote_verify_memory;
13704 remote_ops.to_get_tib_address = remote_get_tib_address;
13705 remote_ops.to_set_permissions = remote_set_permissions;
13706 remote_ops.to_static_tracepoint_marker_at
13707 = remote_static_tracepoint_marker_at;
13708 remote_ops.to_static_tracepoint_markers_by_strid
13709 = remote_static_tracepoint_markers_by_strid;
13710 remote_ops.to_traceframe_info = remote_traceframe_info;
13711 remote_ops.to_use_agent = remote_use_agent;
13712 remote_ops.to_can_use_agent = remote_can_use_agent;
13713 remote_ops.to_supports_btrace = remote_supports_btrace;
13714 remote_ops.to_enable_btrace = remote_enable_btrace;
13715 remote_ops.to_disable_btrace = remote_disable_btrace;
13716 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13717 remote_ops.to_read_btrace = remote_read_btrace;
13718 remote_ops.to_btrace_conf = remote_btrace_conf;
13719 remote_ops.to_augmented_libraries_svr4_read =
13720 remote_augmented_libraries_svr4_read;
13721 remote_ops.to_follow_fork = remote_follow_fork;
13722 remote_ops.to_follow_exec = remote_follow_exec;
13723 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13724 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13725 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13726 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13727 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13728 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13729 remote_ops.to_execution_direction = remote_execution_direction;
13730 remote_ops.to_thread_handle_to_thread_info =
13731 remote_thread_handle_to_thread_info;
13734 /* Set up the extended remote vector by making a copy of the standard
13735 remote vector and adding to it. */
13738 init_extended_remote_ops (void)
13740 extended_remote_ops = remote_ops;
13742 extended_remote_ops.to_shortname = "extended-remote";
13743 extended_remote_ops.to_longname =
13744 "Extended remote serial target in gdb-specific protocol";
13745 extended_remote_ops.to_doc =
13746 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13747 Specify the serial device it is connected to (e.g. /dev/ttya).";
13748 extended_remote_ops.to_open = extended_remote_open;
13749 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13750 extended_remote_ops.to_detach = extended_remote_detach;
13751 extended_remote_ops.to_attach = extended_remote_attach;
13752 extended_remote_ops.to_post_attach = extended_remote_post_attach;
13753 extended_remote_ops.to_supports_disable_randomization
13754 = extended_remote_supports_disable_randomization;
13758 remote_can_async_p (struct target_ops *ops)
13760 struct remote_state *rs = get_remote_state ();
13762 /* We don't go async if the user has explicitly prevented it with the
13763 "maint set target-async" command. */
13764 if (!target_async_permitted)
13767 /* We're async whenever the serial device is. */
13768 return serial_can_async_p (rs->remote_desc);
13772 remote_is_async_p (struct target_ops *ops)
13774 struct remote_state *rs = get_remote_state ();
13776 if (!target_async_permitted)
13777 /* We only enable async when the user specifically asks for it. */
13780 /* We're async whenever the serial device is. */
13781 return serial_is_async_p (rs->remote_desc);
13784 /* Pass the SERIAL event on and up to the client. One day this code
13785 will be able to delay notifying the client of an event until the
13786 point where an entire packet has been received. */
13788 static serial_event_ftype remote_async_serial_handler;
13791 remote_async_serial_handler (struct serial *scb, void *context)
13793 /* Don't propogate error information up to the client. Instead let
13794 the client find out about the error by querying the target. */
13795 inferior_event_handler (INF_REG_EVENT, NULL);
13799 remote_async_inferior_event_handler (gdb_client_data data)
13801 inferior_event_handler (INF_REG_EVENT, NULL);
13805 remote_async (struct target_ops *ops, int enable)
13807 struct remote_state *rs = get_remote_state ();
13811 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13813 /* If there are pending events in the stop reply queue tell the
13814 event loop to process them. */
13815 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13816 mark_async_event_handler (remote_async_inferior_event_token);
13817 /* For simplicity, below we clear the pending events token
13818 without remembering whether it is marked, so here we always
13819 mark it. If there's actually no pending notification to
13820 process, this ends up being a no-op (other than a spurious
13821 event-loop wakeup). */
13822 if (target_is_non_stop_p ())
13823 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13827 serial_async (rs->remote_desc, NULL, NULL);
13828 /* If the core is disabling async, it doesn't want to be
13829 disturbed with target events. Clear all async event sources
13831 clear_async_event_handler (remote_async_inferior_event_token);
13832 if (target_is_non_stop_p ())
13833 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13837 /* Implementation of the to_thread_events method. */
13840 remote_thread_events (struct target_ops *ops, int enable)
13842 struct remote_state *rs = get_remote_state ();
13843 size_t size = get_remote_packet_size ();
13845 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13848 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13850 getpkt (&rs->buf, &rs->buf_size, 0);
13852 switch (packet_ok (rs->buf,
13853 &remote_protocol_packets[PACKET_QThreadEvents]))
13856 if (strcmp (rs->buf, "OK") != 0)
13857 error (_("Remote refused setting thread events: %s"), rs->buf);
13860 warning (_("Remote failure reply: %s"), rs->buf);
13862 case PACKET_UNKNOWN:
13868 set_remote_cmd (char *args, int from_tty)
13870 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13874 show_remote_cmd (char *args, int from_tty)
13876 /* We can't just use cmd_show_list here, because we want to skip
13877 the redundant "show remote Z-packet" and the legacy aliases. */
13878 struct cmd_list_element *list = remote_show_cmdlist;
13879 struct ui_out *uiout = current_uiout;
13881 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13882 for (; list != NULL; list = list->next)
13883 if (strcmp (list->name, "Z-packet") == 0)
13885 else if (list->type == not_set_cmd)
13886 /* Alias commands are exactly like the original, except they
13887 don't have the normal type. */
13891 ui_out_emit_tuple option_emitter (uiout, "option");
13893 uiout->field_string ("name", list->name);
13894 uiout->text (": ");
13895 if (list->type == show_cmd)
13896 do_show_command (NULL, from_tty, list);
13898 cmd_func (list, NULL, from_tty);
13903 /* Function to be called whenever a new objfile (shlib) is detected. */
13905 remote_new_objfile (struct objfile *objfile)
13907 struct remote_state *rs = get_remote_state ();
13909 if (rs->remote_desc != 0) /* Have a remote connection. */
13910 remote_check_symbols ();
13913 /* Pull all the tracepoints defined on the target and create local
13914 data structures representing them. We don't want to create real
13915 tracepoints yet, we don't want to mess up the user's existing
13919 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13921 struct remote_state *rs = get_remote_state ();
13924 /* Ask for a first packet of tracepoint definition. */
13926 getpkt (&rs->buf, &rs->buf_size, 0);
13928 while (*p && *p != 'l')
13930 parse_tracepoint_definition (p, utpp);
13931 /* Ask for another packet of tracepoint definition. */
13933 getpkt (&rs->buf, &rs->buf_size, 0);
13940 remote_upload_trace_state_variables (struct target_ops *self,
13941 struct uploaded_tsv **utsvp)
13943 struct remote_state *rs = get_remote_state ();
13946 /* Ask for a first packet of variable definition. */
13948 getpkt (&rs->buf, &rs->buf_size, 0);
13950 while (*p && *p != 'l')
13952 parse_tsv_definition (p, utsvp);
13953 /* Ask for another packet of variable definition. */
13955 getpkt (&rs->buf, &rs->buf_size, 0);
13961 /* The "set/show range-stepping" show hook. */
13964 show_range_stepping (struct ui_file *file, int from_tty,
13965 struct cmd_list_element *c,
13968 fprintf_filtered (file,
13969 _("Debugger's willingness to use range stepping "
13970 "is %s.\n"), value);
13973 /* The "set/show range-stepping" set hook. */
13976 set_range_stepping (char *ignore_args, int from_tty,
13977 struct cmd_list_element *c)
13979 struct remote_state *rs = get_remote_state ();
13981 /* Whene enabling, check whether range stepping is actually
13982 supported by the target, and warn if not. */
13983 if (use_range_stepping)
13985 if (rs->remote_desc != NULL)
13987 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13988 remote_vcont_probe (rs);
13990 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13991 && rs->supports_vCont.r)
13995 warning (_("Range stepping is not supported by the current target"));
14000 _initialize_remote (void)
14002 struct cmd_list_element *cmd;
14003 const char *cmd_name;
14005 /* architecture specific data */
14006 remote_gdbarch_data_handle =
14007 gdbarch_data_register_post_init (init_remote_state);
14008 remote_g_packet_data_handle =
14009 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14012 = register_program_space_data_with_cleanup (NULL,
14013 remote_pspace_data_cleanup);
14015 /* Initialize the per-target state. At the moment there is only one
14016 of these, not one per target. Only one target is active at a
14018 remote_state = new_remote_state ();
14020 init_remote_ops ();
14021 add_target (&remote_ops);
14023 init_extended_remote_ops ();
14024 add_target (&extended_remote_ops);
14026 /* Hook into new objfile notification. */
14027 observer_attach_new_objfile (remote_new_objfile);
14028 /* We're no longer interested in notification events of an inferior
14030 observer_attach_inferior_exit (discard_pending_stop_replies);
14033 init_remote_threadtests ();
14036 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14037 /* set/show remote ... */
14039 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14040 Remote protocol specific variables\n\
14041 Configure various remote-protocol specific variables such as\n\
14042 the packets being used"),
14043 &remote_set_cmdlist, "set remote ",
14044 0 /* allow-unknown */, &setlist);
14045 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14046 Remote protocol specific variables\n\
14047 Configure various remote-protocol specific variables such as\n\
14048 the packets being used"),
14049 &remote_show_cmdlist, "show remote ",
14050 0 /* allow-unknown */, &showlist);
14052 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14053 Compare section data on target to the exec file.\n\
14054 Argument is a single section name (default: all loaded sections).\n\
14055 To compare only read-only loaded sections, specify the -r option."),
14058 add_cmd ("packet", class_maintenance, packet_command, _("\
14059 Send an arbitrary packet to a remote target.\n\
14060 maintenance packet TEXT\n\
14061 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14062 this command sends the string TEXT to the inferior, and displays the\n\
14063 response packet. GDB supplies the initial `$' character, and the\n\
14064 terminating `#' character and checksum."),
14067 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14068 Set whether to send break if interrupted."), _("\
14069 Show whether to send break if interrupted."), _("\
14070 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14071 set_remotebreak, show_remotebreak,
14072 &setlist, &showlist);
14073 cmd_name = "remotebreak";
14074 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14075 deprecate_cmd (cmd, "set remote interrupt-sequence");
14076 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14077 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14078 deprecate_cmd (cmd, "show remote interrupt-sequence");
14080 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14081 interrupt_sequence_modes, &interrupt_sequence_mode,
14083 Set interrupt sequence to remote target."), _("\
14084 Show interrupt sequence to remote target."), _("\
14085 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14086 NULL, show_interrupt_sequence,
14087 &remote_set_cmdlist,
14088 &remote_show_cmdlist);
14090 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14091 &interrupt_on_connect, _("\
14092 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14093 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14094 If set, interrupt sequence is sent to remote target."),
14096 &remote_set_cmdlist, &remote_show_cmdlist);
14098 /* Install commands for configuring memory read/write packets. */
14100 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14101 Set the maximum number of bytes per memory write packet (deprecated)."),
14103 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14104 Show the maximum number of bytes per memory write packet (deprecated)."),
14106 add_cmd ("memory-write-packet-size", no_class,
14107 set_memory_write_packet_size, _("\
14108 Set the maximum number of bytes per memory-write packet.\n\
14109 Specify the number of bytes in a packet or 0 (zero) for the\n\
14110 default packet size. The actual limit is further reduced\n\
14111 dependent on the target. Specify ``fixed'' to disable the\n\
14112 further restriction and ``limit'' to enable that restriction."),
14113 &remote_set_cmdlist);
14114 add_cmd ("memory-read-packet-size", no_class,
14115 set_memory_read_packet_size, _("\
14116 Set the maximum number of bytes per memory-read packet.\n\
14117 Specify the number of bytes in a packet or 0 (zero) for the\n\
14118 default packet size. The actual limit is further reduced\n\
14119 dependent on the target. Specify ``fixed'' to disable the\n\
14120 further restriction and ``limit'' to enable that restriction."),
14121 &remote_set_cmdlist);
14122 add_cmd ("memory-write-packet-size", no_class,
14123 show_memory_write_packet_size,
14124 _("Show the maximum number of bytes per memory-write packet."),
14125 &remote_show_cmdlist);
14126 add_cmd ("memory-read-packet-size", no_class,
14127 show_memory_read_packet_size,
14128 _("Show the maximum number of bytes per memory-read packet."),
14129 &remote_show_cmdlist);
14131 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14132 &remote_hw_watchpoint_limit, _("\
14133 Set the maximum number of target hardware watchpoints."), _("\
14134 Show the maximum number of target hardware watchpoints."), _("\
14135 Specify a negative limit for unlimited."),
14136 NULL, NULL, /* FIXME: i18n: The maximum
14137 number of target hardware
14138 watchpoints is %s. */
14139 &remote_set_cmdlist, &remote_show_cmdlist);
14140 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14141 &remote_hw_watchpoint_length_limit, _("\
14142 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14143 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14144 Specify a negative limit for unlimited."),
14145 NULL, NULL, /* FIXME: i18n: The maximum
14146 length (in bytes) of a target
14147 hardware watchpoint is %s. */
14148 &remote_set_cmdlist, &remote_show_cmdlist);
14149 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14150 &remote_hw_breakpoint_limit, _("\
14151 Set the maximum number of target hardware breakpoints."), _("\
14152 Show the maximum number of target hardware breakpoints."), _("\
14153 Specify a negative limit for unlimited."),
14154 NULL, NULL, /* FIXME: i18n: The maximum
14155 number of target hardware
14156 breakpoints is %s. */
14157 &remote_set_cmdlist, &remote_show_cmdlist);
14159 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14160 &remote_address_size, _("\
14161 Set the maximum size of the address (in bits) in a memory packet."), _("\
14162 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14164 NULL, /* FIXME: i18n: */
14165 &setlist, &showlist);
14167 init_all_packet_configs ();
14169 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14170 "X", "binary-download", 1);
14172 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14173 "vCont", "verbose-resume", 0);
14175 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14176 "QPassSignals", "pass-signals", 0);
14178 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14179 "QCatchSyscalls", "catch-syscalls", 0);
14181 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14182 "QProgramSignals", "program-signals", 0);
14184 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14185 "QStartupWithShell", "startup-with-shell", 0);
14187 add_packet_config_cmd (&remote_protocol_packets
14188 [PACKET_QEnvironmentHexEncoded],
14189 "QEnvironmentHexEncoded", "environment-hex-encoded",
14192 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14193 "QEnvironmentReset", "environment-reset",
14196 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14197 "QEnvironmentUnset", "environment-unset",
14200 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14201 "qSymbol", "symbol-lookup", 0);
14203 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14204 "P", "set-register", 1);
14206 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14207 "p", "fetch-register", 1);
14209 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14210 "Z0", "software-breakpoint", 0);
14212 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14213 "Z1", "hardware-breakpoint", 0);
14215 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14216 "Z2", "write-watchpoint", 0);
14218 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14219 "Z3", "read-watchpoint", 0);
14221 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14222 "Z4", "access-watchpoint", 0);
14224 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14225 "qXfer:auxv:read", "read-aux-vector", 0);
14227 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14228 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14230 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14231 "qXfer:features:read", "target-features", 0);
14233 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14234 "qXfer:libraries:read", "library-info", 0);
14236 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14237 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14239 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14240 "qXfer:memory-map:read", "memory-map", 0);
14242 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14243 "qXfer:spu:read", "read-spu-object", 0);
14245 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14246 "qXfer:spu:write", "write-spu-object", 0);
14248 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14249 "qXfer:osdata:read", "osdata", 0);
14251 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14252 "qXfer:threads:read", "threads", 0);
14254 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14255 "qXfer:siginfo:read", "read-siginfo-object", 0);
14257 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14258 "qXfer:siginfo:write", "write-siginfo-object", 0);
14260 add_packet_config_cmd
14261 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14262 "qXfer:traceframe-info:read", "traceframe-info", 0);
14264 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14265 "qXfer:uib:read", "unwind-info-block", 0);
14267 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14268 "qGetTLSAddr", "get-thread-local-storage-address",
14271 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14272 "qGetTIBAddr", "get-thread-information-block-address",
14275 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14276 "bc", "reverse-continue", 0);
14278 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14279 "bs", "reverse-step", 0);
14281 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14282 "qSupported", "supported-packets", 0);
14284 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14285 "qSearch:memory", "search-memory", 0);
14287 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14288 "qTStatus", "trace-status", 0);
14290 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14291 "vFile:setfs", "hostio-setfs", 0);
14293 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14294 "vFile:open", "hostio-open", 0);
14296 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14297 "vFile:pread", "hostio-pread", 0);
14299 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14300 "vFile:pwrite", "hostio-pwrite", 0);
14302 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14303 "vFile:close", "hostio-close", 0);
14305 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14306 "vFile:unlink", "hostio-unlink", 0);
14308 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14309 "vFile:readlink", "hostio-readlink", 0);
14311 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14312 "vFile:fstat", "hostio-fstat", 0);
14314 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14315 "vAttach", "attach", 0);
14317 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14320 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14321 "QStartNoAckMode", "noack", 0);
14323 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14324 "vKill", "kill", 0);
14326 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14327 "qAttached", "query-attached", 0);
14329 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14330 "ConditionalTracepoints",
14331 "conditional-tracepoints", 0);
14333 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14334 "ConditionalBreakpoints",
14335 "conditional-breakpoints", 0);
14337 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14338 "BreakpointCommands",
14339 "breakpoint-commands", 0);
14341 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14342 "FastTracepoints", "fast-tracepoints", 0);
14344 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14345 "TracepointSource", "TracepointSource", 0);
14347 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14348 "QAllow", "allow", 0);
14350 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14351 "StaticTracepoints", "static-tracepoints", 0);
14353 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14354 "InstallInTrace", "install-in-trace", 0);
14356 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14357 "qXfer:statictrace:read", "read-sdata-object", 0);
14359 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14360 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14362 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14363 "QDisableRandomization", "disable-randomization", 0);
14365 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14366 "QAgent", "agent", 0);
14368 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14369 "QTBuffer:size", "trace-buffer-size", 0);
14371 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14372 "Qbtrace:off", "disable-btrace", 0);
14374 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14375 "Qbtrace:bts", "enable-btrace-bts", 0);
14377 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14378 "Qbtrace:pt", "enable-btrace-pt", 0);
14380 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14381 "qXfer:btrace", "read-btrace", 0);
14383 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14384 "qXfer:btrace-conf", "read-btrace-conf", 0);
14386 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14387 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14389 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14390 "multiprocess-feature", "multiprocess-feature", 0);
14392 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14393 "swbreak-feature", "swbreak-feature", 0);
14395 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14396 "hwbreak-feature", "hwbreak-feature", 0);
14398 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14399 "fork-event-feature", "fork-event-feature", 0);
14401 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14402 "vfork-event-feature", "vfork-event-feature", 0);
14404 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14405 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14407 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14408 "vContSupported", "verbose-resume-supported", 0);
14410 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14411 "exec-event-feature", "exec-event-feature", 0);
14413 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14414 "vCtrlC", "ctrl-c", 0);
14416 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14417 "QThreadEvents", "thread-events", 0);
14419 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14420 "N stop reply", "no-resumed-stop-reply", 0);
14422 /* Assert that we've registered "set remote foo-packet" commands
14423 for all packet configs. */
14427 for (i = 0; i < PACKET_MAX; i++)
14429 /* Ideally all configs would have a command associated. Some
14430 still don't though. */
14435 case PACKET_QNonStop:
14436 case PACKET_EnableDisableTracepoints_feature:
14437 case PACKET_tracenz_feature:
14438 case PACKET_DisconnectedTracing_feature:
14439 case PACKET_augmented_libraries_svr4_read_feature:
14441 /* Additions to this list need to be well justified:
14442 pre-existing packets are OK; new packets are not. */
14450 /* This catches both forgetting to add a config command, and
14451 forgetting to remove a packet from the exception list. */
14452 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14456 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14457 Z sub-packet has its own set and show commands, but users may
14458 have sets to this variable in their .gdbinit files (or in their
14460 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14461 &remote_Z_packet_detect, _("\
14462 Set use of remote protocol `Z' packets"), _("\
14463 Show use of remote protocol `Z' packets "), _("\
14464 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14466 set_remote_protocol_Z_packet_cmd,
14467 show_remote_protocol_Z_packet_cmd,
14468 /* FIXME: i18n: Use of remote protocol
14469 `Z' packets is %s. */
14470 &remote_set_cmdlist, &remote_show_cmdlist);
14472 add_prefix_cmd ("remote", class_files, remote_command, _("\
14473 Manipulate files on the remote system\n\
14474 Transfer files to and from the remote target system."),
14475 &remote_cmdlist, "remote ",
14476 0 /* allow-unknown */, &cmdlist);
14478 add_cmd ("put", class_files, remote_put_command,
14479 _("Copy a local file to the remote system."),
14482 add_cmd ("get", class_files, remote_get_command,
14483 _("Copy a remote file to the local system."),
14486 add_cmd ("delete", class_files, remote_delete_command,
14487 _("Delete a remote file."),
14490 add_setshow_string_noescape_cmd ("exec-file", class_files,
14491 &remote_exec_file_var, _("\
14492 Set the remote pathname for \"run\""), _("\
14493 Show the remote pathname for \"run\""), NULL,
14494 set_remote_exec_file,
14495 show_remote_exec_file,
14496 &remote_set_cmdlist,
14497 &remote_show_cmdlist);
14499 add_setshow_boolean_cmd ("range-stepping", class_run,
14500 &use_range_stepping, _("\
14501 Enable or disable range stepping."), _("\
14502 Show whether target-assisted range stepping is enabled."), _("\
14503 If on, and the target supports it, when stepping a source line, GDB\n\
14504 tells the target to step the corresponding range of addresses itself instead\n\
14505 of issuing multiple single-steps. This speeds up source level\n\
14506 stepping. If off, GDB always issues single-steps, even if range\n\
14507 stepping is supported by the target. The default is on."),
14508 set_range_stepping,
14509 show_range_stepping,
14513 /* Eventually initialize fileio. See fileio.c */
14514 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14516 /* Take advantage of the fact that the TID field is not used, to tag
14517 special ptids with it set to != 0. */
14518 magic_null_ptid = ptid_build (42000, -1, 1);
14519 not_sent_ptid = ptid_build (42000, -2, 1);
14520 any_thread_ptid = ptid_build (42000, 0, 1);
14522 target_buf_size = 2048;
14523 target_buf = (char *) xmalloc (target_buf_size);